Predicate and quantifiers_discrete

Question: Consider the predicate ∀x A(x) → ∃x B(x)
i Just want to know is this predicate always true ?
Reason i think "∀x A(x)" will always be false and hence making the predicate always TRUE ..!!
let A(x)=x is even
B(x)=x is odd
now there won't be case when All x will be "even" making it false..please correct me
Comment: When you say " is this predicate always true ?" you are asking if the formula of predicate logic is *valid*, that means: "true in every interpretation". Thus, from the fact that is it true in a (suitable chiosen) interpretation, you are not licensed that this is so in **every** interpretation.
Answer: No, the predicate can be false. Consider $A(x)$ as $x=x$ and $B(x)$ as $x\neq x$. Then your predicate is false.
Comment: See this question "check if ∀x(P (x) → Q(x)) and ∀xP (x) →∀xQ(x) are logically equivalent." they both are not equivalent because the solution said that "∀xP (x)" of  RHS part will always be false ..,making RHS True and not LHS true
Answer:
Reason i think "∀x A(x)" will always be false and hence making the predicate always TRUE ..!!

$\forall x A(x)$ will not always be false, even if maybe it will usually be false. For it to be true, you have to pick $A(x)$ to be something really stupid that is always true, such as "$x = x$" or simply $\textsf{True}$.

let A(x)=x is even B(x)=x is odd now there won't be case when All x will be "even" making it false..

You are right for the specific example of $A(x)$ being "$x$ is even" and $B(x)$ being "$x$ is odd", that the formula comes out true. But for other predicates $A$, $B$, it can come out true. So you haven't shown that it is always true. In fact it is sometimes false, as has already been pointed out.
Comment: See this question "check if ∀x(P (x) → Q(x)) and ∀xP (x) →∀xQ(x) are logically equivalent." they both are not equivalent because the solution said that "∀xP (x)" of RHS part will always be false ..,making RHS True and not LHS true
Comment: @sourav Are you trying to ask a new, different question? Click "Ask Question" at the top of the page.

Predicate and quantifiers_discrete


Solve the problem using Chebyshev inequality

Question: The problem is the following:
The symmetric coin is tossed 1600 times. What is the probability that the head will be shown up more than 1200 times?

Attempt.
Using the formula $\mathbb{P}(|X-MX|)>e)≤ DX/e^2$ I put the numbers in it
$$\mathbb{P}(|X-800|>1200)\le 400/1200^2$$
But do not get the answer which is $\le 1/800$.
Answer: Let $X$ be the number of heads. Then $X$ has mean $\mu=800$ and variance $\sigma^2=(1600)(1/2)(1/2)=400$. The Chebyshev Inequality says that
$$\Pr(|X-\mu|\ge k\sigma)\le \frac{1}{k^2}.$$
In our case, we are interested in something related to the probability that $X\ge 1200$. Now $1200=\mu +k\sigma$, where $k=20$. So by the Chebyshev Inequality we have
$$\Pr(|X-800|\ge 400)\le \frac{1}{20^2}.$$
But the distribution of $X$ is symmetric about $800$, since the coin is fair. It follows that
$$\Pr(X\le 1200)\le \frac{1}{2}\cdot\frac{1}{20^2}=\frac{1}{800}.$$
We have shown that the probability that $X\ge 1200$ is $\le \frac{1}{800}$. So in fact $\Pr(X\gt 1200)\lt \frac{1}{800}$.
Comment: (more)  Basically we are interested in the right tail, from $1200$ up. Actually, the problem asks about $1201$ or more. So we could replace the $k=20$ by solving $1201=800+(k)(20)$, and get an improved (slightly!) estimate probability is $\le \frac{1}{2}\cdot\frac{1}{(20.05)^2}$. But both the earlier bound and this one are quite poor, Central Limit Theorem gives better estimates.
Comment: You can find the **exact** probability by using appropriate software. I think Wolfram Alpha will do it, certainly Mathematica or Maple will. Or you can use the normal approximation to the binomial. But your problem asks you to use Chebyshev, as an exercise with working with that inequality.
Comment: You used an additional step to to find the k. Could you please explain the following 1200=μ+kσ
Comment: We have $\sigma=20$ and $\mu=800$. to use the Chebyshev Inequality, we need to find the appropriate $k$. We want $1200=800+(k)(20)$, so $k=20$.
Comment: Can I use other methods to solve the problem e.g. Bernoulli's theorem? I tried but none of calculators could count it
Answer: You did everything right, except that to find when it is greater than $1200$ you need $|X-800|>400$ not $|X-800|>1200$. Also note, that this will include cases $X>1200$ as well as $X<400$, and since the distribution is symmetric around $800$, all you need to do is divide $400/400^2$ by $2$.
Comment: Because $|X-800|>z$ is $X-800>z$ or $X-800<-z$, i.e. $X>800+z$ or $X<800-z$, and you need $X>1200$. Think about it differently: suppose you have median of $X$ equal $8$ and you are asked when $X$ is greater than $12$. Well, when $X>12$ or $X-8>4$, not $X-8>12$.
Comment: Why should I put 400 instead of 1200?


Finding the derivative 23

Question: Differentiate $$V= \frac{4\pi r^2}{3}\left(\sqrt{\frac {16}{r^2}-2}\right)$$
I have tried it. But its too complicated for me. Hope you can help me out.
Comment: is this right so?
Comment: Yeah. It is. Sorry Im new to this programming mathjex thing.
Comment: Consider simplifying $\sqrt{\frac{16}{r^2}-2}$ as $\frac{\sqrt{16-2r^2}}{r}$, you can cancel one $r$ then try to apply the product rule.
Comment: Also I wanted to tell you that this site requires that you provide context to your question like why do you want to differentiate this (is this a part of a bigger problem?),what have you tried yourself otherwise your questions might get closed and downvoted.
Comment: To add to kingW3's comment, you should also put a better title than "find the derivative 23"
Answer: for your first derivative we get by the product and chain rule
$$V'(r)=8/3\,\pi\,r\sqrt {16\,{r}^{-2}-2}-{\frac {64\,\pi}{3\,r}{\frac {1}{
\sqrt {16\,{r}^{-2}-2}}}}
$$
the rule of differentiating is when we have $$f(x)=cg(x)$$, $$f'(x)=cg'(x)$$ if $c$ is a constant
Comment: But when I look back at the answer, it has no pi. That is what confuses me
Comment: but your formula above has a $\pi$!
Comment: dv/dr = 16(4-r^2) / (3rsqrt (16/r^2-2) is the answer
Comment: no this is not right, a $\pi$ is missing
Comment: That is what Im confused about. Do u think the answer scheme is wrong
Comment: yes the answer is definitively wrong
Answer: $$V= \frac{4\pi r^2}{3}\left(\sqrt{\frac {16}{r^2}-2}\right)$$
$$V=\frac{4\pi r^2}{3}\left(\sqrt{\frac {16-2r^2}{r^2}}\right)$$
$$V=\frac{4\pi r^2}{3}\cdot\frac {\sqrt{16-2r^2}}{r}$$
$$V=\frac{4\pi }{3}r\sqrt{16-2r^2}$$
$$V'=\frac{4\pi }{3}\left(1\cdot \sqrt{16-2r^2}+r\cdot\frac{-4r}{2\sqrt{16-2r^2}}\right)$$
$$V'=\frac{4\pi }{3}\left(\sqrt{16-2r^2}-\frac{2r^2}{\sqrt{16-2r^2}}\right)$$
$$V'=\frac{4\pi }{3}\frac{16-2r^2-2r^2}{\sqrt{16-2r^2}}=\color{red}{\frac{16\pi}{3}\cdot \frac{4-r^2}{\sqrt{16-2r^2}}}$$
Answer: To differentiate it with respect to r first of all note that $\dfrac{4\pi}{3}$ is a constant and that $(a\cdot f(x))'=af(x)$ so, in your case:
$$\dfrac{d}{dr}V=\dfrac{4\pi}{3}\cdot\dfrac{d}{dr}\left(r^2\sqrt{\dfrac{16}{r^2}-2}\right)$$
So now you just need to apply the product rule $(f\cdot g)'=f'g+fg'$ as follows:
$$\dfrac{d}{dr}V=\dfrac{4\pi}{3}\left(2r\sqrt{\dfrac{16}{r^2}-2}+r^2\left(-\dfrac{16\sqrt{r^2}}{r^3\sqrt{16-2r^2}}\right)\right)$$
And, simplifying:
$$\dfrac{d}{dr}V=\dfrac{16\pi r(-r^2+4)}{3r\sqrt{-2r^2+16}}$$
Answer: The variable in the problem is $r$, so that's what we will do the derivative around.
First you're going to want to write the equation in a more agreeable form:
$$V(r) = \frac{4\pi r^2}{3} \cdot \left(16r^{-2}-2\right)^{1/2}$$
We can see we're going to need to use the product rule and then also use the chain rule on the righthand side of the multiplication symbol. You can make a substitution to the side, or you can do this all in one fell swoop. I'm going to show you the latter.
First, apply the product rule rule (derivative of the product equals derivative of the first times the second plus the derivative of the second times the first):
$$V'(r) = \frac{d}{dr}\left( \frac{4\pi r^2}{3} \right) \cdot \left(16r^{-2}-2\right)^{1/2} + \frac{4\pi r^2}{3} \cdot \frac{d}{dr} \left[ \left(16r^{-2}-2\right)^{1/2} \right]$$
To evaluate the lefthand derivative, we will want to pull the constant $4\pi/3$ outside the derivative, bring the power of $2$ down in front of the $r$, and reduce the power on $r$ to $1$:
$$V'(r) = \frac{4\pi}{3}(2r) \cdot \left(16r^{-2}-2\right)^{1/2} + \frac{4\pi r^2}{3} \cdot \frac{d}{dr} \left[ \left(16r^{-2}-2\right)^{1/2} \right]$$
To do the righthand derivative, we are going to want to apply the chain rule by doing the derivate (via power rule) around $16r^{-2}$ and then multiplying by the derivative of $16r^{-2}-2$:
$$\begin{align}
V'(r) &= \frac{4\pi}{3}(2r) \cdot \left(16r^{-2}-2\right)^{1/2} + \frac{4\pi r^2}{3} \cdot \frac{d}{dr} \left[ \left(\color{blue}{16r^{-2}-2}\right)^{\color{green}{1/2}} \right] \\
V'(r) &= \frac{4\pi}{3}(2r) \cdot \left(16r^{-2}-2\right)^{1/2} + \frac{4\pi r^2}{3} \cdot \color{green}{\frac12}\left(\color{blue}{16r^{-2}-2}\right)^{\color{green}{1/2-1}}\left( \color{blue}{16(-2)r^{-2-1}} \right)
\end{align}$$
From there it's just algebra.
Answer: You can also do $$V^2=\frac {16\pi^2r^4}9\left(\frac{16-2r^2}{r^2}\right)=\frac{32\pi^2}{9}\left(8r^2-r^4\right)$$
Now differentiate both sides wrt $r$
$$2VV'=\frac {32\pi^2}{9}\left(16r-4r^3\right)$$
That simplifies the differentiation part considerably. Now you divide by $2V$ (which you know).

Finding the derivative 23


Integral definition of e

Question: I know that $e$ can be defined via a convergent series: $$ e = \sum_{n=0}^\infty {1\over n!}$$
Or as a limit: $$ e = \lim_{n \to \infty} { \left(1 + {1 \over n}\right)^n }$$
Or as the value which satisfies the condition:

For any real number $x$, $f(x) = {df\over{dx}}$

Is there an integral definition of $e$ ?
Something like: $$e = \int_0^\infty ...$$
Comment: Your derivative definition is a little bit dodgy. If $\mathrm{f}(x) = \mathrm{f}'(x)$ then $\mathrm{f}(x) = k\mathrm{e}^x$, where $k$ is any real number (the zero function, i.e. $k=0$, satisfies the ODE!). You need to apply some initial conditions, e.g. $\mathrm{e}$ is given by the value $\mathrm{f}(1)$ when $\mathrm{f}(x) = \mathrm{f}'(x)$, subject to the condition $\mathrm{f}(0)=1$.
Comment: $\lim\limits_{x\to 0}\Big(\frac{1}{x}\displaystyle\int_{0}^{x}(1+\sin(t))^{1/t}dt\Big)$
Answer: $\int_1^x \frac{1}t dt = 1$ so $e$ is the unique $x$.
Comment: doesn't answer the question IMO...
Comment: $e$ is the unique $x$ which satisfy the equation
Comment: Shouldnt you get $\ln x$?
Comment: @fish.frog Shush.
Answer: Would you accept $\displaystyle e = \int_0^\infty \frac1{\lfloor x\rfloor!} \,dx$?
Comment: Is that correct? It just keeps spitting it back out on my TI-89.
Comment: It's correct, but it's not very interesting — it's just $\sum_{n=0}^\infty \frac1{n!}$ in a thin disguise.
Comment: Well it's what I was looking for. Don't know why I didn't get this earlier.
Comment: What scenario exactly is this answer useful in?
Answer: I think it's worth pointing out the link between the examples you proffered.
Note $e^t$ is the solution to the differential equation $dx/dt = x, x(0) = 1$. Thus, $x(1) = e$.
Now, try to approximate the solution to this ODE using the forward Euler method with step size $1/h$ to estimate $x(1)$. The first step yields $x(1/h) \approx x(0) + (1/h)x(0) = (1 + 1/h)x(0) = 1 + 1/h$. The second step yields $x(2/h) \approx x(1/h) + (1/h)(x(1/h) = (1+1/h)x(1/h) = (1+1/h)^2$. Taking $h$ steps yields $x(1) \approx (1 + 1/h)^h$. Using consistent approximations results, you get that, as the step size $1/h$ goes to $0$, $x(1) \rightarrow e$.
Now, note that $\frac{d^2x}{dt^2} = \frac{d}{dt} \left( dx/dt \right) = \frac{d}{dt} x$. (This follows just by plugging in the equality $dx/dt = x$.) Inducting, we get that $\frac{d^nx}{dt^n} = x$ for all $n \in \mathbb{N}$, and the convergent sum result is simply a direct application of Taylor's theorem.
Basically, my point is that these equivalent definitions are not coincidence, and hint at a lot of neat results.

Integral definition of e


How to refresh a part of the page after some time automatically?

Question: I have a user control loaded on the default.aspx page using the
Control UControl = null;

UControl = this.LoadControl("UserControl1.ascx");

 UControl.ID = UControl.GetType().Name;
                    panel1.Controls.Add(UControl);

Now I want to refresh only the content of the user control not all the page.
I already used
<meta http-equiv="refresh" content="300">

and
Response.AppendHeader("Refresh", "2");

But these are refreshing the entire default.aspx page.
How I can only refresh the user control without refreshing the default.aspx.
Answer: You need to look into the <asp:UpdatePanel> control. You can use it with a timer as well to auto refresh, or hook it into a trigger such as button or link.
Try here on the offical asp.net site:

http://www.asp.net/ajax/tutorials/understanding-partial-page-updates-with-asp-net-ajax

But a simple search will also produce plenty of tutorials.
Answer: You can use the Ajax Timer Control: http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-timer-control


Weird bug with border:0 / none css

Question: i have a weird bug with my css

#box1 {
  border:2px solid #CC9933;
  padding:5px;
  -moz-border-radius:10px 0;
  -webkit-border-radius:10px 0;
  border-radius:10px ;
  margin-bottom: 10px;
  width: auto;
}

#box1 label {
  background-color: black;
  color:white;
  float: left;
  margin-left: 1px;
}

