Necessary and sufficient conditions for a polynomial $f(x) \in \mathbb{Z}[x]$ to be irreducible.

Question: This is not for homework, and I am not totally convinced I understand the question entirely.  Also, I'm not allowed to use the fact that $\mathbb{Z}[x]$ is a UFD.  The question asks

Show that $f(x) \in \mathbb{Z}[x]$ is irreducible if and only if $f(x)$ is either a prime integer or an irreducible polynomial in $\mathbb{Q}[x]$ such that the $\gcd$ in $\mathbb{Z}$ of the coefficients of $f(x)$ is $1$.

The part of the question I am finding confusing is the phrasing "...or an irreducible polynomial in $\mathbb{Q}[x]$ such that the $\gcd$ in $\mathbb{Z}$ of the coefficients...".  What is the $\gcd$ in $\mathbb{Z}$ of the coefficients of a polynomial in $\mathbb{Q}[x]$?  Does the author mean to multiply $f(x)$ by an integer $c$ such that the coefficients of $cf(x)$ are integers, and then look at the $\gcd$ of those coefficients?  Under this tentative assumption of what the question is asking, here is what I have so far.
If $f(x)$ is a prime integer or an irreducible polynomial in $\mathbb{Q}[x]$ such that the $\gcd$ in $\mathbb{Z}$ of the coefficients of $f(x)$ is $1$, then $f(x)$ is irreducible in $\mathbb{Z}[x]$ (this follows from a theorem that states: "a polynomial $f(x)$ factors as a product of polynomials of degree $m$ and $n$ in $\mathbb{Q}[x]$ if and only if $f(x)$ factors as a product of polynomials of degree $m$ and $n$ in $\mathbb{Z}[x]$").
Conversely, suppose $f(x)$ is irreducible in $\mathbb{Z}[x]$.  If $\deg (f(x)) = 0$, then it is not hard to see that $f(x)$ must be a prime integer.  If $\deg (f(x)) > 0$, then I can again use the result quoted in the last paragraph to say that $f(x)$ cannot be written as the product of polynomials of lower degree in $\mathbb{Q}[x]$ (for if it could, then $f(x)$ would be reducible in $\mathbb{Z}[x]$).  At this point, I'm not sure how to show that the $\gcd$ in $\mathbb{Z}$ of the coefficients of $f(x)$ is $1$.  I'm also a bit uneasy about the approach in general.  Critiques and hints are very welcome!
Comment: $f$ is assumed to be in $\mathbb{Z}[x]$, the condition in the question states that $f$ is irreducible as a polynomial in $\mathbb{Q}[x]$, but $f$ still has integer coefficients and so the gcd makes sense.
Comment: The author views $\mathbb{Z}[X]$ as a subset of $\mathbb{Q}[X]$. (Since $\mathbb{Z}\subset\mathbb{Q}$.) So the alternative is 1. a constant polynomial whose constant term is irreducible in $\mathbb{Z}$, or 2. a polynomial (with integer coefficients) that is irreducible in $\mathbb{Q}[X]$, and whose coefficients are coprime.
Comment: Ah, yes.  I have the attention span of a gnat apparently...
Answer: The question asks about irreducibility in $\mathbb{Q}[x]$, but the polynomial itself is in $\mathbb{Z}[x]$.  So there is always a g.c.d., without anything special happening.
As for your last question: how about a proof by contradiction?  What would happen if the g.c.d. of the coefficients were not $1$?
Comment: @tylerc0816 Not so.  If you are trying to prove that $2x+3$ is irreducible, and you don't use the fact that its coefficients are relatively prime, then you have made a mistake.  $2x+4$ is irreducible in $\mathbb{Q}[x]$ but not $\mathbb{Z}[x]$.  Oh, and this is the reason I forgot to mention for writing more detailed proofs; you see your own mistakes easier :)
Comment: I see.  If the $\gcd$ of the coefficients is not $1$ then we can pull out a prime factor, contradicting the irreducibility of $f(x)$ in $\mathbb{Z}[x]$.  Adding this into the sketch I posted above, can you see anything else glaringly wrong?
Comment: @tylerc0816 Nope, it's all correct, and shows pretty good form.  One minor quibble I have is in the first paragraph, where you say "this follows from a theorem that states..."  I'd be slightly more specific about how it follows, because it's not clear where you're using the gcd.  I know you said it's not for homework, but I'm of the philosophy that we learn to write proofs because we eventually want to communicate ideas to other humans, and humans are notorious for getting confused easily.  But otherwise, looks solid, and good job.
Comment: Thank you.  In fact I believe the assumption about the $\gcd$ is irrelevant when quoting that theorem.  More specifically, I could have said "since $f(x)$ is irreducible in $\mathbb{Q}[x]$, it cannot be written as the product of two polynomials of lower degree, and hence cannot be written as the product of polynomials in $\mathbb{Z}[x]$ of lower degree", not bringing up the assumption about the $\gcd$ at all.  I believe the assumption about the $\gcd$ is needed only for proving the other direction.


Finding an equation of two perpendicular tangent lines of a parabola

Question: A parabola would be given as the following: $y^2=4px$.
1) The question is, one wishes to find each equation for two orthogonal (perpendicular) tangent lines of a parabola.
What would be the equations?
Add: And one wishes to find the locus of the intersecting point of two orthogonal tangent lines. How would one be able to get the locus?
The book I am reading to says that $y=mx+\frac{p}{m}$ can be the equation for a tangent line of a parabola. Is this right?
2) And suppose that there is a point $P(x_0,y_0)$ outside the parabola (this parabola is the aforementioned.). Assume that from the point, two tangent lines can be drawn. For each line, then, there would be points $Q_1(x_1,y_1)$, $Q_2(x_2,y_2)$.
Then why is $y_1y=2p(x+x_1)$ and $y_2y=2p(x+x_2)$?
Edit:
I'll add one more question to 1):
Edit: Adding to 1).
Comment: For the equations in your second question, what are "$x$" and "$y$", and where are "$x_0$" and "$y_0$"?
Answer: I'm assuming you don't want any calculus involved here (too bad!), so let $\,(a,b)\,,\,(c,d)\,$ be the points on the parabola through which pass two tangent lines to it that are perpendicular:
$$\text{First tangent: we need to solve the system}\;\;\;\;y^2=4px\;\;,\;\;y-b=m(x-a)\Longrightarrow$$
$$(m(x-a)+b)^2=4px$$
$$\text{Second tangent:  we need to solve the sytem}\;\;\;\;y^2=4px\;\;,\;\;y-d=-\frac{1}{m}(x-c)\Longrightarrow$$
$$\left(-\frac{1}{m}(x-c)+d\right)^2=4px$$
Of course, solving the above take into account that
$$b^2=4pa\;\;,\;\;d^2=4pc$$
since both points were chosen to be on the parabola.
Also, remember that two straight lines (none of which is horizontal/vertical) with slopes $\,m_1\,,\,m_2\,$ are perpendicular iff $\,m_1m_2=-1\,$, and this the reason we took the second tangent's slope to be $\,-1/m\,$
Comment: $$y^2=4px\Longrightarrow 2yy'=4p\Longrightarrow y'=\frac{2p}{y}$$ and $\,y'\,$ is the slope of the tangent line in the chosen point. If you do the above with two generic points of the parabola and then use that it **must** be that ths slope of one must be minus the inverse of the other slope then you can make it easier, I guess.
Comment: How would usage of calculus simplify the matter?
Answer:
The way to answer to the questions is to ensure that the lines are tangent to the parabola, i.e. they have the same slope as the parabola in the points of contact (this is the missing piece of the answers so far).

To make things easier let's swap the coordinates:
$$x = {y^2 \over 4p}$$

The slope of the parabola is it derivative:
$$x' = {2y \over 4p} = {y \over 2p}$$

Now let's consider the tangents. We can have two generic equations with the following parameters:
$$slope = m$$
and
$$coefficient = q_1$$
for the first equation,
$$slope = {-1 \over m}$$
(perpendicular to m) and
$$coefficient = q_2$$ for the second equation.

The equations will be:
$$x = {my + q_1}$$
$$x = {-\frac{1}{m}y + q_2}$$

At this point we equate the slope of the parabola to that of the first equation:
$$y = 2mp$$
and substituting that in the equation of the parabola:
$$x = m^2p.$$

Repeating the process for the second equation:
$$y = {-2p \over m}$$
and substituting that in the equation of the parabola again:
$$x = {p \over m^2p}.$$

Substituting those values in the respective equations of the lines ensures that we find the coefficients of the tangents. For the first equation:
$$m^2p = {2m^2p + q_1}$$
$$q_1 = -m^2p$$
and for the second equation:
$$q_2 = {-p \over m^2}.$$

In total the equations of the tangents are:
$$x = my - m^2p$$
$$x = {-1\over m} y - {p \over m^2}.$$
Answer: [Edit: Greatly simplified over previous version. Plus, corrected a mis-reading of the equation.]
Parabola Fun Fact:

If a parabola with a horizontal axis has a chord with endpoints $A(x_1, y_1)$ and $B(x_2, y_2)$, then the tangent line through the point with $y$-coordinate $\frac{1}{2}(y_1+y_2)$ is parallel to $AB$.

Now, the slope of $AB$ is
$$m = \frac{y_1-y_2}{x_1-x_2} = \frac{y_1-y_2}{\frac{1}{4p}y_1^2-\frac{1}{4p}y_2^2}=\frac{4p}{y_1+y_2}$$
By the Parabola Fun Fact, $AB$ is parallel to the line tangent to the parabola at point $T$, where
$$T = \left( \frac{1}{4p} \left(\frac{y_1+y_2}{2}\right)^2, \frac{y_1+y_2}{2}\right)
= \left( \frac{\left(y_1+y_2\right)^2}{16p}, \frac{y_1+y_2}{2}\right)
= \left( \frac{p}{m^2}, \frac{2p}{m}\right)$$
We determine the equation of the tangent line using the point-slope form, $y-y_0=m(x-x_0)$:
$$\begin{align}
y - \frac{2p}{m} = m \left(x-\frac{p}{m^2}\right) \qquad \to \qquad
y = mx+\frac{p}{m}
\end{align}$$
For the perpendicular tangent, simply replace $m$ by $-1/m$:
$$y = -\frac{1}{m}x-pm$$
For the locus of points of intersection, simply solve the system of the two tangent-line equations. The result is very nice.


UIButton inside UIScrollView doesn't fire on tap

Question: UIButton inside UIScrollView doesn't fire on tap. Please help resolve it.
// Add a button
UIButton *btn1 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btn1.frame = CGRectMake(0, 0, 26, 18);
btn1.bounds = CGRectMake(0, 0, 30.0, 30.0);
[btn1 addTarget:self action:@selector(buttonClick1:)
                     forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:btn1];

- (void)buttonClick1:(id)sender {
    int dd = 4;
}

Comment: Check the height or width of the scrollView to see if it is 0, and enable `clipSubview`
Answer: I found this stuff:

But the scrollview will block the
  touches from the button unless you set
  userInteractionEnabled and
  exclusiveTouch properties to NO on the
  scrollview. But that would defeat the
  purpose of having a scrollview inside
  a button I think.

(See Can we put a UIButton in a UIScrollView and vice versa in iPhone)
But how to do it?
Say you have a UIScrollView *sv ... then
sv.userInteractionEnabled = YES;
sv.exclusiveTouch = YES;

I would also add
sv.canCancelContentTouches = YES;
sv.delaysContentTouches = YES;

Comment: canCancelContentTouches and delaysContentTouches are YES by default. ;)
Answer: You must set content size of your view. That must be greater than or equal to the content size of scrollView.
Because default size of your view is 320 x 480 (3.5" retina) and 320 x 568 (4" retina). So increasing height of view as:
self.view.frame=CGRectMake(0, 0, 320, 700);

Then adding this as the subview of your scrollView will get you to the solution.
Answer: OLD ANSWER: All I had to do in iOS 7 was set
[_scrollView setDelaysContentTouches:NO];

UPDATE: After doing a little more research it appears that if your issue is that the UIButton click seems to only be called sometimes, then that is actually probably the desired behavior inside a UIScrollView. A UIScrollView uses the delaysContentTouches property to automatically determine if the user was trying to scroll or trying to press a button inside the scroll view. I would assume it is best to not alter this behavior to default to NO since doing so will result in an inability to scroll if the user's finger is over a button.
Answer: My structure is:
-View
--ScrollView
---ContainerView

and I am using snapkit. My issue was that my ContainerView actually had a height of 0.  I was able to notice this by setting ClipsToBounds = true on the ContainerView (nothing rendered after doing this as bounds had a height of 0).
Any view out of the parent view's bounds will not receive the touch up inside events.
My fix was to set the ContainerView left right and bottom anchors equal to the View and the top equal to the ScrollView (my ScrollView's top is offset from my root View's).
Answer: I was facing this same problem, what i did was instead of adding the button to the container view, i've added it to the scroll view on top of the container view:
scrollView.insertSubview(buttonA, aboveSubview: containerView)

My structure was:
-View
--ScrollView
---ContainerView

I hope this could be of help to any one.
Comment: Would love to know why this is needed actually.. any explanation? Thanks for the tip, solved my problem.
Comment: @alasker , to be honest i do not have a explanation, but it makes me happy to know that it help you.
Answer: This works for me in iOS 10
scrollView.delaysContentTouches = false

From Apple:

A Boolean value that determines whether the scroll view delays the handling of touch-down gestures.

https://developer.apple.com/documentation/uikit/uiscrollview/1619398-delayscontenttouches
Answer: I tried all that you listed here. And also on the whole internet. But my buttons still couldn't be handled.
Finally, the only thing helped me. And I was able to keep "isUserInteractionEnabled" ON on the Scroll View.
So, how I fixed it:
1) Go to Storyboard
2) Connect ContentView and MainView between each other

3) And select width/height equality

By the way, I also have views set up in the code (it doesn't work without prev steps for me).
// sizes
let width = self.view.safeAreaLayoutGuide.layoutFrame.width
mainView.frame = CGRect(x: 0 , y: 0, width: width, height: self.view.safeAreaLayoutGuide.layoutFrame.height)
contentView.frame = CGRect(x: 0 , y: 0, width: width, height: 1000)
scrollView.frame = CGRect(x: 0 , y: 0, width: width, height: mainView.frame.height)

// constraints:
contentView.widthAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.widthAnchor).isActive = true
scrollView.widthAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.widthAnchor).isActive = true

Of course, this is not the solution like "just press two buttons and you'll solve your problem". The main reason was related to constraints & content size in my case. Just FYI, maybe it will help someone.


doorkeeper gem gives "invalid_client" after successfully validated username and password

Question: http://localhost:3000/oauth/token
{
"error": "invalid_client",
"error_description": "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method."
}

while implementing doorkeeper..
Started POST "/oauth/token" for ::1 at 2021-06-13 19:56:20 +0530
Processing by Doorkeeper::TokensController#create as /
Parameters: {"grant_type"=>"password", "username"=>"bhagwan", "password"=>"[FILTERED]"}
User Load (7.0ms) SELECT "users". FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "bhagwan"], ["LIMIT", 1]]
↳ config/initializers/doorkeeper.rb:19:in `block (2 levels) in '
Completed 401 Unauthorized in 1654ms (Views: 0.5ms | ActiveRecord: 28.7ms | Allocations: 5869)*
in doorkeeper.rb
grant_flows %w[password]

resource_owner_from_credentials do
User.find_by(email: params[:username])
&.authenticate(params[:password]) || nil
end

Comment: I think I'm running into a similar issue.
Comment: I ran into this issue and it turned out I had enabled `hash_application_secrets` for doorkeeper. Then after creating a `Doorkeeper::Application` I was grabbing the secret directly from the database - which is now a hash of the secret - and passing that hashed value as the client secret when trying to obtain a token. Doorkeeper then hashes that value again when it tries to auth the client, causing the above failure. It's one possible way for the above error to arise (I really wish I had someone to blame other than myself)
Answer: In my case, it was because the application is private by default. Had to update the application to be public with update!(confidential: false).Since Doorkeeper 5.0.0 applications are private by default (reference).
Comment: Super important answer! I could have saved me a lot time if this would have been more documented.
Comment: my god, I just spent two hours debugging this, would never have suspected this bit.
Answer: You can use skip_client_authentication_for_password_grant config option to skip client authentication for your case:
Doorkeeper.configure do
  skip_client_authentication_for_password_grant true
end

Comment: if you do this, you should be aware that `Starting from 5.5.0 RC1, Doorkeeper requires client authentication for Resource Owner Password Grant
as stated in the OAuth RFC. You have to create a new OAuth client (Doorkeeper::Application) if you didn't have it before and use
client credentials in HTTP Basic auth if you previously used this grant flow without client authentication.