#box1 span {
  display: block;
  overflow: hidden;
}

#box1 span input {
  width: 100%;
  border:none;
  border-bottom:solid 1px #000;
  outline:none;
}

  <form>

       Nom de la société
      <input type="text" value="">

       Adresse
      <input type="text" value="">

  </form>

I won't show all the HTML because it is the same structure.
The thing is that in my web browser it looks like this :

However, this is how it should looks like :
(this is the same code !)
http://jsfiddle.net/8vsyxtys/
Comment: You have a `float` that you aren't `clear`ing. The container `` elements should have `clear:left`.
Comment: If you can't reproduce it, how can we debug it?
Answer: It's most likely the float:left.
Try adding a clear div after each:
css would be: .clear { clear:both; height: 1px; }

#box1 {
border:2px solid #CC9933;
padding:5px;
-moz-border-radius:10px 0;
-webkit-border-radius:10px 0;
border-radius:10px ;
margin-bottom: 10px;
width: auto;
}

#box1 label {
  background-color: black;
  color:white;
  float: left;
  margin-left: 1px;
}

#box1 span {
    display: block;
    overflow: hidden;
}

#box1 span input {
    width: 100%;
    border:none;
    border-bottom:solid 1px #000;
    outline:none;
}
.clear {
  clear: both;
  height: 1px;
 }

 <form>

     Nom de la société
      <input type="text" value="">

     Adresse
      <input type="text" value="">

 </form>

Weird bug with border:0 / none css


Database design, How to reduce the data redundancy for different column

Question: I have an existing table which requires different columns for different record. do I need to split it into multiple tables to reduce the redundancy?
Table1:
productId   typeId  commonAttr1 commonAttr2 attrA1  attrB1 attrB2
_________________________________________________________________
1           1       1Avalue1    1Avalue2    value1
2           1       1Avalue1    1Avalue2    value2
3           2       2Bvalue1    2Bvalue2            value3  value4
4           2       2Bvalue3    2Bvalue4            value5  value6

The "attrA1" is only for recored with typeId=1, "attrB1" and "attrB2" are only for records with typeId=2, "commonAttr1", "commonAttr2" are for both.
There might be 3 options:
1. Do not change. accept the data redundancy.
2. Move "attrA1" to new table2, move "attrB1","attrB2" to new table3.It'll be like:
Table1:
productId   typeId  commonAttr1 commonAttr2
___________________________________________
1           1       1Avalue1    1Avalue2
2           1       1Avalue1    1Avalue2
3           2       2Bvalue1    2Bvalue2
4           2       2Bvalue3    2Bvalue4

Table2:
productId   attrA1
__________________
1           value1
2           value2

Table3:
productId   attrB1   attrB2
___________________________
3           value3   value4
4           value5   value6

3.Create a new table to store the column as Key/Value
Table1:
productId   typeId  commonAttr1 commonAttr2
___________________________________________
1           1       1Avalue1    1Avalue2
2           1       1Avalue1    1Avalue2
3           2       2Bvalue1    2Bvalue2
4           2       2Bvalue3    2Bvalue4

Table2:
productId  typeId   key       value
____________________________________
1          1        attrA1    value1
2          1        attrA1    value2
3          2        attrB1    value3
3          2        attrB2    value4
4          2        attrB1    value5
4          2        attrB2    value6