To opt-out of this you could set the "skip_client_authentication_for_password_grant" configuration option
to "true", but note that this is in violation of the OAuth spec and represents a security risk.`
Answer: I was getting the same error (client_error) because i was on version 5.6.0.  when using grant_type: password
doorkeeper the authorization grant type is not supported by the authorization server

downgrading to 5.4.0 made it work. I didn't see any part in the documentation that stated this. It was really annoying to do trial and error


Flutter Firebase creating a useful instance

Question: should I call it by creating a new instance every time I need it, as in the firebase documents
like this = FirebaseAuth.instance.currentuser
or should I create this statically on another page and always call the same instance?
like this = static FirebaseAuth _auth = FirebaseAuth.instance
Page1:
_auth.currentuser
Page2:
_auth.currentuser
or should I define this as registerLazySingleton with the Get_it package in one place(I don't know get_it so this may be wrong)
Or if there is a more useful way, I would like to find out, isn't it harmful to create different instances all the time?
Answer: Calling FirebaseAuth.instance doesn't create a new instance. It just returns the current instance of the default [FirebaseApp] configured with the app.
Ideally, you wouldn't want to call FirebaseAuth.instance every time you need to access FirebaseUser object, but you can call it at least once per class to keep it clean. It shouldn't affect the performance of your app.


OR function for beautifulsoup's find_all?

Question: i'm trying to scrape a website for data, and the actual text is held in cells of alternating colors.
they alternate between "#ECEBE1" and "White", so i want to search for  with both of those. the command im thinking of would look something like
table=soup.find_all(tr, bgcolor="#ECEBE1" OR bgcolor="White",)
but im not sure if that function exists or how i would do something similar
Answer: As explained here soup can match against a list, so you can just use:
table=soup.find_all(tr, bgcolor=["#ECEBE1", "White"])

Comment: oooh sick thanks. i tried looking through the beautifulsoup documentation myself but didn't notice that.


My change-nickname command suddenly isn't working

Question: So I had this change nickname command that worked perfectly up until a few days ago, and I've been trying to figure out why it's not working, but I can't find what's wrong. Here is my code:
<code>    @commands.command(aliases=['chnick'])
    @commands.has_permissions(manage_messages=True)
    async def change_nick(self, ctx, member: discord.Member, *, nick):

        await member.edit(nick=nick)
        await ctx.send(f"Nickname for {member.mention} has been changed to {nick}")
</code>
Comment: What intents have you enabled?
Comment: This is a helpful explanation of Discord's gateway intents from the perspective of discord.py: https://discordpy.readthedocs.io/en/latest/intents.html
Comment: Statements like "it's not working" aren't helpful; there could be any conceivable reason as to why it's not working. It would help us be able to help you if you included any error messages. Though if I had to guess, as @ŁukaszKwieciński is hinting at, your bot is probably not "seeing" the user you're attempting to modify due to missing gateway intents. Relevant: [discord.py docs](https://discordpy.readthedocs.io/en/latest/api.html#intents) and [Discord docs](https://discord.com/developers/docs/topics/gateway#gateway-intents)
Comment: I'm so dumb. apparently it wasn't working because I was testing it on someone who had the same highest role as my bot lol. Thank you for your help though!!
Answer: You need your intents turned on in your bot's page.
Here is a picture that shows how to do so.
After enabling intents, you have to get the intents.
This is how you get intents on your code.
<code>intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix=prefix intents=intents)
</code>
I hope this helped best of luck on your bot.
Comment: I already had Intents enabled and I realized that my bot just didn't have the right permissions for some reason. Thank you for your help though!!


No module named 'util' in Colab

Question: I get an error when I try to import the util library in google colab. How can I fix it?
I tried :
!pip install utils

and
from util import *

but doesn't work.
Comment: `from utils import *`
Answer: You missed an 's' in utils
!pip install utils
from utils import *

No module named 'util' in Colab


Store data onto local disk without prompting the user

Question: I have a flash application which runs on web. I need to store images and audio files onto the clients local disk(don't want to store on web) without prompting the client. I have already tried with shared object. But since shared object space is limited to 100 KB per domain I am searching for alternatives.
If someone has better solutions please let me know.
Thanks.
Answer: You can't do this with the Flash Player by itself. SharedObject and FileReference/save() are intentionally designed to allow the user to have authority over local storage. It would be a security concern if users did not.
Using an AIR application, though, you can do this using File and FileStream, or EncryptedLocalStore.
Answer: I had the same problem with creating log files and writing to them
The only solution for me was to create a localhost WebService (used WCF), so i could use URLRequest to the localhost and pass data to service - which then updated file or created it.
But in your way, if you want to store things from the user to your disk, maybe you could also somehow play with the Web services. Just need to try.
Visual studio has almost complete Web service template - just edit for your purposes.
Comment: So i think there is no another option to solve this problem. Flash is strictly secured with saving data. Unless it's Adobe Air. Then it is easier, because it is has methods which allows to save data without prompting.
Comment: Thanks for the quick answer.. but I cant use WebServices as I will be hosting this application onto web and want to save data onto users local store


Spreadsheet::ParseExcel row_range differs from gnumeric

Question: I'm having trouble getting Spreadsheet::ParseExcel to parse an .xls spreadsheet generated by gnumeric, and I think the problem is with gnumeric.  ParseExcel's row_range() method is returning (0, 500) when only 285 rows are in use.
I tried selecting cells A1 - I285, and selecting File > Print Area > Set Print Area before saving and processing the .xls file with my Perl script, with no effect.
The file actually contains two worksheets.  One computes the number of rows correctly, and the other doesn't.  I created both worksheets, but don't know what I might have done differently.
Answer:
ParseExcel's row_range() method is returning (0, 500) when only 285 rows are in use.

Spreadsheet::ParseExcel reads the row_range() data from a binary record in the Excel file that stores the max and min row and column values. It doesn't iterate over the worksheet to calculate these values.
Therefore, if row_range() is reporting (0, 500) as the range of rows in use then these are the values that are stored in that record.
The source of the difference may be due to rows containing formatting but no data. Excel differentiates between an "Empty" cell and a "Blank" cell. An "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell is a cell which doesn't contain data but does contain formatting. Excel stores "Blank" cells but ignores "Empty" cells.

I tried selecting cells A1 - I285, and selecting File > Print Area > Set Print Area before saving and processing the .xls file with my Perl script, with no effect.

The print area doesn't have an effect on the range reported by row_range().
If you really want to reduce the file down to 285 data containing rows then select the rows from 286-501, delete them and then save the file.
Alternatively, set up your program to ignore rows containing only cells with blank data.
Answer: I would suspect it's counting rows with non-printable characters, but there's no way I can say for sure unless you post your code.
If it is the non-printable characters, try inserting this bad boy in whatever loop is causing the issue:
next unless $cell;


distribution of maximum of i.i.d. variables

Question: I'm doing a problem where we let consider the probability space $(\Omega, F, P)$  and let $X_{1},X_{2},X_{3}$ be i.i.d random variables. If the distribution of $X_{1}$ is $(\delta_{1} + \delta_{2} + \delta_{3})/3$, and we compute the distribution of  $Y=max\{X_{1},X_{2},X_{3}\}$.
I know that the distribution function $P(Y\leq y)=P(X_{1} \leq y, X_{2} \leq y,X_{3} \leq y)=P(X_{1} \leq y)^{3}$ so can I just say the distribution of Y is  $\delta_{1}^3$? I'm a little confused about the narrations here--- since we have i.i.d. variables, then why can't we just say that $X_{1}$ has distribution $\delta_{1}$ instead of $(\delta_{1} + \delta_{2} + \delta_{3})/3$?
Comment: Who is $\delta_i$? The Dirac distribution in 1 or something else?
Comment: @Momo Oh! So the problem didn't say anything about what it is. But does it really affect the result?
Comment: Of course that the distribution of $X_1$ affects the result. See my answer for an attempt under assumptions that deltas are Dirac.
Answer: Assuming Dirac distributions for $\delta$:
$$
P(X_1\le y)=
\begin{cases}
0, & \text{if } x<1 \\
\frac{1}{3} & \text{if } 1\le x<2 \\
\frac{2}{3} & \text{if } 2\le x<3 \\
1, & \text{if } x\ge 3 \\
\end{cases}
$$
From which you can derive:
$$
P(Y\le y)=
\begin{cases}
0, & \text{if } x<1 \\
\frac{1}{27} & \text{if } 1\le x<2 \\
\frac{8}{27} & \text{if } 2\le x<3 \\
1, & \text{if } x\ge 3 \\
\end{cases}
$$
So $Y=\frac{1}{27}\delta_1+\frac{7}{27}\delta_2+\frac{19}{27}\delta_3$
However, it might be more intuitive not to go through CDF for this discrete case:
$P(Y=1)=P(X_1=1)P(X_2=1)P(X_3)=1=\left(\frac{1}{3}\right)^3=\frac{1}{27}$
...etc
Comment: Thank you for your comment! This all makes perfect sense. Now if we don't assume this is a dirac measure. can I just say the distribution of the max is $\delta ^{3}$? I think the outcome of your example is also $\delta ^{3}$ given that is a dirac measure.
Comment: You cannot say that. $\delta_x$ just concentrates the whole probability mass in x, and it is 0 outside of x. $(\delta_1+\delta_2+\delta_3)/3$ concentrates the probability of 1/3 in each of the points with coordinates 1, 2, respectively 3. What makes you think that you can multiply Diracs like that?
Comment: Thanks! I now see where I was wrong.


Visualizing the flat complex conic

Question: Consider a conic $X^2 + Y^2 - Z^2 = 0$ in $\mathbb{C}P^2$. In an affine chart $Z \neq 0$ it is supposed to  look like a circle (however it looks in $\mathbb{C}^2$), but the deceptiveness of imagining it as something analogous to a real circle broke down when I realized that in this chart it has two points at infinity, namely $A = [1, i, 0]$ and $B = [1, -i, 0]$.
Moreover, it turns out that these points at least lie in the same analytic connected component as $C = [1, 0, 1]$, as can be seen by considering another affine chart $X \neq 0$, where by letting $y = Y/X$ and $z = Z/X$ we readily get $A = (i : 0)$, $B = (-i : 0)$, and $C = (0 : 1)$, so there is an obvious analytically smooth path $y = ki$, $z = \sqrt{1 - k^2}$ ($-1 \leq k \leq 1$) connecting the three points.
At this point cannot imagine what the complex flat conic looks like and how to visualize it. In the affine chart $Z \neq 0$ when $X/Z$ and $Y/Z$ are real it forms a familiar circle, but at the same time when, say, $Y/Z$ is purely imaginary, it now looks like a hyperbola, and when both are purely imaginary, no points satisfy the equation - and all this is just one chart! I assume that in other charts the picture is kind of similar: we get either real circles or real hyperbolas along different axes (and I assume that at some clever sections we get real parabolas), but visualizing it is hard.
UPD: the added complication is that my naive attempts at deforming a circle to a hyperbola fail: assuming $x = \hat x$, $y = e^{i\pi t/2} \hat y$, where $\hat x, \hat y \in \mathbb{R}$ the equation $x^2 + y^2 = 1$ becomes $\hat x^2 + e^{i \pi t}\hat y^2 = 1$, and this equation only has solutions when $t$ is half-integer.
My question is;

Is there a trick to understanding the conic better? Maybe something involving 3-spheres?
Comment: Why should 3-spheres come into the picture? The "curve" you describe is a 2-real-dimensional surface embedded in a 4-real-dimensional space. Every non-singular projective conic, such as the one you describe, is in fact isomorphic to the projective line (via stereographic projection), so this is topologically a sphere.
Comment: Try to parametrize it with a map $\mathbb CP^1\to\mathbb CP^2$.
Answer: Your problem
Strangely but very satisfactorily all non degenerate  quadrics in $\mathbb P^2(\mathbb C)=\mathbb CP^2$ are isomorphic as algebraic varieties.
"Non degenerate" means that if your conic has equation $\Sigma a_{ij}X^iX^j=0\quad (a_{ij}=a_{ji}) \;$, then the matrix $(a_{ij})$ has maximal rank i.e. rank $3$ .
As a consequence all these conics  are also holomorphically, real-analytically , $C^\infty$  and  topologically isomorphic.
And the common model is $\mathbb P^1(\mathbb C)$, as pointed out by Zhen and Mariano.
This is a spectacular example of the superiority of  algebraic geometry over an algebraically closed field and in projective space, a point of view that slowly developed over the centuries (think Desargues, Poncelet, von Staudt, ...)
Of course you must not be deceived by the real affine picture: all these conics are irreducible and have only one connected  component in the Zariski or analytic topology ( I emphasize this aspect because  you write a little ambiguously : "Moreover, it turns out that these points at least lie in the same analytic connected component ..." )
A generalization
Elementary quadratic form theory at the undergraduate level teaches us that over an algebraically closed field of characteristic $\neq 2$ all non degenerate quadratic forms $\Sigma a_{ij}X^iX^j \quad (a_{ij}=a_{ji}) \;$ in $n+1$ variables $X_0,...,X_n$ are congruent i.e. become identical after a change of variables .
(Non degenerate again means that the matrix $(a_{ij})$ has maximal rank $n+1$).
Thus all the quadrics $\Sigma a_{ij}X^iX^j =0$ are isomorphic to the one given by $\Sigma _{i=0}^n (X^i)^2=0$.
So that closes the subject, right?
Wrong! There is a very interesting geometry  of subvarieties of these quadrics, starting with the linear spaces they contain. The last chapter of Griffiths-Harris's Principles of algebraic Geometry is devoted to these questions.
To give just a simple example of what I mean, a non degenerate quadric in $\mathbb P^3(\mathbb C)$ is the simplest smooth surface on which there are smooth curves of all genera.

Visualizing the flat complex conic


Expectation of Geometic distribution

Question: I have the following question :

It costs $30$ cents per day to keep pigeons. Let $N$ be the number of pigeons kept and suppose that $N$ has the geometric distribution $Pr(N=n) = \frac1{10} (\frac9{10})^n (n=0,1,\dots).$

Which yields $30*\frac{0.9}{0.1} = 270=\$2.7$
That is fine. Now I have the one I don't know how to solve :

Now suppose that they cost $35$ cents per head except for the first three which remain at $30$ cents per head. What is the expected cost per day.

I have tried numerous things but I can't get their answer, I don't want to type all of these up because my table pc is slow. I have tried taking the difference between the first three against expected for the new price $35 * 9$ and calculating them all.
I have their solution but do not understand it:
$=5(9-3 + \frac3{10} + \frac2{10}(\frac9{10}) + \frac1{10}(\frac9{10})^2) = \frac{6561}{200} = 32.805$
Comment: Regarding the second part, are we to assume that the first three pigeons are 30cents and the remaining are 5cents, or are the first three free?
Comment: @Tom Sorry I screwed that up. Edited
Answer: The book answer seems wrong, I could derive the result using the Geometric CDF function:
$P(N\leq k)=1-(1 - p)^{k+1}\!$
With $p=0.1, k=3$:
$E(Cost/Day)=0\cdot P(N=0)+30\cdot P(1\leq N\leq 3)+35\cdot(1-P(N\leq 3))=30.2805\,ct$
This results goes under the assumption that $0$ pigeons cause $0$ cost of course, which hence lowers the expected daily cost. Conditional on at least 1 pigeon, we would get
$E(Cost/Pig>1)=\dfrac{30.2805}{1-P(N=0)}=33.645\,ct$
Comment: Thank you for that. I see now.

$30((1 - (1-p)^4) - (1 - (1-p))) + 35(1-((1 - (1-p)^4)) = 30 \times .2439 + 35 \times 69049 = 30.2805 $

Expectation of Geometic distribution


Initialization of the constructor of a QThread C++ with QString parameter

Question: is it possible to initialize a new QThread with a parameter?? I created two threads in MainWindow. Now i want initialize the Thread "mySave" with a QString. But it doesn't work.
void MainWindow::on_startButton_clicked()
{
    thread = new QThread();
    mThread = new myThread();
    threadSave = new QThread();
    mSave = new mySave("HelloWorld");
    ....
}

I change the line mSave = new mySave() to mySave = new mySave("HelloWorld") and the constructor of mySave-Class to
mySave::mySave(QObject *parent, QString stringFromMainWindow)
    : QObject{parent}, m_string{stringFromMainWindow}
{
    this->stringMySave = stringFromMainWindow;
}

mySave.h
class mySave : public QObject
{
    Q_OBJECT
public:
    explicit mySave(QObject *parent = nullptr, QString stringFileName = NULL);

private:
    QFile file;
    QString m_string {};
    ....

But i become a fault!
mainwindow.cpp:57:17: error: no matching constructor for initialization of 'mySave'
mysave.h:9:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [6]' to 'const mySave' for 1st argument
mysave.h:13:14: note: candidate constructor not viable: no known conversion from 'const char [6]' to 'QObject *' for 1st argument
What's wrong...??
Without QString parameter everthing works fine:
void MainWindow::on_startButton_clicked()
{
    thread = new QThread();
    mThread = new myThread();
    threadSave = new QThread();
    mSave = new mySave();

    connect(thread, SIGNAL(finished()), mThread, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    connect(mThread, SIGNAL(emitData(const QByteArray &)), this, SLOT(setEditText(const QByteArray &)));

    mThread->moveToThread(thread);
    thread->start();

    mSave->moveToThread(threadSave);
    threadSave->start();

    QMetaObject::invokeMethod(mThread, "interfaceSerial");

    QMetaObject::invokeMethod(mSave, "startFile", Q_ARG(QString, fileName));

    qDebug() << "Main open " << QThread::currentThread();

    dataTimer.start(0); // Interval 0 means to refresh as fast as possible
}

mySave-Thread constructor
mySave::mySave(QObject *parent)
    : QObject{parent}
{
    qDebug() << "Thread open " << QThread::currentThread();
}

How can i set a QString parameter in the constructor of a new QThread....??
Thanks & Bye bye
Comment: [First, please don't use `NULL` in modern c++.]  The problem will be that you try to provide only the second parameter (the `QString`) without providing the first. You have to provide parameters from left to right, so you either have to provide a `parent` (maybe `nullptr`), or re-order your parameters to have the `QString` on the left.
Comment: Yup...that was the problem...Thankx :-)
Answer: The problem was solved...you have to write
class mySave : public QObject
{
    Q_OBJECT
public:
    explicit mySave(QString stringFileName = NULL, QObject *parent = nullptr);

private:
    QFile file;

The last parameter has to be the QObject!!
Answer: Look at your mySave constructor signature...
explicit mySave(QObject *parent = nullptr, QString stringFileName = NULL);

The first parameter passed must be a QObject * (or something implicitly convertible to a QObject *) and the second parameter passed must be a QString.  If you want mySave to be constructible using a QString only then you must provide a suitable constructor.  The obvious option would be to simply reverse the order of the passed parameters...
explicit mySave(QString stringFileName = QString(), QObject *parent = nullptr);

Having said that, the most commonly used constructor calls for classes of this nature would probably be...
/* Default constructor: no text or parent. */
mySave ms1;

/* Text only. */
mySave ms2("Some text...");

/* Parent object only. */
QObject *parent = ...;
mySave ms3(parent);

/* Pass both text and parent object. */
mySave ms4("Some text...", parent);

All of these cases can be provided by the following two constructors...
mySave::mySave (const QString &stringFileName = QString(), QObject *parent = nullptr)
  : QObject(parent)
  , m_string(stringFileName)
  {
    ...
  }

mySave::mySave (QObject *parent)
  : QObject(parent)
  {
    ...
  }

Or, if you prefer, make the second a delegating constructor...
mySave::mySave (QObject *parent)
  : mySave(QString(), parent)
  {}

Comment: Yup...that was the problem...thankxxx


Probability of two teams matching up in semi-finals of 32-team knockout tournament.

Question: There are 32 teams in a traditional knockout tournament. Each of these 32 teams are of a different quality and can be distinctly ranked from 1st to 32nd in terms of ability. Assume that a higher-ability team always beats a lower-ability team. The teams are randomly seeded in the schedule of this knockout tournament. What is the probability that the second-best team meets the third best team in the semi-finals?
Comment: $\frac{16}{31} \times \frac{8}{30}$ : correct.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Because of the existence of the 1 seed, the 2 and 3 seeds can't meet in the final.  Therefore, necessary and sufficient is that the 2 and 3 seeds are in the same group of 16, the 1 seed is in the other group of 16, and the 2 and 3 seeds are in different groups of 8.
Comment: So, in that case, would it make sense to say that the probability is (16/31) - the probability that the 2 seed is in a different group than the first, multiplied by (8/30) - the probability that the 3 seed is in a different group than the 2 seed and the 1 seed?
Answer: To explain Lourran answer's . Imagine an array of 32 numbers from 1 to 32 randomly distributed, such that one of two neighbour numbers proceed to next round based on their ranking.
The rank 1 can be in 32/32 places. The rank 2 cannot be in the same half as 1 (else they will meet before or in the semi finals) so it has 16/31 choices. The rank 3 cannot be in same quarter as rank 2 and cant be in same half as 1, so 8/30 choices. SO the answer is 32/32 * 16/31 * 8/30


Why not use Ridge after Lasso vs relaxed Lasso

Question: Has anyone ever applied a ridge regression on a
model subset selected from a cross validated lasso? In other words, take a data set with p features and run lasso, grid searched to find optimal penalty parameters. Then record which features were dropped, and run only those features in a ridge regression. This approach seems similar to the "relaxed lasso" suggested by Meinhausen (2007) and clarified in the CV thread.
The only result on using ridge after lasso in literature I could find is this theoretical paper.
My intuition is that if relaxed lasso's objective is to split the separate variable selection and variable shrinkage, then why not go with ridge regression in the second pass? This will ensure that there isn't any variable selection in the second pass, whereas re-running lasso could result in additional feature drops.
Comment: See this thread: https://stats.stackexchange.com/questions/326427 -- some parts of my answer there are relevant. I used ridge after elastic net (ridge+lasso) as an attempt to make something like "relaxed elastic net".
Comment: In this interesting paper [De Mol 2009](https://arxiv.org/abs/0809.1777) the authors use a combination of elastic-net followed by ridge regression (which they simply refer to as _regularized least squares_) in order to select nested list of genes. The underlying idea is that the second ridge step should cope with the well-known _over_-shrinking effect of naïve elastic-net.
Answer:
This will ensure that there isn't any variable selection in the second pass, whereas re-running lasso could result in additional feature drops.

When performing relaxed LASSO then the point is to reduce the shrinking from a LASSO regression that is used for feature selection. For this purpose the second re-run with LASSO will be with a less severe penalty and will not result in additional feature drops.
Why a second lasso regression instead of a second ridge regression? Lasso is less severe in shrinking parameter estimates than ridge regression, although it also depends on the used penalty coefficients.
While the magnitude of the shrinking is more or less the same (as it can be regulated with the penalty coefficients), there are some qualitative differences (see also the different shapes of priors used by LASSO and ridge regression).

The prior for LASSO will drop of less quickly in longer ranges and penalize parameter estimates with different magnitudes more similar.

Ridge regression will penalize larger parameter estimates more severely and sort of pulls the estimates together to similar magnitudes.

Yet, possibly there is not much difference between the two situations when the regularisation is in the regime where the parameter estimates are all non-zero. Then the use of a second LASSO might possibly be still advantageous over a second ridge regression for computational reasons. The computations from the first regression, like LARS, can be quickly used in the second step, and the path is also a straight line that is easily computed.

Image: comparison of priors for LASSO (Laplace distributed prior) and ridge regression (Gaussian distributed prior). The scales can differ when regularisation parameters are changed, but the shapes are the same. The Laplace distribution (for LASSO) is more pointy near zero, but has longer tails far away from zero. The Gaussian distribution (for ridge regression) has a more blunt peak at zero and places more focus on smaller tails, leading to smaller parameter estimates, but not neccesarily close to zero.
Comment: Using relaxed lasso means that you've given up on model calibration-in-the-small.
Comment: @FrankHarrell this calibration-in-the-small versus calibration-in-the-large sound like interesting concepts that I haven't heard of before and had to look up with an internet search and a lot of the links direct back to you. Do you have a good pointer towards a reference that provides an introduction to these concepts?
Comment: https://hbiostat.org/rmsc/validate plus several good papers related to the Brier score that I wish I had referenced there.  Cal-in-the-small refers to the accuracy of probability forecasts at each level of predicted probability that occurs in the data.


share a domain name beween php and mono

Question: I've got a problem : I've got a dedicated server where I use three different domain names and php. Now, I've got a new website that I developped with asp.net. I installed mono, mod_mono and transfered my assembly inside /var/www/mysite
My problem comes up when I try to access my website. I tried IpAdress/mysite/ but it just gives the three and if I want "IpAddress/mysite/Controller1/Action1" it says 404.
As I said my server is apache and is used with php websites which has several domain names.
As one of those domain name can be used for my own website, I tried to create a subdomain name let's say mysite.maindomain.com
Here is the content of the file /etc/apache/sites-enabled/mysite.maindomain.com
 <VirtualHost *:80>
    ServerName mysite.maindomain.com
    ServerAdmin web-admin@mysite
    DocumentRoot /var/www/mysite

    MonoServerPath sousdomaine.domaineprincipal.com "/usr/bin/mod-mono-server2"
    MonoSetEnv mysite.maindomain.com MONO_IOMAP=all

    MonoApplications mysite.maindomain.com "/:/var/www/mysite"
    <Location "/">
      Allow from all
      Order allow,deny
      MonoSetServerAlias mysite.maindomain.com
      SetHandler mono
      SetOutputFilter DEFLATE
      SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
    </Location>
    <IfModule mod_deflate.c>
      AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
    </IfModule>
  </VirtualHost>

When I call mysite.maindomain.com it says "137 ERR_NAME_RESOLUTION_FAILED"
What configuration must I give to make mysite.maindomain.com or IpAdress/mysite/ work?
Edit
I tried to change the vhost configuration by putting a maindomain.com instead of the *
Then I also ran :
nslookup mysite.maindomain.com and got
Server:         127.0.0.1
Address:        127.0.0.1#53
** server can't find mysite.maindomain.com: NXDOMAIN

dig ciiarena.guildwars2-rage.com  and got :
; <<>> DiG 9.7.3 <<>> mysite.maindomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 10196
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;mysite.maindomain.com.  IN      A

;; AUTHORITY SECTION:
maindomain.com.    9588    IN      SOA     a.dns.gandi.net. hostmaster.gandi.net.1342214675 10800 3600 604800 10800

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu Dec 27 17:21:05 2012
;; MSG SIZE  rcvd: 108

after a wget mysite.maindomain.com I get nothing on error.log. As a matter of fact the wget I tried on the server leads to a 302 redirection to another domain than maindomain.
Comment: On the Apache server can you do a: **dig  mysite.maindomain.com**      also a: **nslookup  mysite.maindomain.com**,  if they resolve,  try a :  **wget   http: //mysite.maindomain.com/**  (if no **wget**, try a **curl**, or failing that: **telnet mysite.maindomain.com  80**,   then enter: **GET /**), and have a look at the output  or  tail /var/log/(httpd|apache2)/error*.log
Comment: nslookup says "server can't find mysite.maindomain.com
Comment: Quick fix, add an entry to the local /etc/hosts file  e.g.  127.0.0.1  xxxxxx.yyyyy.zzzzzz
Comment: 127.0.0.1? and it will be ok from my browser?
Comment: Possibly, if the host name wasn't resolving locally you'd likely see a browser error along the lines of: **Oops! Google Chrome could not find mysite.maindomain.com**
Comment: but it does not work. It tried, restart my apache but nothing changed.
When I try mysite.maindomain.com on chrome I get "Unavailable webpage" and in the details it is written Erreur 137 (net::ERR_NAME_RESOLUTION_FAILED)Unknown error
Comment: And do you get the same error from the command line on the linux box, if you do that implies there's a local DNS lookup error on the Apache server.
Comment: I put the error that I get on the linux box at the end of my question.
Comment: See quick fix above.
Comment: And I said I already tried it...
Comment: Check the ErrorLog as @arober11 suggested.
Comment: Ok so I will give you my error logs.
Answer: Reviewing your questions and comments, I notice a number of things. But first, most importantly: This is a DNS issue.

Check your DNS server and make sure that you have an A record setup for this particular subdomain.
In the comments, when it was suggested to add 127.0.0.1 to your /etc/hosts file, that should have been done on the server, not on the client computer. Did you edit the /etc/hosts file on the server or on a workstation / client? If not the server, go back and fix it.
When you are sure that your DNS issues are resolved, if you're still having issues, then make sure you include the subdomain's vhost configuration in Apache in the SAME file as your primary domain. But when you do, make sure to put the subdomain's vhost above the primary domain's vhost container.

Good luck.
Comment: this was effectively a DNS issue. Checking with my friends, the one who registered the subname misspelled it. I accept your answer and wish you an happy new year

share a domain name beween php and mono


Existence of the limit in $\mathcal{D}'$ of $1/x \in [-\varepsilon,\varepsilon]$

Question: Question:
Let be $w(x)=1/x$ and
$$w_\varepsilon(x)=
\begin{cases}
\frac{1}{x},&\quad |x| > \varepsilon\\
0,&\quad |x| \leq \varepsilon\\
\end{cases},
$$ with $\varepsilon >0$.
Show that $\forall \phi \in \mathcal{D}(\mathbb{R}), \exists\; \lim_{\varepsilon \rightarrow 0^+} (w_\varepsilon,\phi) = \lim_{\varepsilon \rightarrow 0^+} \int_{\mathbb{R} \setminus [-\varepsilon,\varepsilon]} \frac{\phi(x)}{x}\; dx =: I_\varepsilon(x)$ and is this limit is finite.
Solution:
Let be $[-a,a]=\text{supp}(\phi)$ for an arbitrary $\phi$, and the notice that:
$$\int_{\mathbb{R} \setminus [-\varepsilon,\varepsilon] \cap \text{supp}(\phi)} \frac{\phi(0)}{x}\;dx = \phi(0) \bigg( \int_{-a}^{-\varepsilon} + \int_a^\varepsilon \bigg) \frac{1}{x}\;dx = 0\; \quad (a)$$ because $\int_{-a}^{-\varepsilon} \frac{dx}{x} \overset{x=-y}{=} \int_\varepsilon^a \frac{dy}{y}$.
We also have that:  $\lim_{x\rightarrow 0} \frac{\phi(x) - \phi(0)}{x} = \phi'(x) \quad (b)$
If from $I_\varepsilon(x)$ we substract $(a)$:
$$ |g_\varepsilon(x)|=\bigg|\int_{\mathbb{R} \setminus [-\varepsilon,\varepsilon]} \frac{\phi(x)-\phi(0)}{x}\; dx \bigg|= \bigg|\int_{-a}^a \chi_\varepsilon(X) \frac{\phi(x) - \phi(0)}{x} \; dx\bigg|$$
And let $|g(x)| = \big|\frac{\phi(x)-\phi(0)}{x}\big| \in \mathcal{L}^1(-a,a)$, then we have that $|g_\varepsilon(x)| < |g(x)|$ because $|g_\varepsilon(x)| = |\chi_\varepsilon(x) g(x)|$.
Then $I_\varepsilon(x)$ is bounded, and from the dominated convergence theorem we can conclude that $\lim_{x\rightarrow 0^+} I_\varepsilon(x) = \int_{\mathbb{R}} \frac{\phi(x) -\phi(0)}{x}\; dx$.
I'm not sure about a couple of things:
1) It's is sufficient to show $(b)$ to ensure the function behave "well" around $0$ when integrated?
2) Is the proof complete or I'm missing some details?
EDIT:
Corrected $w_\epsilon(x)$ definition.
Corrected $w_\epsilon(x)$ definition, again, confused $<$ with $>$.
Comment: You can however take $a$ so big that $\operatorname{supp}(\phi) \subseteq [-a, a]$.
Comment: No. $\frac{1_{|x| < \epsilon}}{x}$ doesn't represent a distribution, but $pv(\frac{1_{|x| < \epsilon}}{x})$ does, and this is what you are showing here. Also if I say $\frac{1}{x}$ is a distribution on $C^\infty_c((0,\infty))$ and $C^\infty_c(\mathbb{R}^*)$ do you see any hint ?
Comment: No this is not an accident. The definition **is** $pv(\frac{1}{x}) = \lim_{\epsilon \to 0^+} \frac{1_{|x| > \epsilon}}{x}$ in the sense of distributions, ie. for $\phi \in C^\infty_c$ : $$\langle pv(\frac{1}{x}), \phi \rangle = \lim_{\epsilon \to 0^+} \int_{-\infty}^\infty \frac{1_{|x| > \epsilon}}{x} \phi(x)dx$$ Your job is to show the limit exists and defines a distribution, of finite order
Comment: Your job was and still is to show the limit exists and defines a distribution, of finite order. In particular you need to avoid the $L^1$ norm and replace it by the $\sup$ norm for $\phi$ and its derivatives
Comment: Your definition overlaps
Comment: You can't say that $[-a,a] = \text{supp}(\phi)$ will hold for arbitrary $\phi \in \mathcal{D}(\mathbb{R})$.
Comment: Your definition of the distribution is unclear. Did you mean $\omega_\epsilon(x) = \frac{1_{|x| > \epsilon}}{x}$ ? In that case $\lim_{\epsilon \to 0^+} \langle \omega_\epsilon, \phi \rangle = \langle pv(\frac{1}{x}), \phi \rangle$ the principal value. Since $1/x$ is odd we can realize it as $\langle pv(\frac{1}{x}), \phi \rangle = \langle \frac{1}{x}, \phi-\phi(0) \varphi \rangle$ where $\varphi(x) = e^{1-1/(1-x^2)} 1_{|x| < 1}$ which is $C^\infty_c$ even and $\varphi(0) = 1$
Comment: @user1952009 I have corrected the definition of $w\epsilon(x)$. I think in you observation you wanted to write $\frac{1_{|x|<\epsilon}}{x}$?
Comment: @user1952009 in my observation I wanted just to be sure that you wrote the $>$ sign in the function by accident. It seems so. For the $PV$, at the point where I'm I have just read about the its definition, so I really have no idea what it is. For your hint, is not $\mathcal{D}((0,\infty))=C_c^\infty((0,\infty))$ and $\mathcal{D}(\mathbb{R}^*)=C_c^\infty(\mathbb{R}^*)$ (with its own convergence)?
Comment: As I said $w_\epsilon(x) = \frac{1_{|x| < \epsilon}}{x}$ doesn't correspond to a distribution on $\mathbb{R}$.
Comment: @user1952009 My bad! I clearly confused $<$ with $>$. Even in my definition I stated it wrong. Now it is clear, thanks a lot. I fix it again.
Answer: Let $\phi \in \mathcal D$ be given. Through a Maclaurin expansion of $\phi$ we can write
$\phi(x) = \phi(0) + x \eta(x)$
where $\eta(x)$ is bounded as $x \to 0$.
Now take $\delta>0$.
Since $\eta$ is bounded at $0$ there is $a>0$ such that $\int_{|x|<a} |\eta(x)| \, dx < \delta$.
We clearly have $T_a := \int_{|x|>a} \frac{\phi(x)}{x} \, dx$ finite, so let's look at $\int_{\epsilon<|x|\leq a} \frac{\phi(x)}{x} \, dx$:
$$
\int_{\epsilon<|x|\leq a} \frac{\phi(x)}{x} \, dx
= \int_{\epsilon<|x|\leq a} \frac{\phi(0) + x \eta(x)}{x} \, dx
= \phi(0) \int_{\epsilon<|x|\leq a} \frac{1}{x} \, dx
+ \int_{\epsilon<|x|\leq a} \eta(x) \, dx
$$
Here,
$\int_{\epsilon<|x|\leq a} \frac{1}{x} \, dx = 0$ since we integrate an odd function over a symmetric set.
Thus,
$$
\left| \int_{\epsilon<|x|\leq a} \frac{\phi(x)}{x} \, dx \right|
= \left| \int_{\epsilon<|x|\leq a} \eta(x) \, dx \right|
\leq \int_{\epsilon<|x|\leq a} \left| \eta(x) \right| \, dx
\leq \int_{|x|\leq a} \left| \eta(x) \right| \, dx
< \delta
$$
As this doesn't depend on $\epsilon$ we have
$$\lim_{\epsilon \to 0} \left| \int_{\epsilon<|x|\leq a} \frac{\phi(x)}{x} \, dx \right| \leq \delta$$
so
$$
\left| \lim_{\epsilon \to 0} \int_{|x|>\epsilon} \frac{\phi(x)}{x} \, dx - T_a \right|
= \left| \lim_{\epsilon \to 0} \int_{|x|>\epsilon} \frac{\phi(x)}{x} \, dx - \int_{|x|>a} \frac{\phi(x)}{x} \, dx \right| \\
= \left| \lim_{\epsilon \to 0} \int_{\epsilon<|x|<a} \frac{\phi(x)}{x} \, dx \right|
\leq \lim_{\epsilon \to 0} \left| \int_{\epsilon<|x|<a} \frac{\phi(x)}{x} \, dx \right|
\leq \delta
$$
i.e. $\lim_{\epsilon \to 0} \int_{|x|>\epsilon}$ exists and is finite.


How to use an array as function argument

Question: I try to understand how to use an array as an argument for a function.
I have an error when i put arguments in this way :minimum([5],10). It is obvious wrong , but I don't know how to make it right.
My example is
#import <Foundation/Foundation.h>

int minimum(int values[],int numElements)
{
    int minValue,i;
    minValue = values[0];

    for(i=1;i < numElements; ++i)
       if(values[i] < minValue)
           minValue = values[i];

    return(minValue);
}

main()
{
    @autoreleasepool {
        int result;
        NSLog(@"For values 5 and numElements 10 results minValue  %i", minimum([5],10);
    }

    return 0;
}

Comment: I suggest you start with a good [language reference](http://en.wikibooks.org/wiki/C_Programming/Arrays).
Comment: What exactly are you trying to do?  What is `[5]` supposed to represent?
Comment: Why are you trying to do this at all (as an Objective-C question)? What are you actually trying to achieve?
Comment: This is really more a C question than an Objective-C question.
Comment: I try to pass arguments for my function but i don't know how because one of the argument is an array
Comment: Well, create an Array and pass it. It's a regular C array btw, nothing specific to Objective-C.
Answer: Do you want to check the minimum value of the first 5 values in an array[10]? in C you can do it in this way
#include <stdio.h>

int minimum(int values[], int numElements) /* or simply int *values */
{
    int minValue,i;

    minValue = values[0];
    for(i=1;i < numElements; ++i) /* do you mean i = 0? */
       if(values[i] < minValue)
           minValue = values[i];

    return(minValue);
}

main() /* int main(void) */
{
    int result[10] = {7, 4, 5, 8, 1, 3, 2, 6, 7, 6};

    printf("%d\n", minimum(result, 5));
    return 0;
}

Answer: Pass using its name and which member.
printf("at 0=%d at 5=%d", functionname(array), functionname(&array[5]));

You need to supply the location (address) of the array item. If you use just the name, it's the same as writing &array[0] (address of 0th member of the array). Otherwise, &array[ member ] will create an address that starts with that member.


How do I set a VxWorks breakpoint on a C static function?

Question: I work on a vxworks platform in C.  I am not able to set a breakpoint on a static C function.  In fact when I do a lkup on the function name when the code is loaded on my card it is not found.
If I use nm and grep to find the symbol in the executable it looks exactly like the name of the function. We are porting code to our platform which uses (correctly) the static keyword for a large number of functions but it's a pain that I can't set a breakpoint on any of these.
Does any one know why I can't see the C static functions on lkup and how to look them up and set the breakpoint.
Comment: What debugger are you using? Depending on your optimization option, your static function may have be inlined by the compiler. That's why you may not find its symbol. But you should be able to set a breakpoint if you compiled your object with debug information.
Comment: I'm guessing greydet is right about it being optimized away.  Try turning all optimization off while debugging.  If you have space restrictions or real-time requirements that disallow turning off all optimization, some compilers allow you to alter optimization for compilation units or even functions on an individual basis.  For example `#pragma optimize` and the attribute by the same name in GCC.  I think WindRiver's compiler is essentially gcc.
Comment: @user463477: had the same problem, then added the -g flag and the flag for "no optimizations"...
Answer: Assuming the routine really exists as you'd expect (i.e., not optimized away or inlined) - I've used a couple approaches in situations like this:
Assembly breakpoint