Which option is better or is there any other solution? Personally I suppose option 2 is better.
Comment: It depends on why you want to do this schema refactoring. What is the issue you are facing with the existing table ?
Comment: [Normalization](https://en.wikipedia.org/wiki/Database_normalization) is what you're attempting and it's always a good idea to keep in mind when designing a DB (although you can overdo it). I'd go with option 2 too, but introduce another table just for the common attributes with it's own id column and your actual transaction table would just have a productId, TypeId and a CommonAttrId
Comment: Thanks, Ashwin, for option2, I kept table1 with the commonattr columns, just move the others to table2 and table3.
Comment: @AshwinNair Restructuring involving NULLs or EAVis not normalization, which is about replacing a table by projections of it that inner join back to it.
Comment: Please specify the queries you will be performing.
Answer: When you have a schema in which common attributes are stored in one table an the other ones are stored in their dependent tables it's called a model (base)type/subtype design (or a model for inheritance). In this stackoverflow question you would fine how to correctly implement it (in order to keep referential integrity)
Hope it helps
Answer: 4 One table with  productId, typeId, commonAttr1, commonAttr2, json
where that last column is a JSON rendering of the other key-value pairs.
EAV (Entity-Attribute-Value) schema is problematic; sometimes #4 is a useful compromise.  More discussion.


Creating a stored procedure for a subscribed report

Question: I'm trying to create a notification system that alerts me when something is setup incorrectly in our ERP database. I have a report that I manually have to run every day to check on to see if there's anything for me to fix. Instead of doing that I'd like to have the report emailed to me or some sort of notification sent to me.
Someone suggested the following:

Create the report in SSRS (Done; if the report doesn't have any data there's nothing to fix if there is data, I need to fix something)
Create a stored procedure that will raise an error if there is no data
The SSRS report will use the stored procedure dataset
Subscribe to the report and it will only send an email if data exists

I'm stuck on the second part with the stored procedure, here's my code:
CREATE PROCEDURE JOBNOMATS
AS
SELECT CASE
            WHEN (SELECT "JobHead"."JobNum", "JobHead"."Company", "JobHead"."PartDescription", "JobHead"."ReqDueDate", "JobMtl"."PartNum", "JobMtl"."MtlSeq", "JobHead"."InCopyList", "JobHead"."Plant"
            FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead" LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON ("JobHead"."Company"="JobMtl"."Company") AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
            WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS  NULL  AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')) IS NULL
THEN RAISERROR(50001,16,1)
 ELSE SELECT "JobHead"."JobNum", "JobHead"."Company", "JobHead"."PartDescription", "JobHead"."ReqDueDate", "JobMtl"."PartNum", "JobMtl"."MtlSeq", "JobHead"."InCopyList", "JobHead"."Plant"
            FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead" LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON ("JobHead"."Company"="JobMtl"."Company") AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
            WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS  NULL  AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')

But I get these two errors:

Msg 156, Level 15, State 1, Procedure JOBNOMATS, Line 7 Incorrect
  syntax near the keyword 'RAISERROR'.

Msg 156, Level 15, State 1, Procedure JOBNOMATS, Line 9 Incorrect
  syntax near the keyword 'ELSE'.
Comment: For starters, your `SELECT CASE` requires and `END`
Comment: @RickS Thanks - should I add just one END or after each evaluation?
Answer: You can't do that in a CASE statement.
You can try something like this...
CREATE PROCEDURE JOBNOMATS
AS
BEGIN
    IF NOT EXISTS(
        SELECT NULL
        FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead"
            LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON
                ("JobHead"."Company"="JobMtl"."Company")
            AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
        WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS NULL
        AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')
    )
    BEGIN
        RAISERROR(50001,16,1);
    END

    SELECT "JobHead"."JobNum", "JobHead"."Company", "JobHead"."PartDescription", "JobHead"."ReqDueDate", "JobMtl"."PartNum", "JobMtl"."MtlSeq", "JobHead"."InCopyList", "JobHead"."Plant"
    FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead" LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON ("JobHead"."Company"="JobMtl"."Company") AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
    WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS  NULL  AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')

END

There are better ways to do this.
Running the same query twice is a bit of a waste.
You can also check the @@ROWCOUNT after the query was executed, and raise the error if it was 0
CREATE PROCEDURE JOBNOMATS
AS
BEGIN
    SELECT "JobHead"."JobNum", "JobHead"."Company", "JobHead"."PartDescription", "JobHead"."ReqDueDate", "JobMtl"."PartNum", "JobMtl"."MtlSeq", "JobHead"."InCopyList", "JobHead"."Plant"
    FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead" LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON ("JobHead"."Company"="JobMtl"."Company") AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
    WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS  NULL  AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')

    IF @@ROWCOUNT = 0
        RAISERROR(50001,16,1);

END

OR
You could also select the results into a temp table, and if the record count in the temp table is 0, raise the error... else select everything from the temp table...
CREATE PROCEDURE JOBNOMATS
AS
BEGIN
    SELECT "JobHead"."JobNum", "JobHead"."Company", "JobHead"."PartDescription", "JobHead"."ReqDueDate", "JobMtl"."PartNum", "JobMtl"."MtlSeq", "JobHead"."InCopyList", "JobHead"."Plant"
    INTO #TEMP
    FROM   {oj "Epicor10Live"."Erp"."JobHead" "JobHead" LEFT OUTER JOIN "Epicor10Live"."Erp"."JobMtl" "JobMtl" ON ("JobHead"."Company"="JobMtl"."Company") AND ("JobHead"."JobNum"="JobMtl"."JobNum")}
    WHERE  "JobHead"."Company"='011' AND "JobMtl"."PartNum" IS  NULL  AND  NOT ("JobHead"."JobNum"='95057' OR "JobHead"."JobNum"='AISMNJOB')

    IF (SELECT COUNT(1) FROM #TEMP) = 0
        RAISERROR(50001,16,1);

    --DO MORE STUFF IF YOU WANT TO...

    SELECT *
    FROM #TEMP
END

all depends how expensive the query is
Comment: Thanks a lot! The last one seems like it's the most efficient.
Comment: I would go with the second one... checking @@ROWCOUNT. But it's your call.
Comment: Alright, you obviously know much more than I do about this. Second one it is!


Improper integral: $\int_1^\infty\frac{\sin(\sqrt{x})}{\sqrt{x}}dx $.

Question: mathematica is reporting that the improper integral $\int_1^\infty\frac{\sin(\sqrt{x})}{\sqrt{x}}dx $ coverges to $2\cos(1)$. However, when I try to confirm this by actually integrating it using u-substitution, I end up with $-2\lim\limits_{n=1}^\infty\left(\cos n - \cos 1\right)$. I am thinking we cannot determine the first limit here.(oscillation). Any help would be appreciated.
Comment: The first limit doesn't exist
Comment: This bug (nice catch!) might be worth posting to http://mathematica.stackexchange.com/ . At least one SE user here and there, @daniel-lichtblau is a Wolfram employee - there are probably others - and might pass it on to the developers.
Comment: The Mathematica Question is here if you are interested: http://mathematica.stackexchange.com/questions/106162/why-does-mathematica-report-that-int-1-infty-frac-sin-sqrtx-sqrtxdx
Comment: $u=\sqrt{x}, du = \frac{1}{2\sqrt{x}}dx$
Comment: the OP tried this already.
Comment: What is interesting is that, if we first change variable $x=u^2$ and ask for integration, the answer from WA  is *the integral does not converge* instead of the stupid $2\cos(1)$.
Answer: OP, you are correct, $$\int_1^n\frac{\sin \sqrt{x}}{\sqrt{x}}dx=-2\cos\sqrt{n}+2\cos 1$$
Hence the improper integral is $$\int_1^\infty\frac{\sin \sqrt{x}}{\sqrt{x}}dx=\lim_{n\to\infty}\int_1^n\frac{\sin \sqrt{x}}{\sqrt{x}}dx=\lim_{n\to\infty}-2\cos\sqrt{n}+2\cos 1$$
And the latter limit does not exist.  Your computer algebra system (mathematica) is giving an incorrect answer.  Alpha gives the same incorrect answer, probably because it's got mathematica under the hood.
Comment: Perhaps, mathematica is choosing something like $ (2\pi n +\pi/2)^2 $ as sequence tending to infinity? (sorry for my previous - incorrect - comment)


How to easily calculate the expected value of powers of Poisson variable?

Question: For a statistics class the solution to one of the question starts with:
"First note that, if $Y$ is a Poisson random variable with mean $\lambda$ then,
$\mathbb{E}[Y]=\lambda$,
$\mathbb{E}[Y^2]=\lambda^2+\lambda$,
$\mathbb{E}[Y^3]=\lambda^3+3\lambda^2+\lambda$,
$\mathbb{E}[Y^4]=\lambda^4+6\lambda^3+7\lambda^2+\lambda$.
I know the first one is a property of the Poisson distribution and the second one follows relatively easy from that but I was wondering how to quickly get the last two.
I know it is possible to compute these values with $$\sum_{k=0}^{\infty}k^3 e^{-\lambda}\frac{\lambda^k}{k!} \text{ and }\sum_{k=0}^{\infty}k^4 e^{-\lambda}\frac{\lambda^k}{k!}$$
But when I do that it takes quite some time and computational work.
Because the solutions just said "note" it makes me think that there is a way faster way to do this or that this is just a well known fact.
So my question is, is there a faster way to compute this then working out the sum?
Comment: Compute the PGF/MGF/CF.
Answer: Let's say you know $E(Y^j)$ for all $\ j\in \{1,2,\ldots, n-1\}.\ $ Then we can get $E(Y^n)$ in terms of $E(Y^{n-1}),\ E(Y^{n-2}),\ \dots,\ $ and $\ E(Y).\ $
$$ E(Y^n) = \sum y^nP(Y=y) = \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} k^n $$
$$ = 0 + \sum_{k=1}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} k^n$$
$$ = \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^{k+1}}{(k+1)!} (k+1)^n$$
$$ = \lambda\sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} (k+1)^{n-1}$$
$$ = \lambda \left( \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} \binom{n-1}{0} k^{n-1} + \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} \binom{n-1}{1} k^{n-2} + \ldots + \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} \binom{n-1}{n-1} k^{0} \right)$$
$$ = \lambda \left( \binom{n-1}{0} \sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!}k^{n-1}  + \binom{n-1}{1}\sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!}  k^{n-2} + \ldots + \binom{n-1}{n-1}\sum_{k=0}^{\infty} \frac{e^{-\lambda} \lambda^k}{k!} k^{0} \right)$$
$$ = \lambda \left( \binom{n-1}{0} E(Y^{n-1})  + \binom{n-1}{1}E(Y^{n-2}) + \ldots + \binom{n-1}{n-2}E(Y) + \binom{n-1}{n-1} 1 \right).$$
Answer: If $Y\sim \text{Poisson}(\lambda)$
$$\mathbb{E}[Y^n]=\sum_{k=0}^{n}\left\{n\atop k\right\}\lambda^k=B_n(\lambda)$$
Where:

$\displaystyle\left\{n\atop k\right\}$ is the Stirling number of the $2$nd kind
$B_n(x)$ is the Bell polynomial

You can find all the Stirling numbers here


Determining when a set is ordered, with noise and missing values

Question: The problem:
I have repeated observations of the ordering of about 25-30 objects, and I have maybe 1000 sets of these objects. I wish to determine which sets of objects are ordered and which are not, but there are a couple complications.
First, there are missing values in each observation. For each observation, about 60% of the objects are observed (on average, but this varies between sets).
Second, I would like to account for some noise, so that even if a small number of the objects swap order or are in the wrong place on a given day, but most of the time most of the objects are in the same order, then it would be labeled as ordered.
What I've done (and some problems with it):
So far, I have created a variance-like measure (M) based off a "true" rank. The "true" rank is constructed by comparing each object i to each object j and determining the percent of observations for which rank(i)$<$rank(j). From this, I pull a vector of row averages (averaging the percent of times object i is before every other object j), and I rank these. The object whose rank is truly "first" should have a high average, and so on. I then compare this "true" rank to the observed rank in the following way:
$M=\frac{1}{D}\sum_d^D \sum_i^n \frac{1}{n_d^*} ( rank_{id}-\bar {rank}_{id} )^2$
where D is the number of observations d, i is the individual, and $\bar {rank}$ is the "true" rank for any given observation d. It is specific to the observation, because the "true" rank is adjusted for which objects are present in the observation (since some are missing each observation). Similarly, n* is the number of objects observed that day (observation). I then use some threshold value as a cutoff point.
This seems to work, and I've used several thresholds, but the (main) issue is that it is not invariant to set size. That is, sets with higher missing rates appear to have a lower measure (M) than those with lower missing rates, simply because the potential difference in values is greater. Sets with higher missing rates are observably different in other areas, and so this method of dividing the data fails a balancing test. The second issue is that determining the threshold is a bit ad hoc, but I could probably live with that if the other issue was not so glaring.
Other Thoughts:
I've started looking at clustering, with the hope that I could test H0: single cluster vs H1: more than one cluster. This is in part because I want to do some hierarchical clustering with the unordered sets once I have determined which they are.
There seem to be a few ways to test for the number of clusters, but (particularly in hierarchical clustering) I don't see many ways to conclude that there is a single cluster. It looks like the gap statistic might be able to do this in more of a k-means context (as well as some others in the k-means context), but testing for the existence of clusters with one type of clustering algorithm and then creating clusters later in the process via another seems strange to me.
I'm sure there are other (possibly obvious) ways to think about an ordering problem like this, and am open to suggestions outside of these areas I've been thinking about.
Comment: Very interesting question. It might be better on ttps://stats.stackexchange.com
Comment: @EthanBolker Thanks for the suggestion, I'll move it there.
Comment: There are some advantages of placing it on stats, there are some advantages of placing it here too. I feel like the question requires more common sense than advanced knowledge. But it also begs for clarifications on many issues. First, when you say that you observe only some part of the objects every time, may we assume that the subsets are random and independent for different observations? Second, looking at your functional, one can notice that it is greater for 30,1,2,3,...29 (one badly misplaced object) than for 2,1,4,3,...,30,29 (15 short swaps). Is that really how you want it to be?
Comment: @fedja Taking your 2nd point first: this is not what I want, but I suspect it is what is driving the issue I point out (that sets with lower missing rates have a lower M). I suspect that solving this issue is key.