let's say you want to set a breakpoint at static function foo().  Find code that calls foo() - let's say bar() calls foo().  Where bar() calls foo(), set a breakpoint.
run until you hit the breakpoint where bar() calls foo(). step at the assembly level.  This should put you at the first instruction of foo().  Note that you might have to step through a few instructions if there are parameters being passed - hopefully you know what a branch / subroutine call looks like in your architecture.
Set an assembly breakpoint when you land at the first instruction of foo().

Function pointer
I've also worked around this by initializing a function pointer with foo()'s address.  When system is running, read the function pointer in the debugger.  Get foo()'s address.  Set breakpoint based on this address.
Note that in these cases you might not have interleaved source, though.
Answer: I don't think it is possible to do what you want. The compiler is not required to generate symbols for static functions, it may even inline them.
Example:
$ gcc -o test test.c
$ nm test | grep foo
0000000000400524 t foo
$ gcc -O2 -o test test.c
$ nm test | grep foo
$

Comment: I have never seen a case of GCC inlining a static function with -O0.  Inlining is, after all, an optimization.
Answer: From the sound of it, you are using the shell to do your debugging and setting breakpoints.
If that's the case, you might have an issue since a static function has internal linkage and is no longer a globally visible function (to the shell).
If you are using DKMs and using the ld command to load the modules, you can add a parameter to LD that will also include static symbols which you should then be able to manipulate in the shell.


Get CPU Usage for Process by Process ID

Question: I have a process ID, and I need to get the CPU usage a.k.a % Processor Time of the process.
For example, here is a simple function to return the CPU usage of AppName:
Private Function Get_CPU_Usage(AppName as String)
   Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", AppName, True)
   Return AppCPU.NextValue
End Function

It might be wrong but it's just an example.
I need to do something like this:
Private Function Get_CPU_Usage(ProcessID as Integer)
   Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", ProcessID, True)
   Return AppCPU.NextValue
End Function

Note ProcessID vs AppName.  I have multiple processes running with the same name; each application's PID is stored in my program.  I know I can iterate through...
PerformanceCounter("Process", "ID Process", AppName, True)

to find the process name, like app, app#1, app#2, but it seems inefficient and sloppy.
What is the recommended procedure here?
Comment: possible duplicate of [Performance Counter by Process ID instead of name?](http://stackoverflow.com/questions/9115436/performance-counter-by-process-id-instead-of-name)
Comment: Thanks!  I converted the C# form into VB.net and posted the answer.
Answer: Thanks to Hans Passant for the link to the answer in C# form, here is the VB.net function converted from Performance Counter by Process I instead of name:
Public Shared Function GetProcessInstanceName(ByVal PID As Integer) As String
    Dim cat As New PerformanceCounterCategory("Process")
    Dim instances() = cat.GetInstanceNames()
    For Each instance In instances
        Using cnt As PerformanceCounter = New PerformanceCounter("Process", "ID Process", instance, True)
            Dim val As Integer = CType(cnt.RawValue, Int32)
            If val = PID Then
                Return instance
            End If
        End Using
    Next
End Function

Get CPU Usage for Process by Process ID


A propriedade this está retornando undefined no typescript

Question: olá! tenho esse código em typescript:
import { InternalService } from './../services/InternalServices';
import { Request, Response } from "express";

class InternalController {
    internalService = new InternalService();

    constructor() {
    }

    async status(req: Request, res: Response): Promise<number> {
        return await this.internalService.status()
    }
}

export { InternalController };

e no arquivo ./../services/InternalServices tenho:
class InternalService {
    constructor() { }

    async status(): Promise<number> {
        return 200;
    }
}

export { InternalService }

está tudo visualmente perfeito mais quando eu rodo aparece a mensagem no termina:
(node:7281) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'internalService' of undefined
    at /workspace/Theryston/back-end/src/controllers/InternalController.ts:12:27
    at Generator.next (<anonymous>)
    at /workspace/Theryston/back-end/src/controllers/InternalController.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (/workspace/Theryston/back-end/src/controllers/InternalController.ts:4:12)
    at status (/workspace/Theryston/back-end/src/controllers/InternalController.ts:19:16)
    at Layer.handle [as handle_request] (/workspace/Theryston/back-end/node_modules/express/lib/router/layer.js:95:5)
    at next (/workspace/Theryston/back-end/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/workspace/Theryston/back-end/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/workspace/Theryston/back-end/node_modules/express/lib/router/layer.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7281) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7281) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