To clarify, subsets are not random. The frequency which object 1 appears may be significantly different than object 2, but we can assume that any observation is independent from another observation (object 1 appearing in observation 1 is independent from whether it appears in observation 2, but it may have a higher chance of appearing in any observation than object 2 does).
Comment: The issue you point at may be solved by the trivial observation that the deviation in rank in a partial sample is roughly speaking the deviation in the full sample times $n^*_d/n$, so instead of $D$, you should really divide by $D^*=\sum_{d=1}^D (n_d^*/n)^2$ in your notation. Try it and see if the results get better. I'll think of the rest meanwhile.
Comment: @fedja Your first point is very intuitive, regarding the ratio of deviation in rank for a partial and full sample being proportional to the size of these groups. In truth, the 1/D does little for me, as all sets are observed equally, but this makes the measure more general. However, what I understand is that I should normalize ranks such that I compare similarly sized objects. Thus my interpretation of what you are saying is that my functional becomes $M=\frac{1}{D} \sum_d^D \sum_i^n (n/n^*_d)^2(rank_{id}-\bar {rank}_{id})^2$. This "scales up" the deviation for observations with high missings.
Comment: Looking at that, I also may also need to throw another 1/n into that so that I can compare, say, a set of size 25 to that of size 30.
Comment: What you suggest is very similar to what I suggest except you give equal weight to all observations and I give some preference to observations with more objects and you should leave $1/n_d^*$ in the summands where it was in both cases (you still estimate the average deviation, not the sum of deviations). There is no clear argument why one way is better than the other, so decide between the two options (they are both consistent) experimentally. $n$ is already accounted for by that extra $n_d^*$ in the denominator ($M=\frac 1D\sum_{d=1}^D\sum_{i=1}^{n}(n/n_d^*)^2(n_d^*)^{-1}(\Delta r_{id})^2$
Comment: I would also try to lower the power $2$ to $1$ (just average absolute values). That somewhat mitigates the effect of big misplacements of few objects. Of course, the scaling should be changed to $n/n_d^*$ then and $M$ replaced by roughly speaking $\sqrt M$.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94822/discussion-between-amquack-and-fedja).
Answer: This is just to record my train of thoughts and to construct $M$ at least as "intuitive" as the original one but with the property that dropping a random set of objects from the observation won't affect it too much.
Let us have a permutation $\pi$ that deviates from some fixed order (say, the standard $1,2,\dots n$ one) in some places. The original quantity that was suggested to measure the "disorder" was essentially $\frac 1n\sum_{k=1}^n (\pi(k)-k)^2$ and the problem seemed to be that the proposed estimator for it from a randomly chosen subset of varying cardinality about $n/2$ was biased with the bias depending on the cardinality.
There were 2 things I didn't like. One was about the measure itself. It was that the permutation $(n,1,2,\dots,n-1)$ had $n$ times larger measure of disorder (about $n^2$ than the permutation $(2,1,4,3,\dots, n,n-1)$ (about $n$). One could argue that one big displacement and $n-1$ small ones is worse than $n$ small ones, but "30 times worse" seemed like an overkill. So I took the liberty to reduce the power with which to average to $1$ and consider $\frac 1n\sum_{k=1}^n |\pi(k)-k|$ instead.
The second thing was the attempt to discern the actual order before computing the deviations. That introduces some extra uncertainty because the order estimator based on the ranking may be reasonably correct when the ranks are really different but can get not too reliable when the ranks are close. So I wanted the estimator that does not rely on the knowledge of the true order.
The first thing I recalled was that $\sum_{k=1}^n |\pi(k)-k|$ is pretty much the same as the total number of inversions in $\pi$. One inequality is obvious: every displaced number participates in at least as many inversions as its displacement. The other inequality is a bit subtler but it also holds with an absolute coefficient independent of $n$. Thus, we can just try to estimate the expected number of inversions per one set element.
How to count the number of inversions? That's easy: just consider all pairs $i<j$ and count the number of observations in which this pair of objects appears in the wrong order and then sum over $i,j$. The only complication is that, since we do not know the true order, we do not know which order is right and which is wrong. However, if the pair $i,j$ appeared in $B_{i,j}$ observations $A_{i,j}$ times in one order and $B_{i,j}-A_{i,j}$ times in the other one, we definitely have the lower bound $C_{i,j}=\min(A_{i,j},B_{i,j}-A_{i,j})$ for the number of wrong orders and if we believe that the disorder is not too high, it won't be a big stretch of reality to assume that most of the time this lower bound will be the truth (if the disorder is high, then $C_{i,j}$ would be comparable with $B_{i,j}$, so the threshold most likely won't be passed anyway).
This leads to the quantity $S=\sum_{i<j}C(i,j)$ but we should normalize it somehow. The normalization I chose is "per observed pair", i.e., the denominator is $B=\sum_{i<j}B(i,j)$, so the meaning is, roughly speaking, the chance of the random pair of objects to get swapped. If you want the normalization per element, then it should be multiplied by $n-1$ when comparing different $n$'s. Which normalization makes more sense depends on your passing criteria (one can argue that when $n$ gets larger, proportionally higher deviations should be allowed (which would be my idea) but one can also argue that they shouldn't; in a sense, comparing the levels of disorder for different $n$'s is a bit of art and should be discussed separately).
Thus we are tempted to put $M=S/B$ and to finish the story. Unfortunately, it still shows the tendency to noticeably go down when you remove objects from observations (to be exact, if you have some noisy set order with random selection and just lower all probabilities of being observed proportionally, it goes down). Let us try to understand why.
We will suppose that for each pair $(i,j)$ being included into the observation does not depend on being swapped and that swaps in different observations are independent (that is another assumptions that may or may not hold; it can be tested from the data, though it doesn't seem necessary because if it really mattered, you would observe it on the test with removing random objects from existing observations that you ran).
So my model is just that for each fixed pair $(i,j)$ you have some probability $p$ (I'll drop the indices $i,j$ for brevity) of appearance and the other probability $q$ of being swapped from the true order (I do not assume that they are independent of the pair!). Then the expected value of the corresponding $B$ is just $E=Bp$ (with the binomial distribution $Bin(D,p)$) and once $B$ is fixed, we are trying to use the estimator $C$ for the expected number of swaps $qB$.
However our estimator $C$ is biased: we actually have
$$
\mathcal E(C)=\sum_{k=0}^B {B\choose k}q^k(1-q)^{B-k}\min(k,B-k)<qB
$$
This bias disappears when $B\to\infty$, but it is quite noticeable for small values of $B$ (if you have nothing better to do, you can graph the ratio $\mathcal E(C)/(qB)$ as a function of $B$  for various $q$) and it increases in size when $B$ goes down. So when the probability of appearance goes down, the average bias increases and a lower value of $M$ is observed.
We don't mind the bias per se (just view it as measuring some other quantity) but we certainly want to make it independent of $B$.
When $B=0,1$, $C=0$, so these values carry no information whatsoever, which means that we cannot fix the bias there. Fortunately, $B=0$ makes $0$  contribution to everything, so we do not need to worry about it. But $B=1$ should be just excluded by force, so we are lead to redefining the denominator in the formula for $M$ to
$$
\sum_{i<j, B_{i,j}>1}B_{i,j}\,.
$$
When $B=2,3$, we have $\mathcal E(C)=Bq(1-q)$, so we would like to maintain this ratio throughout higher values. This is possible if instead of $\min(k,B-k)$, we write
$$
B{B\choose k}^{-1}{B-2\choose k-1}=\frac{k(B-k)}{B-1}
$$
mimicking a shorter binomial formula. Note that it differs from $\min(k,B-k)$ at most twice, so the physical meaning is more or less preserved.
Thus, $S$ gets redefined as $\sum_{i<j, B_{ij}>1}\frac{A_{ij}(B_{ij}-A_{ij})}{B_{ij}-1}$
The only real influence on the expected value of $M$  now comes from dropping $B=1$, so we need to look at how big contribution to $\mathcal E(B)$ it makes. It is just $Dp(1-p)^{D-1}\approx Dp e^{-Dp}$, so it is just $e^{-Dp}$ - portion of the whole expectation. With your $D=175$ and the individual object appearance rate at least $1/4$, this is less that $e^{-10}$, so we should not bother about it too much.
I would say more but with MathJax  typing becomes progressively more and more unpleasant, so I'll stop here. I hope the derivation is more or less clear nowbut feel free to ask questions.


How to approximate $x^y$ using a quadratic function

Question: I need to build an algorithm that finds the approximately $x^y$ where $x = [0, 1]$ and $y = [0, 0.4)$.
This is for a computer algorithm (the standard library is too slow). I thought about making a lookup table but that would require a 2 dimensional table (since I have 2 variable). I would be ok with a lookup 1 dimensional lookup table.
Ideally the function would be most accurate at around x=1, y=0.16
Comment: Use $x^y = \exp(\ln(x)\cdot y)$
Comment: You can use the taylor expansions for ln x and exp(x).
Comment: isn't taylor expansion only for e^x ?
Comment: This may be useful: $x^y \approx \exp \left(y\frac{x-1}{6}\left(1+\frac{8}{1+x}+\frac{1}{x}\right)\right) $
Comment: For $x\in\bigg[\dfrac23,\dfrac32\bigg]$, we have $\ln x\simeq\sqrt x-\dfrac1{\sqrt x}$ .
Answer: If there is an inbuilt exponential function, then you can use the following equation to approximate it in the given intervals:
$$x^y \approx \exp \left(y\frac{x-1}{6}\left(1+\frac{8}{1+x}+\frac{1}{x}\right)\right)$$
The inner term is an approximation to ln(x) using Simpson's Rule, which is quite accurate. You can use a lookup table or a taylor series or some approximation if the inbuilt exp is not fast enough.
The accuracy is quite good, see this graph: https://www.desmos.com/calculator/75cebv9qks .
The green and blue lines coincide so nicely that they are not even visible seperately.
Near 0.16, its not that accurate and you may use 2 or 3 terms of the Simpson's Rule.
Comment: >in the given intervals< would it be too much to ask you how you made up this function ? or even just paste some links that explain how to build those ?
Comment: Good answer. It seems to only get within about 0.05 of the actual value near 0.16 though.
Comment: Actually its the Simpson's rule for numerical integration. I used the formula to approximate ln(x) as the inner term using the fact that $\ln(x)=\int_1^x \frac1x$.
Comment: @theREALyumdub I thought it was near y=0.16, not x=0.16. It is quite accurate near x=1.
Comment: I used Kartik's graph, which is x^x. So you are probably correct that y is the problem
Comment: no it is near y=0.16, x=1 that it should be most accurate
Comment: @user2475269 Then it is quite accurate and you dont need more terms.
Comment: I just realised if i do make a lookup table, i could probably modify the values in the lookup so that it corrects for the error introduced by simpsons rule
Answer: The commenters are right that exp(ln(x) * y) is the most efficient way to do this. On the other hand I have an over-complicated way to do it below, which may be slightly faster because it uses a look-up table.
I'm not sure I exactly understand what you mean by quadratic function, at first I thought you meant the complexity had to be quadratic, but it sounds like you are asking legitimately for a polynomial. I think it should suffice to say that polynomials do not approximate exponential functions such as the above, because the ratio of an exponential function changes drastically, where a polynomial approaches a fixed number (The lead coefficient multiplied by the factorial of the degree, I believe...).
You could make a binary look up table as follows, and make it small enough steps to suit your accuracy with numbers in between.
$$ y = a_n \frac{1}{2^n} + a_{n-1} \frac{1}{2^{n-1}} + ... + a_1 \frac12 $$
$$ x^y = a_n x^{2^{-n}} * a_{n-1} x^{-2^{n-1}} * ... * x^{a_1} $$
Note the above formula is right associative. By pre-computing the values of $ x^{2^{n}} $, one can multiply them together depending on the value of y and it's binary form, and pre-compute for different values of x to the desired n-depth for accuracy.
Even I don't think that is the better answer, it may be slightly faster in a time sensitive situation.
Comment: I didn't realize that polynomial function could not approximate these. I edited my question.
Comment: Actually, I may be wrong about that. Give me a second
Comment: Also, I don't know if you're about to edit your post, but what are the values of a_n
Comment: They are the binary booleans for y, ie if y = 5, 101 in binary, they are the digit numbers
Comment: try using taylor expansions truncated at x^2. Note that the function looks like a line above about y= 0.5 and that should be used for good accuracy there


How to instantiate a AdnroidViewModel in Linear Layout

Question: I am creating a Custom Linear Layout view to represent a custom calender. Ealier I used SQlitehelper to get the data. But now I am migrating to Room DB.  But I couldn't instantiate AndroidViewModel and get data.
This is the AndroidViewModel
class AdminExpensesVM(application: Application):AndroidViewModel(application) {
    private val repository:AdminExpensesRepo
     val readAll :LiveData<List<AdminExpensesData>>

    init {
        val adminExpensesDB=AdminExpensesDatabase.getInstance(application).adminExpensesDao
        repository= AdminExpensesRepo(adminExpensesDB)
        readAll=repository.getAllExpenses()
    }
   }

This is the Custom LinearLayout
class Admin_Calender : LinearLayout {

    private lateinit var adminExpensesVM: AdminExpensesVM;

constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {

  val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
  val view: View = inflater.inflate(R.layout.admin_calender, this)

  adminExpensesVM=ViewModelProvider.AndroidViewModelFactory.getInstance(context as Application).create(AdminExpensesVM::class.java)

    }

}

But this cannot be done becasue it get a error casting context to application. How can I do this? Is there anyway to get application to instantiate AndroidViewModel or is there any way to do it with only context?
Thank you

Answer: I don't really get your question but maybe this can help try to make it scoped with your activity
val adminExpensesVM: AdminExpensesVM by activityViewModels()

Comment: I got uresolved reference to the activityViewModel() , is there any dependancy for that?
Comment: implementation 'androidx.fragment:fragment-ktx:1.1.0'


Calculate $\lim_{x\rightarrow1}\frac{(1-x^2)}x$ by definition

Question: How do I calculate the $\lim_{x\rightarrow1}\frac{(1-x^2)}x$ using the δ/ε definition?
I'm losing my mind on this :c
I'm like lost after something like this:
|$\frac{(1+x)  (1-x)}x$ - L| < ε
Answer: To get you started, if you want to show that
$$\lim_{x \to c} f(x) = L$$
then you show, for all $\varepsilon > 0$, there exists $\delta > 0$ such that
$$0< | x-c| < \delta \;\;\;\;\; \text{implies} \;\;\;\;\; | f(x) - L | < \varepsilon$$
You wish to show that, in that case,
$$\lim_{x \to 1} \frac{1-x^2}{x} = L$$
But you need to first determine what $L$ should be. Looking at a graph would give us a good start: $L=0$.

To confirm this we want to show that, for all $\varepsilon > 0$, there exists some $\delta > 0$ such that
$$0 < |x-1| < \delta \;\;\;\;\; \text{implies} \;\;\;\;\; \left| \frac{1-x^2}{x} \right| < \varepsilon$$
Your goal: find the necessary $\delta$.
Wikipedia also has some worked examples you might find useful. I think that the thing you'll find common in these is that the $L$ you're looking for is "given." To my understanding you can't really find the limit outright from the definition, just verify whether something is indeed the limit. In that sense, then, you need to figure out the limit $L$ should be and then verify it by finding the corresponding $\delta$.
Some more definitions and examples can be found on Paul's Online Math Notes and on Brilliant.
Answer: Given $\varepsilon$, when $0<|1-x|<\delta < \frac{\varepsilon}{6}$,
then
$$ \bigg|\frac{1-x^2}{x}-0\bigg|= \bigg|
\frac{(1-x)(1+x)}{x}\bigg| <\delta \frac{2+2\delta}{1-\delta }<6\delta<
\varepsilon$$
Answer: $\lim_\limits{x\to 1} \frac {1-x^2}{x} = 0$
We must show that for any $\epsilon > 0$ there is a $\delta >0$ such when $|x-1|<\delta$  it implies that  $|\frac {1-x^2}{x} | < \epsilon$
$|\frac {(1-x^2)}{x}| = |1-x||\frac {1+x}{x}|$
Let's insist that $\delta < \frac 12$ then $|\frac {1+x}{x}| < 5$ (i.e. $\frac 12 < x < \frac 32 \implies x+1 < \frac 52$ and $x > \frac 12)$
$|\frac {(1-x^2)}{x}| < 5\delta < \epsilon$
$\delta = \min (\frac 12, \frac {\epsilon}{5})$
Answer: Let $$0<|1-x|<\delta$$ $$ \Rightarrow |(1-x) -0| <\delta \Rightarrow \left|(1-x) \frac{2-\delta}{1-\delta}-0\right| <\delta \left|\frac{2-\delta}{1-\delta}\right| $$
$$\Rightarrow \left|\frac{(1-x)(1+x)}{x}-0\right|<\delta \left|\frac{2-\delta}{1-\delta}\right|$$
$$ \Rightarrow \left |\frac{1-x^2}{x}-0 \right|< \epsilon(\delta) \Rightarrow \lim_{x\rightarrow 1} \frac{1-x^2}{x} \Rightarrow 0.$$


Is it possible to override the power off action?

Question: I'm trying to modify or override the functionality of power off menu button in android (not the button to screen on / off).
I want to fired a process before the device shutdown, run a process and after that shutdown the device
If this it's possible?
Comment: it is not and should not be possible. If it was, you could start an endless process, and prevent the device from shooting down
Comment: Thanks for your comment @VladyslavMatviienko
Answer: Simple answer: No.
This is not possible, without custom modification to your firmware or the core of the Android operating system, for a limited number of devices.
More info
So on a rooted device, you might be able to do that.
Check this link.
Comment: How can i do it with a rooted device? Because i have it, this idea i know only can run in a rooted device
Comment: i don't have the reputation to vote your answer. I go to test it. Thanks for your answer
Answer: Yes it is possible.You don't have to have a rooted device just use a broadcast.
In manifest:
<receiver android:name="com.example.broadcastreceiver.YourClass">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_SHUTDOWN" />
    </intent-filter>
</receiver>

YourClass:
public class YourClass extends BroadcastReceiver {
    @Override
    public void onReceive(Context c, Intent i) {
          if(i.getAction().equals("android.intent.action.ACTION_SHUTDOWN")){
                     //Fire your code here
          }
    }};
}

If it sounds impossible,Find another way to do the same thing ;)
Comment: @EduardoRotundo I didn't exactly get what you mean.Your English is not so clear.You want to prevent the shutdown now?And by the way you can also update an answer by pressing the arrow up button.
Comment: You can cancel the power menu on a certain device with root.You also can on other devices I suppose it's simple.If you need it I can help you with that too.(But it should be rooted)
Comment: I test this option and works! so now i go to break the shutdown sequence, because now the phone goes off but the debug point it's still alive until phone off
Comment: Umm,I'm not sure what you mean.So you want to cancel shutdown + process + shutdown manually?
Comment: I want trigger a process when the user press the power off option. This process can take about 20 minutes or less and after that turn off the phone
Comment: Ok I get it now.Well that's gonna be so annoying for the user.But anyway.You should ask another question with a better title mentioning this process is too long.Then call me there,I'll help you with that also.Just if you upvote my answer too.That would be appreciated :)
Comment: Sorry for not used a more explict title @stevemoretz
Comment: @EduardoRotundo check this topic: https://stackoverflow.com/questions/39064523/detect-power-button-long-press/39205019
Comment: after read the post and do some tests, i see the ShutdownThread process it's not available to override or modify, because the dispatchKeyEvent only works if the activity has focus
Comment: I'm not really into that,But I give you the idea all you need is to find a way to know when the power button is long pressed now I'll take it from here.You have root.So You do a shell input script to click on 0,0 and it will make the menu go away you do whatever you want now.After you're done by another shell command via root turn off the device the only part left to figure is the first part which is available in that link