alguém poderia me ajudar?
Comment: Esse erro não é do TypeScript, mas sim do JavaScript, já que está ocorrendo em _runtime_.
Answer: Você passou a função status como parâmetro de callback para outra função?
Me parece que ela não está reconhecendo o this, porque ela foi invocada sem o binding do objeto.
Se em algum ponto do seu código você tem algum código similar a isso:
const internalController = new InternalController();
middleware(internalController.status);

Tente refatora-lo dessa maneira:
const internalController = new InternalController();
middleware(() => internalController.status());

Comment: show! funcionou! obrigado!


Porque ocorre "undefined" mesmo definindo o elemento exato a ser atingido?

Question: Estou aplicando uma injeção na barra de endereço do navegador web, sobre a página de um vídeo no youtube, no qual desejo extrair a data da postagem do mesmo.
Se abrirmos este link vemos uma div similar a esta:

Ao selecionarmos a data da postagem e em seguida usar a ferramenta "View Selection Source" disponível no próprio navegador web, podemos ver o código-fonte da linha selecionada:

(fonte: mplayerplugin @ sites.google.com)
De posse do nome da classe watch-time-text, tentei fazer o seguinte:
javascript:postado=document.getElementsByClassName("watch-time-text").innerHTML; alert(postado);

E ocorreu o seguinte:

(fonte: mplayerplugin @ sites.google.com)
Porque ocorre esse undefined mesmo o elemento existindo na pagina?
Porque um gif vale mais do que mil palavras
Answer: O método getElementsByClassName retorna uma coleção de elementos e não um elemento apenas.
Se você tem certeza que só existe um elemento com esta classe pode usar o índice 0 pra obtê-lo.
postado = document.getElementsByClassName("watch-time-text")[0].innerHTML;
alert(postado);

Comment: Sempre bom poder ajudar =)
Comment: Claro, eu que agradeço! E olha que agora funcionou com sua dica. Receba meu upVote seguido do Voto absoluto. E novamente meu síncero agradecimentos.


access callback admin permission is not working

Question: This is a follow up to  drupal.stackexchange.com/q/228722/9921
I have an api that I creates that I would like to restrict access to users with administrator role. But for some reason the 'administrator permission'  is not working. And the api returns an error when I add this restriction.
To clearify the use of language here:
    User : admin
    Role : Administrator
if you go to people permissions, Administrator has a permission of type administer permissions

I am 100% certain the user is an administrator
function mymodule_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_api_userslist',
    //'access callback' => array('administer permissions'), // tried both and they don't work
    'access arguments' => array('administer permissions'),
    'delivery callback' => 'mymodule_json',
  );
  return $items;
}

function mymodule_api_userslist() {
  // code not included since I know it works if the permission are just all permisions
  $data = Do an entityfieldquery to fetch users and return them
  return $data;
}

function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

The above code is being called via
  $users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

Any ideas?
____EDIT
<?php

/**
 * Implements hook_menu().
 *
 * */
function data_export_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'data_export_api_userslist',
    'access arguments' => TRUE,
    'delivery callback' => 'data_export_json',
  );
  return $items;
}

function data_export_api_userslist() {

  $data = data_export_process_users();
  // Do an entityfieldquery (or some other query) to fetch users and return them
  // as an array, not HTML or json. Json encoding will happen in the delivery callback.
  return $data;
}

/**
 * Delivers JSON. Used as a deliver callback for api menu items.
 *
 * @param array $data
 *   An array to be encoded as json.
 */
function data_export_json($data) {
  if (is_int($data)) { //https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_deliver_html_page/7.x
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

function data_export_process_users () {

  $results = array();

  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');

  $results = $query->execute();

  $users_node_list = entity_load('user', array_keys($results['user']));

  $return_results = array();

  foreach ($users_node_list as $key => $value) {
    $output = array();
    $output['name'] = $value->name;
    $output['email'] = $value->mail;
    $output['init'] = $value->init;
    $output['role'] = array_slice($value->roles, 1, 1)[0];
    $output['status'] = ($value->status) ? 'active' : 'blocked';
    $output['last_access'] = format_date($value->access,'small');
    $return_results[] = $output;
  }

  return $return_results;
}

function data_export_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', ['administrator', 'contributor', 'publisher'], 'IN');
  $query->condition('users.init', '', '<>');
}

Comment: Comments have been moved in a [chat room](http://chat.stackexchange.com/rooms/53771/discussion-on-question-by-quantico-access-callback-admin-permission-is-not-worki).
Answer: Your latest edit clears up where the problem is likely to be:

The above code is being called via
$users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

You're probably under the impression that the active user session from the calling site will somehow be passed through to and become valid for the API site? That won't happen, even if it's the same site - you're making a completely new request which doesn't share anything with the request you're making it from.
If you're building a secured API, you need to provide an authentication method that integrates with Drupal's login system, while still handling tokens etc for the API communication itself. That can be a fair amount of work, so people tend to use existing solutions like the Services module.
That module has an authentication layer for the core Drupal user login built in, and provides hooks for you to register your own resources. It will probably take less time to build your API using Services than building and testing your own authentication, so it's worth a look.


How can I use __str__ to change how an attribute of my objects shows up?

Question: I want the chips my player has to show up as $xxx, but to keep the chips as an int. I tried the code below, but the str part is just grey. What am I doing wrong?
class Player:
    def __init__(self, name, gender, taunt, aggression, hand, chips):
        self.name = name
        self.gender = gender
        self.taunt = taunt
        self.aggression = aggression
        self.hand = hand
        self.chips = chips

        def __str__(self):
            return "${0}".format(self.chips)

Comment: What do you mean it's grey?  What happens when you do `print(Player('','','','','',1))`?
Answer: What you need to do is unindent the __str__ function and it will work as normal:
class Player:
    def __init__(self, name, gender, taunt, aggression, hand, chips):
        self.name = name
        self.gender = gender
        self.taunt = taunt
        self.aggression = aggression
        self.hand = hand
        self.chips = chips

    # Note the outdent of the function

    def __str__(self):
        return "${0}".format(self.chips)

Comment: *facepalm* That was dumb of me. Thanks for helping though!! :) Much appreciated!


How to enable ckeditor in the emails templates at admin/config/people/accounts?

Question: Just that.
I need to enable ckeditor to write the text body for the welcome e-mail message at admin/config/people/accounts
How can I do this?
Comment: I don't know how to do it; but I doubt even after achieving this, the mails would be sent as plain text, which is the default format of the mails sent from a Drupal site. I suggest you to look for some other menthod for formatting(using html in) emails
Comment: Using html is what I do, but my client want to be able to periodically change these emails and he has no html knowledge.
Answer:
Create custom module for Drupal 7;
Add below code to your module;
replace all MODULENAME in code to your module name;
clear cache;
refresh /admin/config/people/accounts page

For all textarea fields there's text selector appear - you should select format, where ckeditor attached:
/**
 * Implements hook_form_FORM_ID_alter() for user settings page.
 */
function MODULENAME_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
  _MODULENAME_form_user_admin_settings_elements($form);
}

/**
 * Scan through elements.
 */
function _MODULENAME_form_user_admin_settings_elements(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      if (isset($elements[$key]['#type']) && ($elements[$key]['#type'] == 'textarea')) {
        $elements[$key]['#type'] = 'text_format';
      }
      else {
        _MODULENAME_form_user_admin_settings_elements($elements[$key]);
      }
    }
  }
}

be warn, that placeholders signs [bla-bla:something] can be replaced by unicode symbols (&XXXX), check before to show your client.
if you want add text format only for certain textarea use Devel module dpm function for seeking that element and setting next code $elements[CERTAIN_ARRAY_PATH2ELEMENT]['#type'] = 'text_format'; without scanning through all elements.
Comment: Thanks Nikit for your answer But I got an error when I save the configuration of admin page, the body part of the template will be blank.I done this in the default user email template.And I am not using any module for mail templates. Actually my task is to send HTML in the email i.e. email body with header and footer tag.
Can you please suggest any solution. Pallavi
Comment: 2Pallavi: what error it's show?
Comment: I have the same problem, I face blank page after saving content. The error message is " Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1572
Comment: I have checked again this code, and it's successfully work on clean Drupal with ckeditor and custom module. Looks like troubles came from another thing, I need to debug for recognizing bug...
Answer: In my answer I'm only going to focus on Welcome (no approval required) email body field.

First make sure to install HTML Mail module and its dependencies
Create Full HTML format if its not being created yet admin/config/content/formats
Implement the following code in a module and replace mymodule with your own module name

Code:
/**
 * Implement hook_form_alter().
 */
function mymodule_form_user_admin_settings_alter(&$form, &$form_state) {

  // alter type textarea to text_format
  $form['email_no_approval_required']['user_mail_register_no_approval_required_body']['#type'] = 'text_format';

  // alter default format to full_html (you need to create this format before you assign it)
  $form['email_no_approval_required']['user_mail_register_no_approval_required_body']['#format'] = 'full_html';

  // add validation function to alter field value before submit (before saving it to variable tables)
  $form['#validate'][] = 'mymodule_system_settings_form_validate';
}

function mymodule_system_settings_form_validate(&$form, &$form_state) {

  // get submitted value
  $html = $form_state['values']['user_mail_register_no_approval_required_body'];

  // set value of the submitted value
  form_set_value($form['email_no_approval_required']['user_mail_register_no_approval_required_body'], $html['value'], $form_state);
}

The reason I'm using validate function is to alter field value before submitting value and store it into variable table. Without altering the value Drupal will store value as array (value, format) and users will start getting Array as text instead of the actual text that you need them to see.
Answer: if the field format is choosen as long text
in the
  admin/config/people/accounts/

click on modify then select
 treatment: filter text


Docker service in swarm fails with error ask: non-zero exit (1)

Question: When we run command  :
docker service create --name [name] --with-registry-auth image-name

Services fails with Error - non-zero exit (1)

docker version - Docker version 1.12.2
Comment: That's not a valid command. Is that actually the command you ran, or did you change it to post here?
Comment: @BMitch `docker service create` absolutely is a valid command; it's a part of Docker Swarm.
Comment: @user5702955 Is the image you're trying to run public? Please include it if it is.
Comment: @tjbiddle it is with the proper arguments. But the question above didn't include the correct arguments.
Comment: @BMitch I'm not sure what you mean - `docker service create --name test_service nginx` works fine for me.
Comment: @TJBiddle The `[name]` would throw an error, but honestly I didn't see the `image-name` on the end of their question before, I may just be going blind. Regardless, without an exact copy/paste of the command being run and error message seen, this may not be answerable.
Comment: Ah - yeah, `[name]` would definitely mess things up; I just took that as a placeholder.
Answer: try docker service logs [name] to get a more detailed message why your service failed.
Answer: Solution
The quick easy way to follow and see logs with docker swarm is by using
docker service logs --follow [SERVICE_NAME | SERVICE_ID]

This command open an interactive terminal(STDOUT) on your shell to show all logs applications running inside this service
I don't recommend the usage of docker service logs [SERVICE_NAME | SERVICE_ID], Since the service might be crashing early at the beginning where it was able to yet log the messages before the container crashes, but with --follow option all logs are shown!
Comment: I had to use the service ID rather than its name (`docker service ls` to find).
Comment: Yeah, Service ID or name can be used to identify a service on docker, thanks for the add up!


What does goodness of fit tell us with skewed data?

Question:
"The goodness of fit test is a statistical hypothesis test to see how well sample data fit a distribution from a population with a normal distribution. Put differently, this test shows if your sample data represents the data you would expect to find in the actual population or if it is somehow skewed."