Jquery in ajaxed loaded content referencing incorrect node id

Question: I have a list of nodes each with a click. The click sends a node reference argument which loads a new view using ajax. Jquery collects the node reference number via a hidden input value on the content-type-tpl.php. Likewise the nodes in the new view each have a click which sends a node reference argument which loads a new view using ajax. However while the clicks in the original view work correctly, the clicks in the newly called view do not reference the correct node. Instead of referencing the node id for the node which is clicked, the node id of the next node in the view is collected instead. Oddly when placing <?php echo $node->nid;?> on the content-type-tpl.php, the correct node id is echoed on the page. But sadly this is not the one sent to the view argument. So clicking any node in the the newly loaded ajaxed view, sends the id for the next node. Here's the javacript:
 Drupal.behaviors.ajaxlinks = function (context) {
    $('.morelink:not(.togg-processed)', context).addClass('togg-processed').each(function () {
      var myindex = $('.morelink').index($(this));
      var target = $('.newthing').eq($('.morelink').index($(this)))
      var nid = $(".mynid").eq(myindex).val();
    $(this).click(function() {
if (($('.hiddenrows').eq(myindex).is(":hidden"))
|| ($('.shownrows').eq(myindex).is(":visible")))
{
    $('.hiddenrows').eq(myindex).show();
    $('.newthing').eq(myindex).show();
      var toLoad = Drupal.settings.basePath + 'replies/' + nid;
      xhr = $.ajax({
        url: toLoad,
        success: function(data) {
        $(target).css( "height","200px" );
        $(target).html($(data));
     Drupal.attachBehaviors(context);
}
});
}
else
{
    $('.hiddenrows').eq(myindex).hide();
    $('.newthing').eq(myindex).hide();
}
    return false;

It's the same code so I can't see why it works differently in the newly loaded view. Can anyone spot what I am doing wrong?
Answer: Looks like Drupal.attachBehaviors should have fired on (target) instead of (context). It was refiring the script on the whole context instead of just the new ajaxed content. So I changed Drupal.attachBehaviors(context); to Drupal.attachBehaviors(target);
Now it works!


"Primary script unknown" while reading response header from upstream - NGINX

Question: Olá,
estou tentando executar meu site do Wordpress na Host que possui está configuração:

Ubuntu LTS 16.04, Nginx, Apache, MySQL, PHP, Webmin

Ao tentar entrar na página inicial, o erro que é exibido no arquivo de error log, é este abaixo:

2018/05/03 02:35:22 [error] 3372#3372: *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 184.108.40.206, server: meusite.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "meusite.com"

Alguma ideia do que possa ser?
Comecei a me aventurar agora na criação do meu próprio servidor, então os erros começaram a aparecer e preciso de ajuda para entender a raiz e tentar resolver.
Obrigada!
Comment: Se você tiver conhecimento em inglês (eu sou ruimzin) tem uma resposta aqui: https://serverfault.com/q/517190
Comment: @Don'tPanic Vou dar uma olhada!
Answer: O seu problema é esta na configuração fastcgi.
No Webmin >>> Vá para VirtualMin >>> Selecione o Dominio >>>
Services >> Server configuration >> Website Options
Lá deve ter mais de uma opção, alem do selecionado CGI.
Selecione outra opção e Salve.
O SITE NAO IRA FUNCIONAR (MAS VERIFIQUE, TALVEZ SEJA O CASO DE TROCAR SUA CONFIGURAÇÃO)
CASO SEU SITE NÃO VOLTE...
Faça o mesmo caminho acima e volte para CGI como estava.
Assim o seu site vai reconfigurar o SOCKET do CGI.

NGINX & APACHE é Servidor Web e Proxy Reverso
Isto é os dois só pode ser utilizado se você configurar em portas diferentes.
Por exemplo:
APACHE= PORTA:8080
NGINX= PORTA:80
Caso use cache como Varsish, verifique as configurações de portas
Contudo utilizando os dois é possivel.
Configurar o Nginx como um Servidor Web e Proxy Reverso Apache.
Comment: Na verdade, dá pra rodar o Apache como webserver e o NGINX como proxy, como é feito no VESTACP, por exemplo.


Icon doesn't load

Question: Hi my icons don't load and i don't know why. They should appear in the navigation. Im very new and don't find good new resources to learn.
Everything is old. Some links would help thank u.
Comment: In the future, it is substantially better to post the actual code instead of screenshots of your code. Stack overflow provides a way to format source code in questions and answers.
Answer: The GetView needs to set the image on the ImageButton in the layout. Notice that you aren't even using the items in your adapter? Instead of using a list of ImageButton why not accept the drawables, and then set the image of each ImageButton from the items? See an updated version of GetView (below) which should get you a working example of setting the image on the ImageButton in each of your buttons.
public override View GetView(int position, View convertView, ViewGroup parent) {
     View v = convertView;
     if(v == null){
         v = LayoutInflater.From(context).Inflate(Resource.Layout.MenuButtonLayout, parent, false);
     }
     var imageButton = v.FindViewById<ImageButton>(Resource.Id.myButton);
     imageButton.SetImageResource(Resource.Drawable.Noten);
     return v;
 }

Icon doesn't load


Fire event on create and another record

Question: I try to create company and user. When company was created should fire event created. I register observer and everything is ok. But user need to has password and email (this data are send from form) but company table doesn't have this fields. Currently I declare in Company model two fields public $tmpEmail and public $tmpPassword while I assign attributes I fill this properties. Afterwards I read this properties in my observer class, but for me is not good enough approach. How I can do it better?
Simplified example:
class Company extends Model
{
    $fillable = ['company_name', 'phone_number'];
}

class CompanyObserver
{
    public function created(Company $company)
    {
        print_r($company->company_name);
        print_r($company->tmpPassword);
        print_r($company->tmpEmail);
        $user = new User(['name' => $company->company_name', 'email' => $company->tmpEmail, 'password' => $this->tmpPassword);
    }
}

Comment: Where do you create the company? from an response function?
Comment: Currently in test (TDD :)), buy finally company will be created in controller.
Comment: Please consider my answer like an idea "well" formatted. Before downvoting writ in the comments. In your unit test you should test just the insert inside the model. In your controller you test company and user together
Answer: Just an idea formatted
In my opinion you are creating too many porposes in a model. Company should know just itself.
If you have a scenario like an action from a form:
public function actionFromForm(Request $request) {
   $company = //Save your model
   $user = new User(['name' => $company->company_name, 'email' => $request->input('tmpEmail'), 'password' => $request->input('tmpPassword'));
}

Comment: This is good when if I use this only in controlles, but I need something automatically, because I won't create `User` object each place when I want to create company. `Company` know only about itself, this is role of observer pattern to looking on company and after some action (in my case create) add user. You have right now `Company` has unnecessary info (about user) but this my question, how figure it out, using observer patter.

Fire event on create and another record


Can't expose port for podman pod in macvlan network

Question: I'm using podman 3.4.4 on Ubuntu 22.04 and am trying to setup a pod with a macvlan network.  I'm running several other macvlan containers without issues, but when trying to setup a pod (caddy + a backend & a frontend in one pod) I can't expose port 80/443 as they are already exposed.
Setting up the pod:
podman pod create --name baz \
  --network foonet \
  --dns 192.0.2.2 \
  --ip 192.0.2.10 \
  -p 80:80 \
  -p 443:443

foonet:
podman network create -d macvlan\
  -o parent=bridgeexample \
  --subnet 192.0.2.0/24 \
  --gateway 192.0.2.1 \
  --ip-range 192.0.2.0/24 \
  foonet

One of the containers in the pod, exposes port 80/443:
podman create --pod baz \
  --name baz_caddy \
  caddy:latest

The typical error message I've seen:
Apr 11 21:19:37 atomic podman[4039059]: Error: error starting container 30e70a74280cf68b5c92eb7b0f6955ee9c2f53396fe2f7fd1c48964f28ed8738: cannot listen on the TCP port: listen tcp4 :80: bind: address already in use

If I try to expose the port on the IP I've assigned the container (192.0.2.10:80:80) I get:
bind: cannot assign requested address

Any ideas?
Update: larsks was right, trying to export ports when using macvlan is incorrect. I removed the ports and things started working.
Thanks!
Comment: You don't need to publish ports when using a macvlan network; the containers are attached directly to the network. If a service is listening on port 80, you can connect directly to port 80 on the appropriate ip. Drop the `-p 80:80` and `-p 443:443` and see what happens.
Comment: Thank you! I knew that but somehow forgot it while trying to setup this. I then ran into another issue (containers expected a certain naming convention which I had deviated from) which was easily solved by --add-host.
Answer: larsks solved the issue, I had an accident while thinking I should expose ports for macvlan backed networks.


How can sort Antd table data by length, when the data contain a null value

Question: I want to sort a table by the length of the data. But there are some null values coming.
This is my sorter function
 sorter: (a, b) => a.rechargeType.length - b.rechargeType.length

following error coming when there is a null value
TypeError: Cannot read property 'length' of null

Answer: You can simply do that,
sorter: (a, b) => {
    if(a && a.rechargeType && a.rechargeType.length && b && b.rechargeType && b.rechargeType.length) {
        return a.rechargeType.length - b.rechargeType.length;
    } else if(a && a.rechargeType && a.rechargeType.length) {
        // That means be has null rechargeType, so a will come first.
        return -1;
    } else if(b && b.rechargeType && b.rechargeType.length) {
        // That means a has null rechargeType so b will come first.
        return 1;
    }

    // Both rechargeType has null value so there will be no order change.
    return 0;
}

This way null values will come last. For more reading about the return value of sort compare function you can read this.


is there a way to check if a word in a generated list, is inside a text file?

Question: I want to check if a word in a generated list is inside a text file
I made an anagram generator, and I want to see if the list created by that generator has a real word by checking if it's inside an English dictionary.
#input
word = input("Word: ")

#function to generate anagrams of the word
def make_anagram(word):
    if len(word) <= 1:
        yield word
    else:
        for let in make_anagram(word[1:]):
            for i in range(len(word)):
                yield let[:i] + word[0:1] + let[i:]

#function to check anagrams
def check_if_anagram(word):
    #this is the file with the dictionary
    file = open("english-words-master\words.txt")
    words = file.read()

    #here's where I'm havning trouble
    anagram = list(make_anagram(word))
    if str(anagram) in words and str(anagram) != word:
        print(str(anagram) + " is a real anagram.")
    else:
        print("there is no real anagram for " + word)
    file.close()

the second function always returns the else statement.
I'm still a beginner so I don't understand how lists work very well, what's wrong in the check_if_anagram function?
Answer: You are checking if the whole list is in the file. For example, if anagram = ['abc', 'acb'] There you are literally checking:
if "['abc', 'acb']" in words

Which will most likely never happen...
What you want to do, is check each anagram from the list:
anagrams = list(make_anagram(word))
for anagram in anagrams:
    if anagram in words and anagram != word:
        print(anagram + " is a real anagram.")
        break
else:
    print("there is no real anagram for " + word)


Change background of li element on hover that has a current image in li

Question: I'm made a image grid using a set of li elements and need to add a hover effect when you hover over each image in the li. I got it to work fine with the css opacity property for the .grid li a img:hover i set. When i however set a background image in here it doesn't show. Loading the browser and using the inspector shows the image loaded when i hover over it but visually it doesn't show. I tried setting the z index higher etc with no luck.
I'm open to doing this other wayys if better because each image will have its own different hover state.
HTML:

CSS:
ul.grid {
  list-style: none;
  margin: 20px auto 0;
  width: 798px;
  }

.grid li {
  float: left;
  margin: 0px 4px 0px 0px;
  }

.container {
  margin-left: auto;
  margin-right: auto;
  margin-top:50px;
  width: 513px;
  }

.grid li a img:hover {
  background: url(images/image1_hover.jpg) no-repeat;
  }

.grid li img {
  background-color: white;
  margin: 0;
  width: 262px;
  height: 200px;
  }

.grid li a {
  display: block;
  }

Answer: The problem you were having was related to apples and oranges. You had apples (IMG) tags on top of oranges (backgrounds)... so changing the background was working but your IMG was sitting on top of it - z-index would not help you. In this situation use background image alone.  See below.
Edited:  I see you also want them to be links.  The following will work for you.
That said, I would actually use a sprite rather than have 6 different images in this situation. And, the CSS below could likely be optimized, and certainly optimized by using LESS or SASS - but it's nearly 4 on a Friday and the company micro tap was flowing ;)

Answer: You may have an easier time using some jquery to change the source tag of your image when hovering over it.


How could I execute /_next/static/xxx.js by script tag

Question: I've customize next.config (webpack) to build a static js file (.next/static/loader.js).
The original loader.js is an IIFE:
(function stickerLoader(){
  alert('Hello');
  // ... some source code
}())

And its usage is like:

However, the above won't execute immediately, cause it was compile to:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["static/loader.js"],{

/***/ "./components/Sticker/loader.js":
/*!**************************************!*\
  !*** ./components/Sticker/loader.js ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports) {

(function stickerLoader() {
  alert('Hello');
  // ... some minified source code
})();

/***/ })

},[["./components/Sticker/loader.js","static/runtime/webpack.js"]]]);

Does Next.js has any settings could remove the WEBPACK WRAPPER, and leave my source code only, so my expected result would be like:
(function stickerLoader() {
  alert('Hello');
  // ... some minified source code
})();

My next.config.js:
module.exports = {
  webpack(config, options) {
    return merge(config, {
      entry() {
        return config.entry().then(entry => {
          return Object.assign({}, entry, {
            'static/loader.js': path.resolve(
              __dirname,
              'components',
              'Sticker',
              'loader.js'
            )
          });
        });
      }
    });
 };
};

Answer: If you want it without any webpack stuff, why do you add it to the webpack build?
If this is a simple js file, put it in the public/ (or static/ at v9.0.5 and below) folder as a regular static js file.
Comment: I agree your opinion which is also my current solution: I wrote a standalone script to call `terser` to minify multiple `loader.js` and write the result to `public/`.
Comment: I'm just curious to know if `next.js` have some alternative ways to achieve my objective...


How to find perpendicular distance from point to plane in $3D$.

Question: The line $L_1$ passes through point $A$ whose position vector is $3i - 5j + 4k$, and is parallel to the vector $3i + 4j + 2k$. The line $L_2$ passes through the point $B$ whose position vector is $2i + 3j + 5k$, and is parallel to the vector $i - j - 4k$. The point $P$ on $L_1$ and $Q$ on $L_2$ are such that $PQ$ is perpendicular to both $L_1$ and $L_2$. The plane $\pi_1$ contains $PQ$ and $L_1$, and the plane $\pi_2$ contains $PQ$ and $L_2$.
(i) Find the length of PQ.
Since $PQ$ is perpendicular to both lines, the cross product of both lines' directions is the direction vector of $PQ$
$\Rightarrow (3i + 4j + 2k) \times (i - j - 4k) = -7(2i - 2j + k).$
Hence $|PQ| = \sqrt{(4+4+1)} = \sqrt{9} = 3.$
(ii) Find a vector perpendicular to π1.
Since $\pi_1$ contains $PQ$ and $L_1$, the cross product of both direction vectors will be the normal vector of $\pi_1$
$\Rightarrow (2i - 2j + k) \times (3i + 4j + 2k) = -(8i + j - 14k).$
(iii) Find the perpendicular distance from $B$ to $\pi_1$.
$B$ was given as the position vector $(2i + 3j + 5k)$, which lies on the line $L_2$.
I can't figure out how to get the equation of $\pi_1$ because it involves getting a point on the plane (which would be $P$), and I can't figure out how to get point $P$ either.
If I had point $P$, I would have found the equation of $\pi_1$, and then, using the distance formula, found the shortest distance between $B$ and $\pi_1.$
How can I find this distance? Please explain
Comment: A piece of (unasked) advice: you're using physics notation, which for some of us poor mortal mathematicians is pretty annoying to read. Try to "translate" your notation to mathematical one (i.e., $\,8i+j-14k=(8,1,-14)\,$ and *perhaps* (just *perhaps*) more people around here will try harder to read all the above.
Comment: @DonAntonio this is maths A level, we are required to use many notations including this one; I personally prefer column notation however this is easier to type. Why is it so hard to read??
Comment: @Ozzy Is this question from Further Mathematics in A-level? I'm doing my A levels (excluding Further Math), and I have never seen a question like this. Just curious.
Answer: So I figured answer:
(iii) Using the distance formula, the shortest distance D from B to π1 is given by:
D = |ax + by + cz + d| / |n| where n is the normal to plane; a, b, c, d are the coefficients of the equation of the plane; x, y, z are the coordinates of the point from the plane.
π1: 8i + j - 14k = 75
B: 2i + 3j + 5k
D = |(8)(2) + (1)(3) + (-14)(5) + (-75)| / sqrt(64+1+196)
D = |-126| / sqrt(261)
D = 126/16.155 = 7.799 ~= 7.80


Production Kafka configuration in Lagom Framework with Kubernetes?

Question: How to configure kafka cluster in lagom framework in kubernetes in production mode.
Its expecting kafka_native service while starting service container.
Cassandra cas_native successfully configured but kafka not working
Comment: [This](https://www.lagomframework.com/documentation/1.3.x/scala/KafkaClient.html#Lagom-Kafka-Client1) could be useful.
Comment: Have you read [the blog post](https://developer.lightbend.com/guides/lagom-kubernetes-k8s-deploy-microservices/) about it?
Comment: @erip yes we read that blog and we deployed kubernetes without kafka

that blog only mentioned cassandra not kafka
Comment: we even contracted lightbend about this but they are asking to take enterprice subscription for conductr, but not supporting on kubernetes
Answer: As you are using Kubernetes you can use service locator DNS and take advantage of Kube DNS Service... You have to have a headless service in front of  Kafka...


Find the range of values for $a+b$ when $y=-\frac{1}{8}x^2+ax+b$ is tangent to the $x-$axis.

Question: Given the function $$y=-\frac{1}{8}x^2+ax+b\tag{*}$$ I'm asked to find the range of values for $a+b$ when $y$ is tangent to the $x-$axis. I know the answer is $a+b\leq\frac{1}{8}$ but I haven't found a way to confirm it.
This is just the final part of the exercise. In the rest of it, I found the vertex $V(p,q)$ for (*), which coordinates are, $$p=4a, \hspace{10mm} q=2a^2+b,$$ and found that when $V$ lies on $x+y=1,$ then $b=-2a^2-4a+1$. This let us conclude that $\beta(a,b)=8a+b$ reaches its maximum at $(1,3).$ However I don't know how this information is useful to solve the last part of the exercise.
I tried to use the fact that the roots of (*) are,
$$x=\frac{-a\pm\sqrt{a^2+b/2}}{-1/4}$$ if $y$ is tangent to the $x-$axis, then $a^2+\frac{b}{2}=0$. But I don't know how to continue from here since I'm going to find an equality, not an inequality as I'm asked to do.
Answer: If $f(x)=-\frac{x^2}8+ax+b$, then $f'(x)=-\frac x4+a$, and therefore $f'(x)=0\iff x=4a$. So, since the graph of $f$ as tangent to the $x$-axis, $f(4a)=0$, which means that $b=-2a^2$. But then\begin{align}a+b&=a-2a^2\\&=-2\left(a-\frac14\right)^2+\frac18\end{align}and$$\left\{-2\left(a-\frac14\right)^2+\frac18\,\middle|\,a\in\Bbb R\right\}=\left(-\infty,\frac18\right].$$
Answer: Given parabola is tangent to x-line iff it discriminat is $0$, so $$a^2+b/2 =0$$
So $f(a)=a+b = a-2a^2$ which is a quadratic function on $a$ and achieves the maximum at $a={1\over 4}$, so $f(a)\leq {1\over 4}-{1\over 8} = {1\over 8}$.
Answer: $f(x)=-\frac{1}{8}x^2 + ax +b. \\
f'(x)=-\frac{1}{4}x +a.\\
f'(x_0)=0 \Leftrightarrow x_0=4a.\\
f(x_0)=f(4a)=2a^2+b.\\
f(x_0)=0 \Leftrightarrow b=-2a^2.\\S(a, b)=a+b = a + (-2a^2).\\
S'(a, b)=-4a+1.\\
S'(a, b)=0 \Leftrightarrow a=\frac{1}{4}.\\
S(a, b) \le -2(\frac{1}{4})^2 + \frac{1}{4}=\frac{1}{8}.
$


Why does Meshgrid differ from the for loop here for filling in this tensor?

Question: I'm trying to fill in this 3dimensional tensor efficiently using Meshgrid instead of using for loops, and it seems like the Meshgrid way does not give me what I expect( for loop way).
import numpy as np

def s(x,y,z,w):
    return x + y + z + w + .1*.1

arr_x = [5,6,3,4,3]
arr_y = [5,3,3,10,34]
T_1 = [5,6,10]
nx = len(arr_x)
ny = len(arr_y)

zx, zy, zt = np.meshgrid(arr_x, arr_y, T_1, sparse = True)
Z = s(zx, zy, zt, 0)
print(Z[4])

for i in range(nx):
    for j in range(ny):
        for k in range(3):
            Z[i,j,k] = s(arr_x[i],arr_y[j],T_1[k],0)
print("----------")
print(Z[4])

Why do I get this as an output, I would think they would be the same?

[[44.01 45.01 49.01]
 [45.01 46.01 50.01]
 [42.01 43.01 47.01]
 [43.01 44.01 48.01]
 [42.01 43.01 47.01]]
----------
[[13.01 14.01 18.01]
 [11.01 12.01 16.01]
 [11.01 12.01 16.01]
 [18.01 19.01 23.01]
[42.01 43.01 47.01]]

Answer: Add indexing='ij' to the meshgrid call, and all will be well.  It's a difference between matrix indexing and image indexing, where x and y are swapped.


Wait com AlertDialog()

Question: boas!
Meu problema é com o AlertDialog assíncrono do Xamarin.Android. Eu tenho uma classe com um método que monto um alerta com alguns campos... Com os dados desses campos, eu monto um objeto para fazer meu CRUD.
O problema está na hora de chamar o AlertDialog, quando chamo, ele é montado e logo instancia meu objeto com os valores vazios do AlertDialog, pois é assíncrono.
llCompraAtiva.Click += delegate
{
    this.RunOnUiThread(() => dadosCompra = Util.modalPagamento(this));
    string teste = dadosCompra.NumCartao;
};

Pensei em montar algo com Thread, mas não me saí bem...
Resumindo: Preciso digitar os dados nos inputs, depois instanciar o objeto com os valores desses inputs.
Alguém poderia me ajudar?
Tks
Comment: Qual o retorno de: Util.modalPagamento(this) ? É um Task ?
Comment: Esquece, confundi com Xamarin.Forms =D
Comment: Hahaha, sem problemas, me ajudou alot! :D
Answer: Não é recomendado bloquear a Thread principal para esperar pelo Dialog, portanto, você precisa fornecer o handler para o proprio Dialog para ele tratar, assim quando o usuário confirmar a ação no Dialog, este, vai acionar o handler para preencher o objeto.
Escrevi um exemplo, mas não tive tempo de testar, acho que vai te dar uma ideia
using (var builder = new AlertDialog.Builder(this))
{
    var title = "Edite seus detalhes: ";
    builder.SetTitle(title);
    builder.SetPositiveButton("OK", OkAction);
    var customDialog = builder.Create();
    customDialog.Show();
}

E o handler do botão:
private void OkAction(object sender, DialogClickEventArgs e)
{
    var botao = sender as Button;
    if (botao != null)
    {
        var resultado = BuscaResultado();
        _dadosCompra.NumeroCartao = resultado;
    }
}

Comment: Consegui aqui, me ajudou bastante! Obrigado @FBatista

Wait com AlertDialog()


How do you upload an image from Android SD card to Django server?

Question: I have the URI address, and am basically trying to display the image on an html page. The html page just displays an empty image. I really have no idea how to do this, as I am a beginner in both Android and Django. Here is my code:
Android Studio Code. I made a new file in my sample java files packages:
public class ImageHTTPPostRequest
{
public void doFileUpload(String path){
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String urlString = "http://127.0.0.1:8000/";   // server ip
    try
    {
        //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(CameraIntentActivity.photoUriPath) );
        // open a URL connection to the Servlet
        URL url = new URL("http://127.0.0.1:8000/");
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+"    ");
        dos = new DataOutputStream( conn.getOutputStream() );
        dos.writeBytes(lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + path + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0)
        {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(lineEnd);

        // close streams
        Log.e("Debug", "File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }

    //------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream ( conn.getInputStream() );
        String str;
        while (( str = inStream.readLine()) != null)
        {
            Log.e("Debug","Server Response "+str);
        }
        inStream.close();
    }
    catch (IOException ioex){
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
}
}

Here is my Django code:
views.py
def imageUpload(request):
form = PhotoForm(request.POST, request.FILES)
if request.method=='POST':
    if form.is_valid():
        image = request.FILES['photo']
        new_image = Photo(photo=image)
        new_image.save()
        response_data=[{"success": "1"}]
        return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')

forms.py
class PhotoForm(forms.Form):
     uploadImage = forms.FileField(label='uploadImage')

models.py
class Photo(models.Model):
user = models.CharField(max_length=5000)
photo = models.FileField(upload_to='memorylane/static/images')
uploaded = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

def __unicode__(self):
    return '%s' % self.title

and then the html page. I really have no idea what to have here:

<!DOCTYPE html>

{% load staticfiles %}
{% include 'head.html' %}

 <title>Image Upload</title>

Thanks!
Comment: Please mention what issue you are facing i.e. any exception occurring or code is not working?
Comment: When i run the html page, imageUpload, it says: The view didn't return an HttpResponse object. It returned None instead.
Comment: Set content-type not mime-type
Comment: It still returns the same error.
Comment: Ok, the error was because i wasn't actually rendering the page, but now it just shows a blank image.
Answer: if i understand your question very well, this should work for the html page rendering.

views.py

def imageUpload(request):
   form = PhotoForm()
   if request.method=='POST':
       form = PhotoForm(request.POST, request.FILES)
       if form.is_valid():
           image = request.FILES['photo']
           new_image = Photo(photo=image)
           new_image.save()
           response_data=[{"success": "1"}]
           return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
    return  render(request, 'page.html',{"form": form}, context_instance=RequestContext(request))

but i must confess i dont understand what you meant by 'android upload to django server'


Which Delphi Version supports which object file format?

Question: I am searching for a list of supported object file formats for each delphi version. Object files should be linked with something like: <code>{$L lib/object.o}</code>.
The Reason for this is a linker error in Delphi7 for a project i maintain. The error does not occur in compilers >XE3. I have only XE3 and above to test.
Has someone maintained a list or knows a reference to one where i can find informations about the supported format and/or changes with newer versions, maybe also problems with object files, etc?
I would like to help a user of the project with this problem (lz4-delphi issue).
Answer: The change came with XE2 which added support for the COFF object format. Prior versions only supported OMF objects.
The change to add support for COFF was driven by the new 64 bit compiler, introduced in XE2. Embarcadero did not have a 64 bit C++ compiler at that time and so needed to link objects produced by another compiler. They chose to use the MS compiler which emits COFF objects.
Allen Bauer's answer to a question that I asked contains more detail.
In practical terms this means that for Delphi 7 you will need to compile the source code with bcc32. Or compile the C code with some other compiler but then link to a DLL.
Comment: Thx, i hope this information helps the D7 users of my project. I linked him to this.
Comment: Have you any experience with object file converters like: http://agner.org/optimize/#objconv ? Should i suggest this?
Comment: No. Suggest recompiling with bcc32. That is if you want to suggest a way forward that has any prospect of success. It's also fairly miraculous that anyone managed to get a mingw object to link. I never succeeded, but perhaps that was because I was linking to 64 bit. My own code base uses bcc32 for 32 bit and msvc for 64 bit.
Answer: For future reference, Delphi 10.1 Berlin and 10.2 Tokyo both support ELF64 format, and also COFF.


Default entity ID for _entity_view in routing.yml

Question: I've a custom content entity (created using Config pages module) which is used as a welcome screen / dashboard. Privileged super editors can edit those content entities, normal editors can only view it.
The config pages module itself does not provide routes to view modes (only to edit forms), so I used the core's generic _entity_view to create routes for the normal editors myself:
This is my_module.routing.yml
my_module.view_config_pages:
  path: '/admin/config_pages/{i_dont_want_no_parameter}'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        i_dont_want_no_parameter:
          type: 'entity:config_pages'

This works with URLs like /admin/config_pages/1, /admin/config_pages/2 etc... But I want to create nice, parameter-less, named routes to specific entity IDs. Something similar to my dummy-code below
my_module.view_welcome:
  path: '/admin/welcome'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        yeah_no_parameter:
          type: 'entity:config_pages'
          id: 1
my_module.view_stats:
  path: '/admin/stats'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        yeah_no_parameter:
          type: 'entity:config_pages'
          id: 2

Can this be done with _entity_view in YAML files without coding a custom controller?
Answer: The default ID can be set in the defaults section, here is an example:
my_module.view_dashboard:
  path: '/admin/dashboard/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 123
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

my_module.view_stats:
  path: '/admin/stats/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 456
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

This solution creates nice URLs without any controller.


React Native: cant change button style

Question: I am trying to change the style of a button in React Native, but the edits for the button colour, margin, outlines etc aren't working at all. Here is the pic. Below is my code for HomeScreen.js
import React from 'react';
import {
    StyleSheet,
    TextInput,
    View,
    Text,
    Button,
    ScrollView,
    Image,
    Keyboard,
    TouchableOpacity,
    KeyboardAvoidingView,
} from 'react-native';

function HomeScreen({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Image
                source={require('../image/success.png')}
                style={{
                    width: '50%',
                    height: 100,
                    resizeMode: 'contain',
                    marginTop: 0,
                }}
            />
            <Text style={{
                fontSize: 20,
                textAlign: 'center',
                marginLeft: 35,
                marginRight: 35,
                marginTop: 0,
                marginBottom: 10,
                color: '#00a3cc'
            }}>
            {'\n\n'}
            This is the Home Screen
            </Text>
            <Button
            style={styles.buttonStyle}
            onPress={() => navigation.navigate('Settings')}
            title="Go to Settings"
            />
        </View>
    );
};

export default HomeScreen;

const styles = StyleSheet.create ({
    buttonStyle: {
        backgroundColor: '#7DE24E',
        borderWidth: 0,
        color: '#FFFFFF',
        borderColor: '#7DE24E',
        height: 40,
        alignItems: 'center',
        borderRadius: 30,
        marginLeft: 35,
        marginRight: 35,
        marginTop: 20,
        marginBottom: 25,
    }
});

Some help would be appreciated, let me know if more info is required. Thanks in advance.
Answer: You should use TouchableOpacity instead.
import React from 'react';
import {
    StyleSheet,
    TextInput,
    View,
    Text,
    ScrollView,
    Image,
    Keyboard,
    TouchableOpacity,
    KeyboardAvoidingView,
} from 'react-native';

function HomeScreen({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Image
                source={require('../image/success.png')}
                style={{
                    width: '50%',
                    height: 100,
                    resizeMode: 'contain',
                    marginTop: 0,
                }}
            />
            <Text style={{
                fontSize: 20,
                textAlign: 'center',
                marginLeft: 35,
                marginRight: 35,
                marginTop: 0,
                marginBottom: 10,
                color: '#00a3cc'
            }}>
            {'\n\n'}
            This is the Home Screen
            </Text>
            <TouchableOpacity
               onPress={() => navigation.navigate('Settings')}
               style={styles.buttonStyle}
            >
              <Text style={styles.btnText}>Go to Settings</Text>
            </TouchableOpacity>
        </View>
    );
};

export default HomeScreen;

const styles = StyleSheet.create ({
    btnText: {
       color: '#FFFFFF',
       fontSize: 18,
       textAlign: 'center',
    },
    buttonStyle: {
        backgroundColor: '#7DE24E',
        height: 40,
        alignItems: 'center',
        borderRadius: 30,
        marginLeft: 35,
        marginRight: 35,
        marginTop: 20,
        marginBottom: 25,
    }
});

Comment: Hi, that seemed to work. I can change the button's colour now. Thanks a lot.

React Native: cant change button style


Explanation for some parts of this proof.

Question: We want to prove that in a UFD the gcd exists.
In the proof we let $R$ be a UFD and $a,b \in R$
So we suppose that $a,b$ are not units because if one of them were the unit, the proof is trivial.
The proof now let $a,b$ be both non units.
Well we know that we can write $$a=T_1×...×T_m$$ and $$b=R_1×....×R_m$$ were $T_i$ and $R_j$ are irreducible elements.
Now we can rewrite them as $$a=p_1^{α_1}.....p_n^{α_n}$$
And $$b=p_1^{β_1}....p_n^{β_n}$$ were $p_i$ are prime obviously.
Here's my 1st question: how did we let the prime elements in both $a$ and $b$ be equal and with same index $n$?? Shouldn't they be different? Shouldn't we say that $b=q_1^{β_1}...q_m^{β_m}$??
Also:
it defines $s_i=min(α_i,β_i)$ and let $d=p_1^{s_1}...p_n^{s_n}$. again how are the primes equals to the case of $a$ and $b$?
The proof proceeded to show that $d$ is the gcd.
I can see why $d$ is the common divisor.
To show that d is the gcd, we let $x|a$ and $x|b$
Then if x is a unit then $x|d$
But what if x is non unit??
The proof needs details that the author didn't include or they're trivial but I don't see them.
Please help! :(
Answer: The trick is that we allow the exponents $\alpha_i,\beta_i$ to be zero, and the list $p_1,\dots,p_n$ contains all primes that divide either $a$ or $b$.
The other important thing is that in an UFD, $a\,|\,b$ iff for every prime $p$ and exponent $\gamma\in\Bbb N$ we have $p^\gamma\,|\,a\implies p^\gamma\,|\,b$, that is, for every prime $p$, if the exponent of $p$ in $a$ is $\alpha$ and in $b$ is $\beta$ (and a priori they can be zero as well), then $\alpha\le\beta$.
Comment: Suppose $x=\prod_iq_i^{\gamma_i}$ with $q_i$ irreducible with $x|a$ and $x|b$, then $\gamma_i>0$ implies that $q_i$ divides both $a$ and $b$, so it's among the $p_j$'s and $\gamma_i\le \alpha_i$ as well as $\le\beta_i$.
Comment: Yes, I figured out the last part. Sorry I deleted the comment before you replied. Thank you very much!


Problem with Validating the Integer Value in Java

Question: hi i am using Eclipse Rcp and i need to validate the textbox  that only accept the integer value for that i have use the code
 txtCapacity.addKeyListener(new KeyAdapter() {
              public void keyPressed(KeyEvent EVT) {

                    if((EVT.character>='0' && EVT.character<='9')){
                          txtCapacity.setEditable(true);
                           txtCapacity.setEditable(true);

                      } else {
                          txtCapacity.setEditable(false);
                             System.out.println("enter only the numeric number");
                      }
              }
      });

It validates But the Problem with this one is that i cannot use the Backspace key for deleteting the number. and please tell me idea for Validating the decimal too.
thanks in advance
Answer: Dont use the KeyListener! Use a VerifyListener instead as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
  @Override
  public void verifyText(VerifyEvent e) {
    final String oldS = text.getText();
    final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

    try {
      new BigDecimal(newS);
      // value is decimal
    } catch (final NumberFormatException numberFormatException) {
      // value is not decimal
      e.doit = false;
    }
  }
});

Answer: As you are using a listener, you can empty the text field, instead of making it not-editable. You can do something like this, the snippet is based upon your code.
txtCapacity.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent EVT) {
             if(!(EVT.character>='0' && EVT.character<='9')){
                    txtCapabity.setText("");
             }
        }
});

Or better if you use JFormattedTextField. I'm not sure if you have that in SWT, even if you don't then try to look for the similar.
Comment: well this code is allowing the character too. yea i am using the swt
Comment: Ansari thanks a lot for that i am going to vote up...can u have any idea for allowing decimal number
Comment: @Dinup: If you want to allow strict decimal than you need to some other event to handle that. Otherwise, if integer and decimal both would be fine for you, then make a check in the same method for multiple periods. I mean allow only one period, next time you find a period chop that off and reset the value back to the textfield.
Answer: Another possibility is to use the FormattedTextField-Widget from Nebular, see http://www.eclipse.org/nebula/widgets/formattedtext/formattedtext.php
The advantage is that you only have to provide a pattern, there is no need to write your own listeners..
Answer: You can use this function to validate if the number:

    public static int validateInteger(String number)
    {
        int i = -1;

        try {
            i = Integer.parseInt(number);
        }
        catch (NumberFormatException nfe)
        {}
        catch (NullPointerException npe)
        {}

        return i;
    }

If the function returns a value less than zero, then it is not a valid positive number.
Answer: For validating if a value is infact decimal or not, you can simply use -
try {
        new BigDecimal(value.toString());
        // value is decimal
} catch (NumberFormatException numberFormatException) {
    // value is not decimal
}

Answer: You should probably set a Document on your text box. You can implement a customer Document to filter for valid input to satisfy your requirements. Each time text is added or removed from your field, the Document will check if the overall input is valid.
Answer: txtfield.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent evt) {

        char c=evt.getKeyChar();
        if(Character.isLetter(c))
        {
            JOptionPane.showMessageDialog(null, "PLEASE ENTER A DIGIT", "INVALID NUMBER", JOptionPane.ERROR_MESSAGE);
            txtfield.setBackground(Color.PINK);
            txtfield.setText("");

            String s = txtfield.getText();
            if(s.length() == 0){
                txtfield.setBackground(Color.PINK);
            }
        }
        else
        {
            txtfield.setBackground(Color.white);
        }
    }
});

Comment: You can try this one chetan txtfield.setBackground(SWTResourceManager.getColor(warnColor));
Comment: if(s.length() == 0){
                    txtfield.setBackground(Color.PINK);
                }
is not working but m still working on it. Sorry about that