But if our population data is by itself skewed,is there any meaningful inference we can gather from it?
Is there any practical use to it for such data?
Source: Investopedia
Comment: Thanks for citing a source. I couldn't get past the first sentence without hitting a poor explanation: "The goodness of fit test is a statistical hypothesis test to see how well sample data fit a distribution from a population with a normal distribution."  That is at best confusing. For the specific problem of testing normality of distribution, there are dozens of tests, not just one. Testing goodness of fit is much wider problem, and rightly includes any statistical situation in which a model and data are confronted.
Comment: The source gets a little better, but is not to be recommended.
Comment: Ch-squared tests are indeed goodness of fit tests and widely used, and I can't see that anything I said stated or implied otherwise.
Comment: I agree.The initial Quote was what caused me confusion and thats why I seeked clarity.But from what I still understand Chi Squared tests are goodness of fit tests among other things and  are still widely used which seems contradictory to your statement.
Comment: Sorry,my bad.I misinterpreted your comment where you said is not recommended.Now I see you meant about source.Thanks for clearing that up.
Answer: The general sentiment on Cross Validated is that goodness of fit testing is no more helpful than plotting the data; that is, formal inference with the p-value does not help. This is because large sample sizes are going to cause rejections when there are subtle differences that don't matter to you, and small sample sizes will not give the test enough power to detect much of anything.
However, sure, you can test goodness of fit for skewed distributions. The ks.test function in R will test for goodness of fit to normal, exponential, uniform...any distribution X for which there is a pX function. The documentation for ks.test discusses this: https://www.rdocumentation.org/packages/dgof/versions/1.2/topics/ks.test.
The quote you gave seems to imply that the test is for normality. Is the context, by any chance, the Shapiro-Wilk test?
Comment: Just be careful not to believe in $30=\infty$ too much. Remember: I called it a joke (and it's one that made me laugh quite a bit the first time I heard it, right up there with yellow and equivalent to the axiom of choice).
Comment: Distribution assumptions for tests are common, but many tests are quite robust for decent-sized samples. A joke in statistics is that $30=\infty$. You can find posts on Cross Validated speaking time how little goodness of fit tests help. (I'll eventually find some and edit them into my answer.) You will accomplish a lot by visual examination of your data and going, "Looks about normal, certainly good enough with a decent sample size."
Comment: What is brown, furry, runs to the sea, and is equivalent to the axiom of choice? Zorn's lemming.
Comment: The quote I found just in context of "What is Goodness of Fit" search Query. It was not mentioned explicitly,in  case of Normality.
Comment: From your Answer,it seems Goodness of Fit does not provide any meaningful inference. But isn't Goodness of Fit underlying assumption in many tests like Chi-squared test?
Comment: Surely,I will keep this in mind now.You are absolutely right.Now that I rethink,there is little or no use for goodness of fit test if our sample size is greater than or equal to 30.
Comment: For those of you who are curious, what's yellow and equivalent to the axiom of choice? Zorn's LEMON
Answer: Statistical software was one of the first computer applications widely available. So for a long time there was an approach to use flow-chart style decision rules like goodness of fit tests in quantitative fields like finance. If the test passed normality, "Then Do",
otherwise "Else Do." In recent years statisticians have questioned these types of approaches.  However I think goodness of fit tests are still of value for teaching about distributions.
Comment: Perhaps you can give an example of how GoF would help in teaching about distributions. I'm not saying you're wrong, just curious what you have in mind.


Is it possible to use least significant differences even if my oneway ANOVA (9 steps) is not sig?

Question: I ran an oneway ANOVA with 9 steps. In the options I clickt the LSD post-hoc test.
In Andy Fields Statistics Book there is a hint that LSD requires the overall ANOVA to be sig. But it doesn't tell what I should do if I checked the box for LSD and SPSS gives me that as well in my output. And now there are some sig differences. Can i still report them and later use them for interpretation? Just with the note that the overall wasn't significant?
Thanks for helping me
Kerstin
Answer: According to Do we need a global test before post hoc tests? you cannot proceed with the LSD test if the global F test does not reject the null hypothesis. The purpose of checking the global F test first is to correct for multiple comparisons when performing the LSD test. However, other post hoc tests have the correction built in and therefore do not require an initial check of the global F test.


I am trying to enable the jQuery UI module, but I am hitting with error

Question: I am trying to enable the Jquery UI module in drupal 7, but I am hitting with error: The jQuery UI plugin is missing. Download and extract it to your jquery_ui module directory. (Currently using jQuery UI Not found)
I downloaded and extracted the plugin from the link into my Jquery_UI folder in sites/all/modules/jquery_ui. still I could not enable the module.
Answer: Looks like the module is expecting this structure:
modules/jquery_ui/jquery.ui/(actual jquery ui files)
However, it looks like jQuery UI library removed the version.txt file that this module checks for. If it does not find that text file, it considers the plugin 'not installed' which is kind of a bad check.
People are talking about it here, with a fix for Drupal 6 (and some talk for 7): https://www.drupal.org/node/1954136
However the project page advises you to use jQuery Update instead:

Drupal 7+ Since Drupal 7 ships with jQuery UI, the jQuery UI module
  has been deprecated and moved to the jQuery Update module.

https://www.drupal.org/project/jquery_update
You should dump this module and use jQuery Update and go from there.


How can I display translated content by language?

Question: I have a view with multiple displays, each configured as follows.
Display 1: Articles

FILTER CRITERIA:

Content: Published (= Yes)
Content: Content type (= Article)

PAGE SETTINGS:

Path: /articles/insights

Display 2: Page

FILTER CRITERIA:

Content: Published (= Yes)
Content: Content type (= Article)
Content: Page Category (= Glossary)

PAGE SETTINGS:

Path: /articles/glossary

Display 3: A-F

FILTER CRITERIA:

Content: Published (= Yes)
Content: Content type (= Article)
Content: Page Category (= Glossary)
Content: Subtitle (regex ^[A-Fa-f].*$)

BLOCK SETTINGS:

Block name: None
Block category: Lists (Views)
Allow settings: Items per page

The first display, "Articles," with the path /articles/insights, shows the article listing, while the second, third, and other similar displays show the Glossary of articles. The Page Category is a field called field_page_category, which can be selected when adding an article.
Now, I have some articles that are translated into Portuguese-Brazil (pt-br) and have the page category as Glossary. I want to display these links when I access /pt-br/articles/glossary. I tried creating a new display for the View with the path /pt-br/articles/glossary, and in the filter criteria, I added:

Content: Translation language (= Portuguese, Brazil)
Content revision: Translation language (= Portuguese, Brazil)

However, it still displays all the links in English. I'm unable to find a Language filter when attempting to add it.
The SQL query I received is:
SELECT "node_field_data"."langcode" AS "node_field_data_langcode", "node__field_subtitle"."field_subtitle_value" AS "node__field_subtitle_field_subtitle_value", "node_field_data"."nid" AS "nid"
FROM
{node_field_data} "node_field_data"
INNER JOIN {node__field_page_category} "node__field_page_category" ON node_field_data.nid = node__field_page_category.entity_id AND node__field_page_category.deleted = '0'
INNER JOIN {node_field_revision} "node_field_revision" ON node_field_data.vid = node_field_revision.vid
LEFT JOIN {node__field_subtitle} "node__field_subtitle" ON node_field_data.nid = node__field_subtitle.entity_id AND (node__field_subtitle.deleted = '0' AND node__field_subtitle.langcode = node_field_data.langcode)
WHERE ((node__field_page_category.field_page_category_value = 'Glossary')) AND (("node_field_data"."status" = '1') AND ("node_field_data"."type" IN ('article')) AND ("node_field_data"."langcode" IN ('pt-br')) AND ("node_field_revision"."langcode" IN ('pt-br')))
ORDER BY "node__field_subtitle_field_subtitle_value" ASC

How can I configure Drupal Views to display content in Portuguese (pt-br) when accessing the /pt-br/articles/glossary URL? I can't seem to find the Language filter to achieve this.
The language filters I already have are as follows:

Title
Category

Delivery Language
Content

Original language
Content

Translation language
Content

Translation source
Content

Original language
Content revision

Original language
Content revision

Translation language
Content revision

Translation source
Content revision
Answer: If I understand your problem, you are close of the solution.
On your view add

Content: Translation language

And then choose

Interface text language selected for page

Instead of choosing the language. With this option, everytime you enter the page you will get the content based on your language switcher block or URL prefix.
Comment: And make sure this is set: Rendering Language:
Content language of view row
Answer: You don't need to create /pt-br/articles/glossary path
Drupal add language prefix automatically. Needs to add views filter criteria Content: Translation language (= current language). When user select Brazil language only Brazil articles will show.
And of course you need to add Brazil language to site settings
Comment: I have tried this. I am using Drupal 9, and I have selected Content:  Translation language (= Interface text language selected for page) , but it is still showing articles in all the languages.
Comment: Show screenshot of your views settings and screenshot of your node translations tab. And views results screenshot too


Meta-analysis of odds ratios

Question: I would like to work on a meta-analysis project. I have kept 8 studies that satisfy my criteria and I'd like to continue with these. Their results are formed as odds ratios (OR) and confidence intervals (CI).
I read that I should convert them into log values and estimate the standard errors. I did this, but I don't know how to continue since all examples that I have seen are about trials and provide the accurate numbers of outcomes (i.e., before treatment, after treatment, or death/alive, etc.) while I have only ORs and CIs.
Could anyone help me, please? Also, please propose a free software capable of analyzing ORs and CIs.
Comment: I think you will find this useful: http://stats.stackexchange.com/q/13705/1934
Comment: Not a meta analysis person, but the 8 papers must have reported the frequency and described the samples. You'll need them to weight each of the studies. Just OR and CI alone will only work if they are of equal weight, which is quite unlikely.
Comment: I have the sample of each study, but you say me that I also have to find the frequency of each case? I mean that I know the OR of children of single parents with headache for example, and I have to find how many are these children? Did I understand the right thing?
Comment: @Penguin_Knight Actually the weighting for a meta-analysis is often based on inverse variance for a study (which is discoverable from the above information) although usual practice is to report numbers with/without outcome for each group for each study.
Comment: @JamesStanley, thanks for the tips! Meta analysis is a fascinating thing. :)
Comment: In addition to what have been suggested, I suggest you read about the base of meta-analysis, it will help you a lot :
Borenstein, M., L. V. Hedges, J. P. T. Higgins et H. R. Rothstein (2009). Introduction to meta-analysis. Chichester, UK, John Wiley & Sons, Ltd.
Koricheva, J., J. Gurevitch et K. Mengeresen (2013). Handbook of meta-analysis in ecology and evolution. Princeton,  USA, Princeton University Press.
Answer: Although I'm not strictly answering your question, I assume you want to calculate a mean effect size.  Assuming you are using comparable studies you'll need the odds ratios, which you have, and their variances, which you can recover using the post above.  The mean effect size is simply a weighted mean of individual effect sizes: $ES_{mean}=\frac{\sum\limits_{i=1}^kw_{i}ES_{i}}{ \sum{w_{i}^{n=k}}}$ where $ES_{i}$ and $w_{i}$ are the effect size and effect size weight for study i.  The weight of each effect size is simply the inverse of the estimate's variance, or $w_{i}=\frac{1}{\sigma^{2}_{i}}$, hence the more precise the estimate, the more weight it carries.  There are several R packages to conduct meta-analysis; a simple search should provide what you need.
Comment: This answer is slightly contradictory on the need for transformation: The answer at (http://stats.stackexchange.com/a/13708/16974) explains how to do the transformation from the odds ratios (with confidence intervals) back to the log(OR) and associated standard error (which is also on the log scale.)  You then do meta-analysis (as per this answer) on the log-scale estimates, and then would exponentiate the result of this from the log scale back into an odds ratio for reporting.
Comment: The comment above is correct.  The statement regarding the need to forgo transformation is incorrect.  I'll edit the answer and remove the error.
Answer: For a 'free' program, you can use Review Manager from the Cochrane Collaboration. You will input the log(OR) and SE for each study into the analysis using the Generic Inverse Function. This can also be done in R and many other 'free' meta-analytic software packages depending on your comfort level with using these programs.

Meta-analysis of odds ratios


Drupal way to create a dynamic url as a content type field

Question: What would be the Drupal way to create a dynamic URL field on a content type.
Say I have a content type called 'dogs' and so I use that to catalog all the dogs I like on my site. Now I have created a view that lists in two columns 1) all the dogs that I like and 2) a link to search them on google. There are 100s so I would like to make a dynamic url field because I don't want to type in each google search to each record for the dog content type. So:
Title | Search Link

Maltese, http://google.com/#q=Maltese

Beagle, http://google.com/#q=Beagle

etc...

What's the best way to encode the field such that it says:
1) Get the title for this node (Maltese),
2) Append it to the string "http://google.com/#q="
3) Make this my field_dog_search_url
Is this something that can be done in the admin panel or is it better to use a hook. I'd rather use a hook than download and install yet another module just for this one instance, though I'm interested to know if there is a good module that handles this scenario.
Answer: You can do this through the UI. Select the "Rewrite Results" checkbox and "Output this field as a link". Then use replacement patterns to fill in the dynamic part of the URL.
Answer: If it were me I would rewrite the view column.
You could ether do this through a views template, or just rewriting the output of the column.
The latter is probably the easiest, though I personally would use the template as it leaves the output to templates.
To rewrite the column, you could just add another title field, in the second field's settings make sure "Link this field to the original piece of content" is turned off, and then under "REWRITE RESULTS" you should be able to rewrite the output of the filed, and using replacement patterns you should be able to turn it into something like a link that says "search google" and pointing to http://google.com/#q=[title]
If you would like to do it through the template via a views template (again, that's the way I personally would do it) this will help get you started with that:
https://stackoverflow.com/questions/15498918/how-do-i-manually-theme-views-in-drupal-7


O que são assembly languages (linguagem de montagem)?

Question: Eu estava pesquisando quais são as linguagens utilizadas para construir sistemas operacionais. Ao que parece, Windows, Mac e Linux usam, em larga medida, C e C++. Na mesma fonte que encontrei essa informação, li que toda kernel precisa ser programada em uma linguagem de montagem (assembly code).
Mas o que são linguagens de montagem? É o mesmo que linguagens de baixo nível? E, finalmente, por que um sistema operacional precisa ser construído com esse tipo de linguagem?
Comment: Relacionada: [O que é assembler?](https://pt.stackoverflow.com/q/178804/69296)
Comment: E o [HLA(High Level Assembly)](https://en.wikipedia.org/wiki/High_Level_Assembly) é uma linguagem de alto nível ou continua sendo linguagem de baixo nível só que usando perfume importado?
Answer:
Mas o que são linguagens de montagem? É o mesmo que linguagens de baixo nível?

Assembly é uma linguagem de baixo nível, porém, não é o nível mais baixo. Um programa escrito em Assembly ainda precisa ser "convertido" em linguagem nativa (binária) para ser executada por um microprocessador. Quem faz essa conversão é o Assembler.
Assembly é uma linguagem baseada em mnemônicos, que são como "apelidos" de operações básicas que um microprocessador sabe executar. Por exemplo: acessar um local na memória, mover um valor de um local para outro na memória, etc.
Cada família de microprocessador pode possui seus próprios mnemônicos, assim como outras características específicas que podem influenciar no seu desempenho.

E, finalmente, por que um sistema operacional precisa ser construído com esse tipo de linguagem?

Quando se usa uma linguagem de alto nível, podemos usar classes para separar escopos de funções e variáveis, as estruturas condicionais e de repetição, e claro, o Garbage Collector, são benefícios que facilitam nossa leitura, mas esse dinamismo cobra caro na hora de traduzir o programa para a máquina, uma vez que, existem vários microprocessadores, arquiteturas diferentes, e um compilador precisa saber a melhor forma de transformar o código que escrevemos em algo que a máquina irá ler da melhor forma. As vezes isso gera muito código adicional, pra não dizer lixo.
Linguagens de baixo nível precisam de mais código para executar programas complexos pois usam apenas operações básicas, isso a torna difícil para um humano ler, porém, o que é escrito em Assembly já segue uma lógica praticamente do nível que um microprocessador irá ler.
Normalmente, os programas de um sistema operacional são escritos em C e C++ -que alguns autores consideram como linguagens de nível médio. Escrever um programa diretamente em Assembly é mais comum quando se está desenvolvendo para camadas mais próximas do Hardware, como a comunicação com o microprocessador ou com os periféricos, ou configurações mais limitadas ou especificas como para softwares embarcados.