Visualize tangent plane for mean squared error loss function

Question: I would really appreciate your help on a rather simple issue that I just can't solve on my own. I'd like to visualize gradient descent for a simple linear regression problem with two parameters $\theta_0$ (intercept) and $\theta_1$ (slope) using mean squared error as the cost function. What I'd like to visualize is a 3d plot of the cost function and the corresponding tangent plane for different $\theta_0$, $\theta_1$.
Here's what I have so far:
Cost function:
$$J(\theta_0,\theta_1)=\frac{1}{2m}\sum_{i=1}^{m}{(\theta_0 + \theta_1 x_{1}^{(i)}-y^{(i)})^2}$$
Partial derivative wrt $\theta_0$: $$ J_{\theta_0}(\theta_0, \theta_1) = \frac{1}{m} \sum_{i=1}^{m}{(\theta_0 + \theta_1 x_{1}^{(i)} - y^{(i)})} $$
Partial derivative wrt $\theta_1$: $$ J_{\theta_1}(\theta_0, \theta_1) = \frac{1}{m} \sum_{i=1}^{m}{(\theta_0 + \theta_1 x_{1}^{(i)} - y^{(i)})(x_{1}^{(i)})} $$
Let's say my tangent plane kisses the loss function surface plot at $(\theta_0,\theta_1,z)=(1,2,3)$. So if I want to know the z-value at $(\theta_0,\theta_1)=(4,5)$ I would to the following:
$$ z = J_{\theta_0}(1,2)(\theta_0-1)+J_{\theta_1}(1,2)(\theta_1-2)+3 $$
$$ z = J_{\theta_0}(1,2)(4-1)+J_{\theta_1}(1,2)(5-2)+3 $$
However, if I implement all of this in python my tangent plane won't end up where I would expect it to be. Here's my code:
import sympy as sp
import numpy as np
import plotly.graph_objects as go
import dash_html_components as html
import dash_core_components as dcc

# Generate a linear dataset
m = 100
X = 2 * np.random.rand(m, 1)
y = 4 + 3 * X + np.random.randn(m, 1)

# Append ones for bias term
X_b = np.c_[np.ones(len(X)),X]

# Loss function (j), its derivatives (djt0, djt1) and equation for tangent plane (z)
j = lambda theta0,theta1: 1/2*1/m*((X_b.dot(np.array([[theta0],[theta1]]))-y)**2).sum()
djt0 = lambda theta0,theta1: 1/m*(X_b.dot(np.array([[theta0],[theta1]]))-y).sum()
djt1 = lambda theta0,theta1: 1/m*((X_b.dot(np.array([[theta0],[theta1]]))-y)*X_b[:,1]).sum()
z = lambda theta0,theta1: djt0(10,10)*(theta0-10)+djt1(10,10)*(theta1-10)+j(10,10)

# setup sympy
theta0,theta1 = sp.symbols('theta0,theta1')
loss_surface = sp.lambdify((theta0,theta1), j(theta0,theta1))
tangent_plane = sp.lambdify((theta0,theta1), z(theta0,theta1))

# grid and plot
points = np.linspace(-20,20,90)
xgrid,ygrid=np.meshgrid(points,points)

fig = go.Figure(
    data=[
        go.Surface(z=loss_surface(xgrid,ygrid),x=xgrid,y=ygrid),
        go.Surface(z=tangent_plane(xgrid,ygrid),x=xgrid,y=ygrid)
    ]
)

fig.update_layout(
    scene = dict(
        zaxis = dict(range=[0,1600]))
)

fig.show()

Note: the z-lambda function is set for $(\theta_0,\theta_1)=(10,10)$. So I would expect to see to see a tangent plane touching the loss surface at $(10,10)$.
Here's my current result:
loss function looks okay, tangent plane not really
Is there anything obviously wrong in the equations? If not, then I probably messed up the matrix computation in python.
Thank you!
Answer: Solved it! One of the numpy arrays had the wrong shape, which messed up the $J_{\theta_1}(\theta_0,\theta_1)$ computation.
This fixed the problem:
djt1 = lambda theta0,theta1: 1/m*((X_b.dot(np.array([[theta0],[theta1]]))-y)*X_b[:,1].reshape(-1,1).sum()

Now the results look perfect and I can plot tangent planes for different $\theta_0$, $\theta_1$ values.

Hope that helps.
Comment: Hi phil, I've been trying to use your code with sympy but don't quite get the same results, could it be that some other things were changed too?


Create/Modify a Virtual Host and Reload Apache from Inside Rails App

Question: My application is a set of two rails applications. Based on some parameters in first app. I need to setup the virtual host of the second app. I just need to change the ServerName and ServerAlias in apache VH and enable the site using a2ensite and then 'apache2 reload '.
How can I do this from within a rails application?
Thanks,
Imran
Answer: First of all: be aware that enabling web-apps to change the server configuration is a security risk.
<code>#  First, open the config file
fd=File.open('/etc/apache2/sites/yoursite', 'r+')
#  read in the contents
content=fd.read
#  now replace the ServerName and ServerAlias lines with your new setting
if content.gsub!(/ServerName(.*)/,"ServerName NewServerName") and content.gsub!(/ServerAlias(.*)/,"ServerAlias NewServerAlias")
  fd.rewind
  puts "\tsaving file"
  fd.write content
end
fd.close
</code>
I did not test neither code nor the regular expressions, please load the relevant parts of your config file into rubular.com and roll your own regex.
Maybe you should also make a backup before saving using
<code>File.copy(file,file+".bak",true)
</code>


How much time should I spend learning a song on piano?

Question: I am following the Alfred's adult course level 1 book and given that songs are very simple I have come across an issue when exactly do I know I'm ready to move on to the next lesson? I tend to go if i play this piece three times in a row with no error I'm ready is this a good rule? Because by no shape or form have I mastered these songs it just seems a bit odd to spend days or even weeks on something a simple as row your boat if I get the gist of the song and if my successful plays out weight the unsuccessful ones I go the next lesson is this wrong? When did you ladies and gents knew it was time to move on? I'm lost.
Comment: because you're learning from a beginning book, the goal of the pieces is to build the skill to play more challenging pieces. (finger dexterity, reading the sheet music.) if you feel fairly comfortable with the piece, then you're ready to move on- at this level.
Answer: I think it's best to always play a little above your level so you are being challenged. First of all you don't want to get bored.
Secondly being perfect is a goal that will just drive you crazy. Learning an instrument is not a linear curve. I look at it as more of a two steps forward and one step back. And by that I mean move on to a harder piece, but remember that there will always be something more you can get out of a tune, even a simple one like row row.  Keep pushing ahead unless you are really struggling and then by all means slow down and work on stuff.
Also there have been studies about leaning that show we do better if you practice multiple things in a session and move around a bit. So maybe have three or four things you are working on in a practice session and divide your practice up between then. Source for that: https://bulletproofmusician.com/why-the-progress-in-the-practice-room-seems-to-disappear-overnight/
This link also has good stuff about, limiting distractions, setting goals, and other general practice tips:
https://www.npr.org/sections/deceptivecadence/2013/09/03/216906386/10-easy-ways-to-optimize-your-music-practice


Trajectory in the Lienard system

Question: I'm read about a Lienard System in Perko books, but I don't understand how this applies

I have managed to understand the proof, the shape of the trajectory is intuitively clear, doing an analysis of the vector field $F(x,y)=(y-F(x),-g(x))$, b ut how do I formally justify it? Any suggestion? If anyone knows a book or article where this system and its generalizations are treated in detail, I would be very grateful if you could cite it.
Postscript: The result mentioned in Perko is as follows (Ordinary differential equations by Philip Hartman):
Comment: Is this correct, you start with $\ddot x+f(x)\dot x+g(x)=0$, for the phase portrait set $y=\dot x+F(x)$, $F'(x)=f(x)$, $F(0)=0$, $xg(x)\ge 0$, $g(0)=0$ so that the system is $$\dot x = y-F(x),\\\dot y=-g(x).$$
Comment: @LutzLehmann I know, my question is not about the solution. My question is about justifying that every trajectory that starts from $P_0$ must necessarily go through $P_4$.
Comment: Are the following steps and gaps exact enough? $x>0$ initially due to the start, $y$ is falling as long as $x>0$. $F$ is eventually increasing, the falling and rising curves have to meet, by continuity. This should still be easy. Now $x$ is falling, $y$ is still falling, is a further crossing of the graph of $F$ possible? If yes, the argument for a downwards crossing repeats. Need to show that this can not repeat indefinitely, as $y$ is always falling and $F$ bounded below on the finite interval. It remains to show that $x$ can not have a positive asymptotic limit.
Answer: I too can not see the value of the cited theorem without further context.
Let's fixate what is obviously true:

As long as $x>0$ we have $\dot y=-g(x)<0$, so $y$ is at least non-increasing, and with $xg(x)\ge cx^2$ or a similar coercivity condition, $y$ will also be strictly decreasing until $x$ crosses again to negative values.

Due to $\dot x=y-F(x)$, $x$ will be increasing as long as $y>F(x)$. As $y$ is falling and $F(x)$ eventually increasing towards $+\infty$, there will be a cross-over point.

If $y\le F_\min-\epsilon$, where $F_\min$ is the minimum value taken by $F$ on $[0,\infty)$, then from this moment on $\dot x\le-\epsilon$, so $x$ has an upper bound that falls to zero in finite time.

It remains to cover the segment from the crossover $y(t_2)=F(x(t_2))$ to some time $t_3$ where $y(t_3)<F_\min$. Consider $v=\dot x=y-F(x)$ with
$$
\dot v =-g(x)-f(x)v,
\\
\frac{d}{dt}(e^{F(x)}v)=-g(x)e^{F(x)}.
$$
At the cross-over point $t_2$ we have $v=0$ and thus $\dot v<0$. With the integrating factor in the second equation we see that $e^{F(x)}v$ is strictly decreasing as long as $x>0$. So as $e^{F(x)}v<-\epsilon$ for $t>t_2+\delta$ for some $\epsilon,\delta>0$, we also get $\dot x=v<-\tilde\epsilon$ as $F$ is bounded on $[0,x(t_2)]$. This again gives an upper bound for $x$ that falls to zero in finite time.
Answer: To be honest, the theorem you quote is a bit out of context for my taste. For that reason, maybe one can just cook up their own argument (or maybe that argument is analogous to the theorem, I am not sure). So here is what I think, by assessing the situation quickly. I am going to assume we are dealing with the following system of ODEs:
\begin{align}
&\frac{dx}{dt} \,=\, y \, -\, F(x)\\
&\\
&\frac{dy}{dt} \,=\, -\, g(x)
\end{align}
where $F(x)$ and $g(x)$ are continuously differentiable functions with enough continuous derivatives with respect to $x$. I am assuming the graph of the function $y = F(x)$ is as depicted on your diagram, and I am going to assume that
\begin{align}
&g(x) < 0 \,\,\text{ for }\,\, x < 0\\
&g(x) = 0 \,\,\text{ for }\,\, x = 0\\
&g(x) > 0 \,\,\text{ for }\,\, x > 0\\
\end{align}
So basically, to analyse this situation, I would consider the following four curves :
\begin{align}
L \, &=\, \big\{\, (x, y) \in \mathbb{R}^2 \,\, :\,\, x = 0\,\,\text{ and }\,\,  y > 0\, \big\}\\
FG_{+} \, &= \, \big\{\, (x, y)\in \mathbb{R}^2\, \,:\, \, y = F(x) + g(x) \text{ where } x > 0\, \big\}\\
R \, &= \, \big\{\, (x, y)\in \mathbb{R}^2 \, \, :\,\, y = F(x) \text{ where } x > 0\, \big\}\\
FG_{-} \, &= \, \big\{\, (x, y)\in \mathbb{R}^2\, \,:\, \, y = F(x) - g(x) \text{ where } x > 0\, \big\}
\end{align}
With these four curves as boundaries, define the two bigger domains
\begin{align}
&D_{+} \,=\, \big\{ \, (x, y)\in \mathbb{R}^2\, \,:\, \, y \, > \, F(x) \,\text{ and }\, x > 0\,  \big\}\\
&D_{-} \,=\, \big\{ \, (x, y)\in \mathbb{R}^2\, \,:\, \, y \, < \, F(x) \,\text{ and }\, x > 0\,  \big\}
\end{align}
and the  four subdomains
\begin{align}
&D_{x+} \,=\, \big\{ \, (x, y)\in \mathbb{R}^2\, \,:\, \, y \, > \, F(x) + g(x) \text{ and } x > 0\,  \big\}\\
&D_{y+} \,=\, \big\{ \, (x, y)\in \mathbb{R}^2\, \,:\, \,  F(x) + g(x)
\, >\,  y > F(x)\,  \big\}\\
&D_{y-} \,=\, \big\{ \, (x, y)\in \mathbb{R}^2\, \,:\, \, F(x) \, >\, y \,>\, F(x) - g(x)  \text{ and } x > 0\,  \big\}\\
&D_{x-} \,=\, \big\{ \, (x, y) \in \mathbb{R}^2\, \,:\, \, F(x) - g(x)\, >\, y \text{ and } x > 0\,  \big\}
\end{align}
where $D_{x+} \cup D_{y+} \subset D_+$ and $D_{x-} \cup D_{y-} \subset D_{-} \,$.
Assume that for some interval $t \in (\alpha, \beta)$ a solution $\big(\,x(t), \, y(t)\,\big)$ of the original system of differential equations lies in the domain $D_{+}$. Then, since $x > 0$
$$\frac{dx}{dt} \, = \, y - F(x) \, > \, F(x) + g(x) - F(x) \, =\, g(x)
\, >\, 0$$ which means that $x=x(t)$ is a monotonously increasing function, and as such it has a well defined inverse $t = t(x)$ and therefore, $y=y(t)$ can be reparametrized as $y = y\big(t(x)\big) = y(x)$ and so the solution trajectory of the original system can be reparametrized as $\big(x, \, y(x)\big)$, where, by the chain rule, $y=y(x)$ should satisfy the differential equation
$$\frac{dy}{dx} \,=\, \frac{dy}{dt} \frac{dt}{dx} \, =\, \frac{\,\,\frac{dy}{dt}\,\,}{\frac{dx}{dt}} \,=\, \frac{-\,g(x)}{y - F(x)} \, =\,  \frac{g(x)}{F(x)-y} $$ or in short
$$\frac{dy}{dx} \, =\,  \frac{g(x)}{F(x)-y} $$
One can check that in $ D_{+}$ one has $\frac{dy}{dx}\,=\,\frac{g(x)}{F(x)-y} \, < \, 0$, because $g(x) > 0$ and $y > F(x)$ implies $F(x) - y < 0$, which means that $y=y(x)$ is a monotonously decreasing function.
Hence, for $x > 0$ the solution trajectory $(x, \,y(x))$ has the property $y(x) < y(0) = y_0$. The initial condition $y_0$ can be taken to be the $y$-coordinate of the point $P_0 = (0, y_0)$ on the picture.
Next, we will apply the following theorem from the theory of systems of ordinary differential equations:
Theorem. Let $f \, : \, U \, \to \, \mathbb{R}^n$ be a Lipschitz continuous function (this includes continuously differentiable functions) defined on an open set $U \, \subset \, \mathbb{R} \times \mathbb{R}^n$. Furthermore, let $D \subset U$ be a bounded connected open subset of $U$ and let $(x_0, \,y_0) \, \in \, {D}$. Then there exists a unique (local) solution $y = y(x)$ of the initial value problem
\begin{align}
&\frac{dy}{dx} \, =\, f(x,\, y)\\
&y(x_0) \, =\, y_0
\end{align}
Furthermore, the solution $y = y(x)$ can be extended over a closed interval $x \in [a, b]$, so that $\big(x,\, y(x)\big) \in D$ for all $x \in (a, b)$, while $y(a) \in \partial D$ and $y(b) \in \partial D$.
By applying the theorem above to the equation $$\frac{dy}{dx} \, =\,  \frac{g(x)}{F(x)-y} $$ defined in the open set $U = \big\{\,(x,y) \in \mathbb{R}^2 \,\, :\,\, F(x) \neq y\,\big\}$ and restricted to the open bounded domain $D \,=\, D_{x+} \, \cap\, \big\{\,(x,y) \in \mathbb{R}^2 \,\, : \,\, y < y_0\,\big\} $, we can conclude that any solution in $D$, being decreasing, cannot go over the boundary $y = y_0$ and since it is extended forward, the only boundary component of $D$ it can intersect, as per the theorem, is the curve $FG_{+}$.
Absolutely analogously, in the domain $D_{+}$, any solution trajectory of the original system of differential equations can be reparametrized as $\big(x(y), y\big)$ where $x = x(y)$ is the solution to the differential equation
$$\frac{dx}{dy} \, =\,  \frac{F(x)-y}{g(x)} $$
Again, applying the theorem above, but this time for the latter differential equation defined in the open set $U = \big\{\,(x,y) \in \mathbb{R}^2 \,\, :\,\, g(x) \neq 0\,\big\}$ and restricted to the bounded open set $D = D_{y+} \cap\, \big\{\,(x,y) \in \mathbb{R}^2 \,\, : \,\, y < y_0\,\big\} $  we can conclude that any solution trajectory (x(y), y) in $D$ cannot go over the boundary $y = y_0$,  because the same trajectory can be reparametrized as $(x, y(x))$ with $\frac{dy}{dx} = \frac{g(x)}{F(x) - y}$ and we already know that such solution $y=y(x)$ is decreasing and cannot reach $y=y_0$. Therefore, according to the theorem above, the only boundary component of $D$ the solution trajectory can intersect is the curve $R$. This  point of intersection is denoted by $P_2$ on your picture.
The reason for this ping-pong between the two representations
$$\frac{dy}{dx} \,=\, \frac{g(x)}{F(x) - y} \, \text{ and } \, \frac{dx}{dy} \,=\, \frac{F(x) - y}{g(x)}$$ of a solution trajectory of the original system is because on the curve $L$ at the point $P_0$ we have $\frac{dy}{dx} = 0$ and  $\frac{dx}{dy} = \infty$, while on the curve $R$ at the point $P_2$ we have $\frac{dy}{dx} = \infty$ and  $\frac{dx}{dy} = 0$.
Following absolutely the same method for the other domain $D_{-}$, which splits into the subdomains $D_{y-}$ and $D_{x-}$, ping-ponging between the two differential equation representation of a solution trajectory of the original system, you can complete the argument that the solution trajectory reaches a point $P_4$ on the negative half of the vertical axis $x=0$.

Trajectory in the Lienard system


What justifies assuming that a level surface contains a differentiable curve?

Question: My textbook's proof that the Lagrange multiplier method is valid begins:

Let $X(t)$ be a differentiable curve on the surface $S$ passing through $P$

Where $S$ is the level surface defining the constraint, and $P$ is an extremum of the function that we're seeking to optimize. But how do we know that such a curve exists?
$S$ is specifically defined as the set of points in the (open) domain of the continuously differentiable function $g$ with $g(X) = 0$ but $\operatorname{grad}g(X)\ne0$. The function $f$ that we're seeking to optimize is assumed to be continuously differentiable and defined on the same open domain as $g$, and $P$ is an extremum of $f$ on $S$.
Answer: By the Implicit Function Theorem, near $P$ you can represent your level surface as a graph, say $z=\phi(x,y)$, where $\phi$ is continuously differentiable. If $P=\phi(a,b)$, take any line through $(a,b)$ and you get a nice curve.
Comment: Thanks, I'll think of this when I learn about the IFT. My book hasn't covered that yet, though - is there another way?
Comment: No, honestly. In most multivariable calculus courses, we wave our hands wildly at such questions :) And, unless you're taking a somewhat theoretical course, you won't see the Implicit Function Theorem until later in your mathematical life. :)
Comment: I don't understand what you mean by "represent a level surface as a graph". Could you be more explicit as to the nature of the function $\phi$? What is its domain/range? What is the relationship between its input and output?
Comment: For example, the sphere $x^2+y^2+z^2=1$ can be represented as a graph of $z=\phi(x,y)=\sqrt{1-x^2-y^2}$ near the point $P=(0,0,1)$. $\phi$ will map some open set in $\mathbb R^2$ to $\mathbb R$. The size of the open set depends on the nature of your function $g$. For my example, you will have the open unit disk $\{x^2+y^2<1\}\subset\mathbb R^2$.
Comment: My mistake. In that case I don't know a more accessible answer for you than Ted's, though here's my try: the fact that $S$ is a level surface does not matter. Through any point $p$ on any regular surface $M$ and for any vector $v$ tangent to $M$ at $p$, there is a differentiable curve $\alpha$ on $M$ passing through $p$ with $\alpha'(0)=v$. But this is still just a special case of Ted's answer.
Comment: @proximal: The issue, of course, is to justify why a level surface with $\nabla g\ne 0$ is in fact a "regular surface" or $2$-dimensional manifold.
Comment: @proximal Could you bring back your answer? It seemed interesting to me and I think it would be a good idea to leave it if only for future readers.
Comment: @TedShifrin So strictly speaking $P=(a, b, \phi(a, b))$ ?
Comment: Jack, yes, absitively. @proximal would need to rewrite his answer in terms of a local smooth parametrization, which you don't necessarily know exists. From my set-up, it would be $\Phi(x,y)=(x,y,\phi(x,y))$.
Comment: @JackM I would have to decline; Ted is absolutely correct here, and I don't want to mislead anyone.


Trying to create a user with an entity reference taxonomy term using services

Question: So I've been trying to create a user with an entity reference taxonomy term, however for some reason it doesn't seem to work.
I've noticed that it depends on the widget used, but I've tried every combination of widgets and data, and it doesn't appear to work.
Here's an example of one way:
<code>                    "field_likes": {
                        "und": "1"
                    }
</code>
I've also tried this, also for example:
<code>                    "field_likes": {
                        "und": [
                            {
                                "target_id": 1
                            }
                        ]
                    }
</code>
Is there anyway to add taxonomy terms as an entity reference on a user that will work? Has this changed, or am I doing something wrong?
Answer: I was able to get it working with the following on checkboxes and select:
<code>"field_likes": {
"und":{
"target_id": "1"
      }
}
</code>
This technically solves the problem, though I'm not sure how to send up multiple values this way.
EDIT:
Here is the actual solution, which not only allows you to put in entity reference taxonomy terms, but multiple as well:
<code>"field_likes": {
                 "und":{
                         "target_id": "1",
                         "target_id_1": "2"
                        }
                }
</code>
This is with the select list widget, which I think is important for this particular example (based on other links I've been reading).


Issue with styling child element on mouseover with Jquery

Question: I am trying to change the style of the
 element when moving my mouse over the parent
 element, but I can't get it to work.  I think the issue lies within the way I selected the child element since it holds an "undefined" value.
I have also tried just selecting the element by the class name but it didn't work either.
Here's the code:

$(function() {
  $(".parent").on("mouseover", updatetop);

});

function updatetop() {
  var c_child = $(this).children("ul");
  c_child.style.visibility = "visible";
  c_child.style.border = "1px solid black";

}
.parent {
  border: 1px solid black;
  width: 100px;
}

.parent ul {
  position: absolute;
  left: 100px;
  width: 100px;
  visibility: hidden;
}

  PARENT

...

...

...

...

Comment: Any reason you don't just do this with CSS?
Comment: Why you aren't using the css `:hover` pseudo class, like: `.parent:hover ul {…}`
Comment: @ScottMarcus I was not referring to JS vs. CSS, I was referring to the mixup between using a jQuery object with plain javascript. That's where his error is coming from.
Comment: @ScottMarcus I agree with you on the advantage of just using CSS for this
Comment: When already using jQuery why not stick with it? jQuery has a build-in function to handle css changes: [`.css()`](http://api.jquery.com/css/)
Comment: And, your HTML doesn't include a `` element to contain the top-level `` element.
Comment: @empiric Because JQuery is JavaScript and that means executing code in the JS runtime. If you can accomplish the same task without having to parse and execute that JS and instead just rely on the CSS rendering engine, the code becomes simpler and, often, faster.
Comment: This is just an example. The reason i'm not using css for this is because i'm trying to do something else that requires javascript.
Answer: The children() method returns a jQuery collection, not a DOM object.
You can use jQuery's css() method to do the styling:
var c_child = $(this).children("ul");
c_child.css({
  visibility: 'visible',
  border: '1px solid black'
});

Snippet:

$(function() {
  function updatetop() {
    var c_child = $(this).children("ul");
    c_child.css({
      visibility: 'visible',
      border: '1px solid black'
    });
  }

  $(".parent").on("mouseover", updatetop);
});
.parent {
  border: 1px solid black;
  width: 100px;
}

.parent ul {
  position: absolute;
  left: 100px;
  width: 100px;
  visibility: hidden;
}

  PARENT

...

...

...

...

A more typical way to do this would be using CSS :hover:
.parent:hover ul {
  visibility: visible;
  border: 1px solid black;
}

That way, you won't need to add a mouseout event.
Snippet:

.parent {
  border: 1px solid black;
  width: 100px;
}

.parent ul {
  position: absolute;
  left: 100px;
  width: 100px;
  visibility: hidden;
}

.parent:hover ul {
  visibility: visible;
  border: 1px solid black;
}

  PARENT

...

...

...

...

Answer: Just add to your css
.parent:hover ul {
     visibility: visible;
     border: inherit;
}

You don't have to use jQuery for this.
Answer: Hi you can easily do this with help of CSS.
li.parent:hover ul {background-color:#333}

Let me know if you want it through jquery.


Can a critical point be a minima or maxima even if its $f ''(c)=0$?

Question: I'm studying about stationary points of a function. First, in order to get all critical (or stationary points) we equate $f'(x)$ to zero and get all possible critical values. To check it's nature whether its a minima or maxima we plug that specific $x$ value (say $c$) to $f''(x)$.
Its clear to me that if $f''(c)>0$ its definitely a minima
and if $f''(c)<0$ its definitely a maxima
But what if we encounter with $f''(c)=0$??
from what I found in the internet it can be an inflection point.
My problem is can it still be a minima or maxima if $f ''(c)=0$?
Can it be any other shape apart from inflection shape in the last case?
I would like to see an example if $f ''(c)=0$ and its some other shape apart from inflection point.
Your help is highly appreciated.
Comment: If the first non-zero derivative has even order, then it is a maximum or a minimum. If  the first non-zero derivative has odd order, then it is an inflection point.
Answer: Take $f(x)=x^4$. Note that $f''(0)=0$ and $0$ is a point of global minima of $f$.
The actual statement (given in this link) which is most helpful for you to determine whether it is an inflection point or one of minima, maxima requires you to find as many derivatives as you can and then depends on the sign of the even-order derivative.
The method of classification of the critical point, given in the link works so far as a non-zero derivative is reached at the critical point $c$ you want to investigate. (A non-trivial function for which every derivative at $x=c_0$ is $0$, which still achieves a global minima at $x=c_0$ is given by $$f(x)=\left\{\begin{matrix} \exp((x-c_0)^{-2}) & \text{if } x\ne c_0 \\ 0 & \text{if } x=c_0\end{matrix}\right\}$$ and this is a very useful/popular function with this property.)
Answer: Yes it can be either a maximum/minimum or it could be an inflection point.
Let consider for example
$$f(x)=x^3 \implies f'(x)=3x^2\quad f''(x)=6x$$
and in this case $x=0$ is an inflection point.
For the case
$$f(x)=x^4 \implies f'(x)=4x^3\quad f''(x)=12x^2$$
to check the minimum by derivatives we need to consider the  fourth derivative  which is indeed positive.
More in general the nature of the point is given by the sign of the first even derivative not equal to zero at that point.
Comment: Recall that when second derivative test fails we can take a look to the sign of $f'(x)$ to determine the nature of the point. You are welcome! Bye
Comment: Oh right so in $x^4$ its a minimum point right?
Comment: @emil Let consider $y=x^4$ for the minimum, $y=-x^4$ for the maximum and $y=x^3$ for the inflection point.
Comment: Thank you very much!
Comment: This answer seems to imply that a critical point can be both a relative extrema and an inflection point.  However, neither example does that.  The first example, x^3 has no extrema, increasing everywhere, except x=0.  The 2nd example, has no inflection points, concave up everywhere.
@user has a better explanation, when 2nd deriv. test is inconclusive use the first derivative test to determine extrema.
Comment: @nickalh Sorry if I wasn't clear with the explanation. The simple examples provided are to be considered as single example of different cases. The scope wasn't find a single function which shows all the cases. Could  you please specify where the misinterpretation comes from, I can fix it if necessary. Thanks for the comment. Bye
Comment: @nickalh Thanks for the editing, I'm not native english speaker and then the way I wrote the first sentence wasn't clear. Thanks again for the clarification. Bye


UPDATE FROM SELECT with foreign key on parent with one query

Question: How to update (change from first select table value second) second_table.first_table_id if first_table.email match in both select.
If it even possible. With one query!
----------------------------------------- UPDATE -----------------------------------------
EXAMPLE:
I need to update foreign key of second table if email field match in first table. I need to compare two query results with different parent_id (parents are in in same table with children)
         table_1
 -------------------------
| id |  parent_id | email |
 -------------------------
  1     NULL       NULL
  2     NULL       NULL
  3      1         firstname.lastname@example.com
  4      2         email@example.com
  5      1         email@example.com
  6      2         kira@.us

     table_2
 ----------------
| id |  first_id |
 ----------------
   1       3
   2       4
   3       5
   4       6

I have two parents with ids 1 and 2 and some children (ids: 3,4,5,6).
Also, keep in mind: 1 - old, 2 - new
Task: change foreign key in second table if children email with parent_id = 1 and chilren email with parent_id = 2 match (are the same).
In our example in second table row with id = 3 its foreign key field - first_id has to change from 5 to 4.
Comment: I've read your question thoroughly twice and I still don't understand it. Could you please update your question to show sample data and what you expect the update to do. Oh, and "yes" I think it can be done in one query - I just don't know *exactly* what you want to do.
Comment: So the `table_2.id` column is redundant for what you need?
Comment: Did not totally understand what you meant. But table_2.id is just for reference.
Answer: Following might get you started
UPDATE  Table_2 t2u
SET     first_id = (
  SELECT  t2.first_id
  FROM    Table_2 t2
          INNER JOIN Table_1 t1 ON t1.id = t2.first_id
          INNER JOIN (
            SELECT  parent_id = MAX(parent_id), email
            FROM    Table_1
            GROUP BY
                    email
          ) t1p ON t1p.email = t1.email
          INNER JOIN Table_1 t1i ON   t1i.email = t1p.email
                                      AND t1i.parent_id = t1p.parent_id
  WHERE   t2u.first_id <> t1i.id)

Test script (SQL Server)
;WITH Table_1 (id, parent_id, email) AS (
  SELECT 1, NULL, NULL
  UNION ALL SELECT 2, NULL, NULL
  UNION ALL SELECT 3, 1, 'firstname.lastname@example.com'
  UNION ALL SELECT 4, 2, 'firstname.lastname@example.com'
  UNION ALL SELECT 5, 1, 'email@example.com'
  UNION ALL SELECT 6, 2, 'kira@.us'
)
, Table_2 (id, first_id) AS (
    SELECT 1, 3
    UNION ALL SELECT 2, 4
    UNION ALL SELECT 3, 5
    UNION ALL SELECT 4, 6
)
SELECT  t2.*, t1i.id as [update with]
FROM    Table_2 t2
        INNER JOIN Table_1 t1 ON t1.id = t2.first_id
        INNER JOIN (
          SELECT  parent_id = MAX(parent_id), email
          FROM    Table_1
          GROUP BY
                  email
        ) t1p ON t1p.email = t1.email
        INNER JOIN Table_1 t1i ON   t1i.email = t1p.email
                                    AND t1i.parent_id = t1p.parent_id
WHERE   t2.first_id <> t1i.id

Output
id          first_id    update with
----------- ----------- -----------
3           5           4

Comment: I'm trying to understand that query. And I have a question. Where is in query reference for tabel_1.id = 1 (which is old) and id=2(the new). Because i need to change children with this exact ids of parents.
Comment: Is assume you mean `parent_id` and it is the `MAX(parent_id)` where it gets referenced. If you indeed mean `id`, I totally misunderstood.


mailx not sending mail if contents include "backup.sh"

Question: I have a very strange problem with mailx. I will describe the problem quickly and will then give environment details.
I have a file /tmp/junk. I try to mail the contents of this file to me as follows:
ott01pslpr0001(oracle:NONE):/tmp: cat junk |  mailx -s "some subject" firstname.lastname@example.com

If the file /tmp/junk has a word 'backup.sh', then I don't get the mail. If the file doesn't have the word 'backup.sh', I do get the mail.
Example:
If the file contents are as follows:
ott01pslpr0001(oracle:NONE):/tmp: cat junk
a for archive archive.sh
b for backup backup.sh
c for configure configure.sh

I wouldn't get the mail
But if the second line says anything other than backup.sh (e.g. backup1.sh or back.sh or backup.shh or backup_sh), then I do get the mail. The word backup.sh doesn't need to be at the specific place shown. If that word is there anywhere in the file, I wouldn't get the mail.
I checked that the mail has not bounced to the sender. I checked the /var/log/messages, but don't see anything relevant there. I don't know if I should be checking any other log files.
I am totally puzzled. Can someone help?
Environment details:
ott01pslpr0001(oracle:NONE):/tmp: which mailx
/bin/mailx

ott01pslpr0001(oracle:NONE):/tmp: ls -l /bin/mailx
lrwxrwxrwx 1 root root 4 May 27  2014 /bin/mailx -> mail

ott01pslpr0001(oracle:NONE):/tmp: ls -l /bin/mail
-rwxr-xr-x 1 root mail 84856 Jul 13  2006 /bin/mail

ott01pslpr0001(oracle:NONE):/tmp: file /bin/mail
/bin/mail: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped

ott01pslpr0001(oracle:NONE):/tmp: uname -a
Linux ott01pslpr0001 2.6.18-371.el5 #1 SMP Thu Sep 5 21:21:44 EDT 2013 x86_64 x86_64 x86_64 GNU/Linux

ott01pslpr0001(oracle:NONE):/tmp: cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.10 (Tikanga)

ott01pslpr0001(oracle:NONE):/tmp:

Thanks in advance ...
-- Parag
Comment: You want to check the `/var/log/maillog*` logs of the server on which you execute `mailx` if the message gets sent or not, and if it does you need to check the incoming mailserver that handles `@mydomain.com` to see if your message doesn't get discarded by a spam filter or anti-virus.
Comment: Thanks. Just checked `/var/log/maillog`. In both cases (when I got the mail and when I didn't), the messages in the maillog were exactly same (except for timestamp and message ids).
Answer: Just figured out something. We use outlook365. Typically the spam goes to a folder called "Clutter" and I had checked for the missing messages there, without any luck. But I found out that there is another folder called "Junk Email" (I need to figure out what is the difference between the two) and I found this message there. So, somehow the word "backup.sh" is triggering some junk email rule on outlook365. I should have seen this folder earlier. My oversight. Sorry about that.


Is It Possible To Migrate From Realm To Sqlite?

Question: For some reasons(mainly large apk size even with ABI splits, anyway) i need to remove Realm completely and use Sqlite without losing data.
I couldn't find a way. It seems the app must continue using Realm, or users will lost their data completely.
Any idea will be appreciated
Comment: Realm is the only thing that can open the Realm file, and your migration from Realm to SQLite would need both at the same time (to prevent data loss).
Comment: Please see my answer below and consider closing the question if the answer satisfies you
Comment: @EpicPandaForce Woefully, this is answer of this question, thanks.
Comment: @EpicPandaForce Also i'm wondering this, okay, let's assume we removed Realm and user received new version of app. What about the Realm files ? They will be stored as garbage until user clearing the app data or uninstalling app?
Comment: Well unless you delete them yourself.... They're Just files though, so you can do that. To clear Realm files, you can look at the implementation for `Realm.deleteFile()` I think that's what it was called.
Comment: But i'm removing Realm, so how can i use `Realm.deleteFile()`?
Answer: I don't think I understand fully what your problem is. If you are asking if there is a tool that will automate the data migration for you, then no, there is no such a tool.
Otherwise it is rather straight forward:

Handle onCreate, onDowngrade and onUpgrade methods in the implementation of your SQLiteOpenHelper class.
In your onCreate method, right after you create tables, get all your data from Realm and insert into into SQLite tables.

Something like this:
Realm realm = Realm.getDefaultInstance();
RealmResults<MyClass> all = realm.where(MyClass.class)
                                 .findAll();
for (MyClass instance : all) {
    doInsert(instance);
}

I actually suggest that you look into how to reduce APK size while using Realm, but it is up to you
EDIT 1
You would have to make sure that you migrate the data first and then delete Realm files. Although it is not the data files that make your APK big, but rather the actual libraries that come with Realm. So for this you will, unfortunately, have to take two steps: first release update that migrates the data to SQLite, and after some reasonable time (like a week) you can release update that takes Realm libraries completely out. Hope it makes sense.
Comment: @Blackkara For this to work it actually requires that the users would update their app twice, which you can't be certain of. Not all users choose to update to every version. They could easily skip or miss the first upgrade or more and then upgrade later, in which case they would not have they files upgraded.
Comment: Thanks for helpful response but the question is clear and says "i need to remove Realm completely and use Sqlite without losing data." In my next app update the Realm will be removed exactly, so the code above will not work. @EpicPandaForce's comment is just what did i want to learn
Comment: "have to take two steps: first release update that migrates the data to SQLite, and after some reasonable time (like a week) you can release update that takes Realm libraries completely out" This seems the most relevant way for me(but bad), thanks.
Comment: Glad I could help. Please consider closing the question as answered.
Comment: That is correct, however, you can never be certain that all users have performed an update. I've frequently see users that are still behind in updating my apps by several month. This will always be 'best-effort' scenario and never 100%. If the goal is to reduce apk size while preserving user data it is quite reasonable to assume that about 99% of users that actually use the app will complete an update in a week's timeframe
Answer: As i know (not sure) if you are using default RealmConfig, Context.getFilesDir() can return the folder of where default.realm is located. You dont need permission to modify them. You can iterate files under this folder to delete them. Hope it works.
PS : Apache-commons has a great FileUtils.java
Good luck
Emre


Insert annotation view fails in iOS 11.0.3

Question: I released an app to App Store some days ago, and today I went to check if there were any crashes. I found out that on two different devices, I had the same crash, related to MKSpatialCollider's insertAnnotationView. Both devices mount iOS 11.0.3.I use MapKit in a ViewController to display custom AnnotationView objects, that I also group in clusters, that's all. I have no idea about these crashes, what could be happening in my app that triggers these events?
Below, I attached those two exceptions' stacktraces, but if you need something else to figure out what's happening, just let me know:

First exception's stacktrace

Second  exception's stacktrace

Update 1 - Here's the link to the code that should trigger the errors (I'm not sure since Xcode points to another file that doesn't contain MapKit at all): https://gist.github.com/MrOverflOOw/bbc14d546ef10bd17065af08fdf3e27c
Comment: You can track these crashes in  Xcode > Organizer , which let you in code where its happing.
Comment: Yes, that's the place where I found these stacktraces I uploaded! But in Xcode, if I try to click on the stacktrace, it points me to a line that shouldn't be involved at all...
Comment: can you share some code where its happened?
Comment: post updated: see that link!
Comment: I'm getting this on iOS 12 too.
Answer: For anyone who's still searching for an answer to a similar problem: in my case, if a user press the back button while annotations are being added to MapView, my app throws the exception above.
From here (https://forums.developer.apple.com/thread/92799), it seems to be an iOS 11 related problem: Apple should release an update soon.
If anyone has further information or a workaround to solve the problem for the meantime, please share it here: I have been able to solve it displaying an ActivityIndicator until MapKit completes adding annotations.
Comment: I tried these solutions and none of them had any affect. Only when I turned off animating into a map rect: mapView.setVisibleMapRect(zoomRect, animated: false) did this fix the issue see below last answer
Answer: I ran into this error when attempting to remove an instance of MKClusterAnnotation from the map views annotations. Specifically when a annotation view is reused for an MKClusterAnnotation. Check to see if you do anything like:
[mapView removeAnnotations:mapView.annotations];

or if you're in Swift:
mapView.removeAnnotations(mapView.annotations)

or really any line of code where you might muck with an MKClusterAnnotation provided by MapKit.
Comment: Oddly it seems like MKClusterAnnotation instances pile up in the `annotation` property of MKMapView. I ran into this while trying to manually clean them up.
Comment: Were you able to fix this problem?
Comment: @Genki Ultimately, we opted for our own clustering logic unfortunately.
Answer: The workaround that worked for me was to deselect annotations (cluster ones are the problem) before adding or removing any other annotations.
I realize your case may not involve adding or removing annotations, but my app crashes in the same MKSpatialCollider code path, so thought I'd mention this workaround. You might try deselecting annotations before the view goes away.
Comment: I tried deslecting by only turning off animations into a visible maprect did it fix the problem mapView.setVisibleMapRect(zoomRect, animated: false)
Comment: Had a similar stack trace to the first screenshot in the OP and fixed it by deselecting all selected annotations in my view controller's `deinit`.
Answer: I have a partial solution although I tried all the answers listed above and I still got the crash.

However when I set zooming to FALSE the crash stops happening completely!? Why? I want to zoom in it looks nice:
mapView.setVisibleMapRect(zoomRect, animated: false)

This is from this function (in which i am also deselecting the Cluster Annotations as suggested above):
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    lastTouchedAtCoordinate = view.annotation?.coordinate
    guard let annotation = view.annotation else { return }

    if let cluster = annotation as? MKClusterAnnotation {
        var zoomRect = MKMapRectNull
        for annotation in cluster.memberAnnotations {
            self.mapView.deselectAnnotation(annotation, animated: false)
            let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)

            let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)

            if MKMapRectIsNull(zoomRect) {
                zoomRect = pointRect
            } else {
                zoomRect = MKMapRectUnion(zoomRect, pointRect)
            }
        }
        mapView.setVisibleMapRect(zoomRect, animated: true)

    }
}

This stopped the crash. I do not know why. I am loading and adding annotations a lot, but I made sure the user cannot interact with the map (as suggested above) by using a progress loader to dim out the background.
I am not using any threading and everything UI is done on the main thread (like adding annotations)
This is the stack trace from the phone, as you can see the system is removing the annotations (I am not at all as also suggested above), is this an apple bug? Or am I doing something wrong?:

Model:      iPhone8,1 Process:
  Path:
  1.1 (1.0) Code Type:           ARM-64 (Native) Role:                Foreground Parent Process:      launchd 3 Coalition:
Date/Time:           2018-02-14 17:38:15.3949 +0100 Launch Time:
  2018-02-14 17:37:10.1854 +0100 OS Version:          iPhone OS 11.2.5
  (15D60) Baseband Version:    4.30.02 Report Version:      104
Exception Type:  EXC_BAD_ACCESS (SIGSEGV) Exception Subtype:
  KERN_INVALID_ADDRESS at 0x0000000000000298 VM Region Info: 0x298 is
  not in any region.  Bytes before following region: 4328635752
        REGION TYPE                      START - END             [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
        UNUSED SPACE AT START
  --->
        __TEXT                 000000010201c000-00000001022a0000 [ 2576K] r-x/r-x SM=COW  ...eDiveAdvisor]
Termination Signal: Segmentation fault: 11 Termination Reason:
  Namespace SIGNAL, Code 0xb Terminating Process: exc handler [0]
  Triggered by Thread:  0
Filtered syslog: None found
Thread 0 name:  Dispatch queue: com.apple.main-thread Thread 0
  Crashed: 0   MapKit                           0x000000019650d190
  -[MKSpatialCollider insertAnnotationView:] + 244 1   MapKit                           0x00000001964791b8 -[MKNewAnnotationContainerView
  _updateClusterableAnnotationViews:withID:] + 456 2   MapKit                           0x00000001964791b8 -[MKNewAnnotationContainerView
  _updateClusterableAnnotationViews:withID:] + 456 3   CoreFoundation                   0x0000000185dc51c0 -[__NSDictionaryM
  enumerateKeysAndObjectsWithOptions:usingBlock:] + 232 4   MapKit
    0x0000000196479d58 -[MKNewAnnotationContainerView
  updateAnnotationViewsForReason:] + 296 5   MapKit
    0x0000000196549690 -[MKAnnotationContainerView
  finishRemovingAnnotationViews] + 32 6   MapKit
    0x00000001963c56dc -[MKAnnotationManager updateVisibleAnnotations] +
  1616 7   MapKit                           0x00000001963c5064
  -[MKAnnotationManager deselectAnnotation:animated:] + 376 8   MapKit                          0x00000001963e4198 -[MKAnnotationManager
  _removeAnnotation:updateVisible:removeFromContainer:] + 468 9   MapKit                            0x00000001964029ac -[MKMapView removeAnnotation:] + 100 10  MapKit
    0x00000001964010b8 -[MKMapView
  annotationContainer:requestRemovingClusterAnnotationView:] + 60 11
  MapKit                            0x0000000196479f8c
  __73-[MKNewAnnotationContainerView _updateClusterableAnnotationViews:withID:]_block_invoke + 84 12  MapKit                            0x00000001964ac108
  __49-[MKAnnotationView _performHideAnimationIfNeeded]_block_invoke.208 + 232 13  UIKit                            0x000000018f4ea188 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 764 14  UIKit                          0x000000018f4e9afc -[UIViewAnimationState
  sendDelegateAnimationDidStop:finished:] + 312 15  UIKit
    0x000000018f4e9808 -[UIViewAnimationState animationDidStop:finished:]
  + 296 16  QuartzCore                      0x0000000189f4adc4 CA::Layer::run_animation_callbacks+ 1252804 (void*) + 284 17
  libdispatch.dylib                 0x0000000185876a14
  _dispatch_client_callout + 16
Answer: override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    mapView.removeAnnotations(mapView.annotations)
}

Seems to fix the crash for me


Preserve CAShapeLayer's lineWidth in a zoomable UIView

Question: I have a custom UIView, which has a UIImageView as its' subview to display an image and a CAShapeLayer as a sublayer to draw on it. The UIView is zoomable, I use a UIPinchGestureRecognizer to zoom in and out of the view. I can draw straight lines on the view using a CGPathRef. The problem is, when I pinch to zoom the view, the lines I draw also zoom and become thick. How to zoom in the view, keeping the lines thin?
Before zooming (green lines are the ones I draw):

And when I zoom:

What I want is, the lines to be as thin as they were before I zoomed in.
I tried to:
<code>CGMutablePath path = CGPathCreateMutable();

//line drawing code here

//scale path to 1.0?
CGAffineTransform transform = CGAffineTransformMakeScale(1.0, 1.0);
CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &transform);
self.drawingLayer.path = transformedPath;
CGPathRelease(path);
CGPathRelease(transformedPath);
</code>
How do I prevent path width from enlarging when zooming?
Comment: You need to divide the zoom factor from the line width i.e zoom = 4.0 then line width = 1.0/4.0 and same as if zoom is 2 then 1.0/2.0
Comment: Do you just want the line width not to be scaled or should the whole layer content not be scaled as well?
Comment: @PrashantTukadiya that worked! Thanks a lot! Weird, 'cause I've seen such solution and it didn't work for me before.
Comment: @clemens only the line width. I created a property to store the width and change it in the pinch gesture recognizer's method:
`self.lineWidth = self.lineWidth \ recognizer.scale;` as @PrashantTukadiya suggested. By default, `lineWidth = 1.0f`
Comment: @VolodymyrDenysov Glad that worked for you !! also added as answer so other can take help from there
Answer: You need to divide the  line width with the zoom factor.By default line width is 1.
So create property for the same and when you apply zoom with gesture divide it.
i.e zoom = 4.0 then line width = 1.0/4.0
and same as if zoom is 2 then 1.0/2.0
Hope it is helpful


Gradle build fails with "Program type already present: "

Question: I am trying to add brain tree services to my Unity app, as i need real item purchasing.
I am able to get the drop in ui working in a blank android project and created a module that handles it. However whenever i try to add the necessary aar file i get gradle build issues.
I have exported my project to android studio to get more comprehensive error codes and fine grained control over gradle.
However any configuration of gradle still gives me a Program type already present.
This is my the dependencies for my Gradle File
apply plugin: 'com.android.application'

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation(name: 'android-maps-utils-0.5', ext:'aar')
implementation(name: 'google-maps-view-lib-release', ext:'aar')
implementation(name: 'play-services-base-11.0.2', ext:'aar')
implementation(name: 'play-services-basement-11.0.2', ext:'aar')
implementation(name: 'play-services-maps-11.0.2', ext:'aar')
implementation(name: 'play-services-tasks-11.0.2', ext:'aar')
implementation(name: 'support-compat-25.2.0', ext:'aar')
implementation(name: 'support-core-ui-25.2.0', ext:'aar')
implementation(name: 'support-core-utils-25.2.0', ext:'aar')
implementation(name: 'support-fragment-25.2.0', ext:'aar')
implementation(name: 'support-media-compat-25.2.0', ext:'aar')
implementation 'com.braintreepayments.api:braintree:2.20.0'

implementation ('com.braintreepayments.api:drop-in:3.2.1')

{
        exclude group: 'com.android.support.annotation'
        exclude module: 'com.android.support.v4.app'
        exclude module: 'com.android.support.v4.media'
        exclude module: 'com.android.support:support-v4:28.0.0'
        exclude group: 'support-v4'
        exclude module: 'support-v13'
    }
 //implementation(name: 'support-v4-25.2.0', ext:'aar')
}

What i get is:

Error: Program type already present: android.support.v4.media.MediaBrowserCompat$MediaBrowserImplApi21$1
Comment: The answer on this question might help: https://stackoverflow.com/q/49038630/2740621
Answer: Use below command to analyse your dependencies for the duplication.
./gradlew app:dependencies

Noted that implementation 'com.braintreepayments.api:braintree:2.20.0' also depends on android.support.v4. So, try to exclude it also.
For the conflict dependencies version, you can specify the enforced version as below:
configurations.all {
    resolutionStrategy {
        force "com.android.support:support-v4:26.0.0"
    }
}

Answer: Found a solution!
Just needed to edit the play services resolver to be adding in the braintree plugins rather than adding them manually or using gradle. It managed to seperate out all the individual components and resolve the conflicts!
Thanks for the responses tho.
I followed this solution Gradle dependencies on Unity.


manual implementation of Gaussian naive bayesian returns posterior larger than 1

Question: I try to implement Gaussian naive bayesian manually in R. I test my model on iris data set. I would like to build a predictive model. That is, I would like to consider, for each point, the correct class.
My problem:
I see that the posteriors for some points are larger than 1, which is wrong.
What I have tried:

I have divided the data into training and test datasets.

Then I assume equally prior for each class (0.3) (as the prior must sum to one).

I applied the Bayesian rule for the training data set. For this I do the following:

to compute the likelihood for each class, I computed the density (for each point in each class). den[[1]] is the density of the
Sepal.Length. den[2] is the density of Sepal.Width. den[[3]] and den[[4]] are the density for the resining variables.

Then to compute the posterior for each point, I computed prior*likelihood, for each point.

However, I found that some posteriors values are larger than one. I believe I did something wrong, but do not know what is my mistake?
Any help, please?
Here is my code
data(iris)
dim(iris)[[1]]
##split the data based on its class
NewData <- split(iris, iris$Species)
## divide the data based on their class
NewDatSetosa <- NewData$setosa[,1:4]
NewDatVersicolor <- NewData$versicolor[,1:4]
NewDatVirginica <- NewData$virginica[,1:4]

##divide the data into train and test datasets
set.seed(1234)
datadivision <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))
iris.training <- iris[datadivision==1, 1:4]
iris.test <- iris[datadivision==2, 1:4]
##Compute the posterior for each class

posterior <- function(data,prior,newDat){
  post <- list()
##compute the density for each point in the training data set
  den <- lapply(1:4, function(i) dnorm(data[[i]], mean(newDat[[i]]), sd(newDat[[i]])))
## compute the posterior for each point. den[[1]] is the density of the
##Sepal.Length. den[2] is the density of Sepal.Width. den[3] and den[4] ##are the density for the resining variables.

     post <- prior*den[[1]]*den[[2]]*den[[3]]*den[[4]]
  return(post)
}
post.Setosa <- posterior(iris.training, prior=0.3, NewDatSetosa)
post.Versicolor <- posterior(iris.training, prior=0.3, NewDatVersicolor)
post.Virginica <- posterior(iris.training, prior=0.3, NewDatVirginica)

Comment: Not sure I understand what you are doing, but why would a normal distribution (not restricted to [0, 1]) for the likelihood make sense, if you expect an posterior to have something to do with a probability of class membership?
Comment: @Björn   As I understand the normal distribution must be estimated for each class. I tried to do a classification problem. So, I estimate the normal distribution for each class and then apply the Bayesian rule.
Answer: Your priors should be $1/3$, not 0.3. But, this is the minor issue. It's true that your posterior, i.e. $p(c|x)$, where $c$ represents the class can't be larger than $1$. However, it's not equal to prior * likelihood; rather it is proportional to it:
$$p(c|x)=\frac{p(x|c)p(c)}{p(x)}\propto p(x|c)p(c)$$
So, what you've calculated is not a valid PDF or PMF. It should be normalized by $p(x)=\sum_{c_i} p(x|c_i)p(c_i)$. But, you can do the classification w/o the normalization step because $p(x)$ doesn't depend on specific $c_i$.
Comment: @Mary , yes sum wrt each class.
Comment: Thank you so much for your help. Hence, I need to divide `prior*den[[1]]*den[[2]]*den[[3]]*den[[4]]` by the their sum.


Prove non-curvature is asymptotic with unit binormal vector

Question: Let S be an oriented regular surface. A regular curve $\gamma:I\rightarrow S$ is called asymptotic if $II_{\gamma(t)}(\gamma'(t))=0$ for all $t \in I$.
If $\gamma$ has non-zero curvature, prove that it is asymptotic if and only if its unit binormal vector $b(t)$ is parallel to $N(\gamma(t))$ for all $t\in I$.
So I think $II_{\gamma(t)}(\gamma'(t))$ here represents the normal curvature in some way but the notation is confusing me.
Not sure if this is on the right track or not, but I have:
Assuming non-zero curvature, $\gamma'(t)$ is orthogonal to $N(\gamma(t))$ for all $t$. For every $\gamma$, we want    $\gamma''\times N(\gamma(t))=II_{\gamma(t)}(\gamma'(t))=0$ to be asymptotic.
$b(t)=$unit tangent$\times$unit normal$=\frac{\gamma'}{\left \| \gamma' \right \|}\times N(\gamma(t))$
What does having $b(t)$ parallel to the unit normal do towards solving this proof?
Answer: First some remarks: $II_{\gamma(t)}(\gamma'(t))$ here means the normal curvature of at $\gamma(t)$ in the direction $\gamma'(t)$. Also note that $\gamma'' = T'=\kappa N$, so
$\gamma''\times N(\gamma(t))$ is trivially zero. And finally, $\gamma''\times N(\gamma(t))=II_{\gamma(t)}(\gamma'(t))$ doesn't mean anything, since the LHS is a vector and the RHS a scalar.
Hint. What is the definition of sectional curvature? The expression should involve the surface normal, let's call it $U$. From $II_{\gamma(t)}(\gamma'(t))=0$, you can find a relation between the normal $N$ of the curve and the surface normal $U$.
If you want to have a peek at the answer, see this question.
Comment: Does asymptotic make sense for non-oriented surfaces?
Comment: Yes, it does. A curve is asymptotic if its tangent vector is asymptotic, i.e. the normal curvature of the surface in that direction is zero. A surface has asymptotic directions at a point iff the Gauss curvature at that point is non-positive. But it has nothing to do with being oriented or not.


What does $A\iff B$ mean with respect to "sufficiency" and "necessity"?

Question: If I have $A \iff B,$ does that means $A$ is sufficient for $B$ to occurs and $B$ is necessary for $A$ to occurs?
I am confused about the direction of meaning sufficient and meaning necessary, I usually say $\implies$ this direction means the premises is sufficient for the result i.e. $A \implies B$ means $A$ is sufficient for $B$ to occur. And $\Longleftarrow $ means the premises is sufficient for the result i.e. $B \impliedby A$ means $B$ is necessary for $A$ to occur.
But I have seen some people not sticking to this and taking reverse directions for necessary and sufficient. Could anyone explains this for me please?
Comment: If something is needed for a truth, and that something is produced by that truth, those things are logically equivalent. "Sufficient for" means implied by.
Comment: my mother tongue is not English so what is the difference between implied by and is implied by?@DavidPeterson
Answer: If $A \implies B$ then $B$ is necessarily true when $A$ is true. As well, $A$ is a sufficient condition for $B$ to be true.
If $A$ is true then it must be the case that $B$ is true (necessary).
If we want to imply $B$ it is sufficient to determine that $A$ is true.
Imply is a synonym for deduce.
Comment: It is known and standard. Necessary and sufficient conditions are abstract  concepts pertaining to the direction of deduction.
Comment: sometimes in the proof they just say the necessary condition and the sufficient condition as if it is always known and standard.
Comment: what about the necessary one?
Comment: Material implication does not mean that " if A is true, B is necessarily true" it only mean " if A is true, B actually IS true". I can correctly say that " If the Earth has only one natural satellite, then there are 5 continents on Earth". The reason is that factually, the 2 sentences are true, so the material implication is true. But that does not mean that "  the Eart has only one natural satellite" necessarily implies " there are 5 continents". $(A\rightarrow B) $ does not mean $\square  (A\rightarrow B) $ nor $ (A\rightarrow \square B) $ . Material implication is not logical implication.
Comment: Reference: Lipschutz, Outline Of Set Theory ( at archive.org), chapter about the Algebra Of Propositions.
Comment: Another way to say this is that some conditions are " contingently sufficient" and that others are " necessarily sufficient".
Comment: As far as I know, when one talks about sufficient and necessary conditions, one talks about the meta relationship between the truth values of $A$ and $B$. This is because the words "sufficient" and "necessary" pertain to a description of the morphism between the objects, and does not speak of the actual truth values in the proposition.
Comment: Being a sufficient or a necessary relation ( in the sense of material implication) is not a relation pertaining to the meta-level . The relation that belongs to meta-logic is ***logical implication***.
Comment: You may have a look at : Mummert's answer  to
Comment: Yes, I am aware of the difference, it is what I hinted at with the morphism abstraction. What I am further claiming is that necessity and sufficiency are abstract concepts that arise naturally from morphism and not the objects themselves. We then use this concept to "come  back to earth" and materialize the objects while the morphism between them survives. Hence necessity and sufficiency are concepts that arise from logical implication and not material implication. We see necessity and sufficiency in material implication only in the cases in which we could also see it in the logical/abstract.
Comment: Hence, explaining why your example of earth does not acquire the usual use of the term necessity and sufficiency, and the abstract concept they necessarily entail; that is of a logical implication.
Answer: $A$ is a sufficient condition for $B$ is symbolised as $$A \to B$$
$A$ is a necessary condition for $B$ is symbolised as $$B \to A$$
Example (taken from the book "forallX" by P.D. Magnus):
Symbolization key:

$P$: Jean is in Paris.
$F$: Jean is in France.

We can symbolise this sentence

If Jean is in Paris, then Jean is in France.

as $P \to F$.
An intuitive way of understanding the concept of sufficient condition, is: $P$ is a sufficient condition for $F$ means $P$ being true guarantees the truth of $F$. In this example, if Jean is in Paris, I know he is definitely in France.
Along these lines, $F$ is a necessary condition for $P$ means $P$ would not have happened without $F$. In this example, if Jean is not in France, I can be sure he is not in Paris.
$A$ if and only if $B$ is simbolised as $$A \leftrightarrow B$$
It means $A$ is a sufficient and necessary condition for $B$.
Comment: Good point, @Ray LittleRock. If $A \to B$ is true, $A$ being true guarantees the truth of $B$. Do you think this wording is incorrect? How would you express this subtlety?
Comment: Thanks for your answer on hypothetical scenarios @Ray LittleRock. It really helped. I was going to accept it but then the answer disappeared.
Comment: The fact that "the Earth has only one natural satellite" is a sufficient condition for " there are 5 continents on Earth" to be true, for the material implication relation holds between these two sentences. But it is not the case that the first one guarantees the truth of the second: no-one could ever deduce the second from the first. Material implication is not the same thing as logical implication. There is no modal component in material implication. See : Lipschutz, Outline Of Set Theory, Chapter on the Algebra of proposiitons ( at archive.org).
Comment: Shortly : $(A \rightarrow B) $ is not the same thing as $\square (A\rightarrow B)$. What is true, nevertheless,  is that : "if A implies B and if A is true, it is guarantied ( logically)  that B is true".
Comment: " Guarantees" means that " it is impossible for B to be false when A is true". , or, if you prefer, that there is no possible world in which the first sentence is true and the second false. But certainly the Earth could have had only one natural satellite and , though, have more ( or less) than 5 continents. Simply, in the actual world ( the world as it is) the 2 sentences are true, and therefore, the material implication relation holds ( due to the truth table of " if...then"). That does not mean , notwithstanding, that  the first sentence " guarantees" or " logically implies" the second.
Comment: Are you saying that, "A being true guarantees the truth of B", does not necessarily guarantees what is actually being symbolized by B ? I see where you are heading. That concept is clear for me, but I wonder if we are talking about wording, here.
Comment: There is actually a little " subtlety" here. You may have a look at Wolfram's Philosophical logic (Introduction, § 1.2.2) , in which the author explains the distinction between a sufficient condition that is only " contingently sufficient" ( as a matter of fact) and a sufficient condition that is " necessarily sufficient" ( " as a point of logic").- Also note that : though material implicaton is a logical operator, ***material implication is not the same thing as logical implication***.
Comment: Sentence A logically implies ( " entails") sentence B iff the material implication $(A\rightarrow B)$ is a tautology ( i.e. is true in all possible cases, all possible " worlds".)
Answer: $A\implies B$ reads that "$B$ is true whenever $A$ is true".
However this does not promise anything about $B$ when $A$ is false.  It is possible that $B$ might be true while $A$ is false, and if so, then $A\implies B$ will still be satisfied.
So $A\implies B$ claims that the truth of $A$ is sufficient but not necessary for the truth of $B$.

Likewise, $A\impliedby B$, also written as $B\implies A$,  claims that the truth of $A$ is necessary but not sufficient for the truth of $B$.

Finally $A\iff B$, being equivalent to $(A\implies B)\wedge(A\impliedby B)$, claims that the truth of each is sufficient and necessary for the truth of the other.
Answer:
If I have A⟺B, does that means A is sufficient for B to occurs and B
  is necessary for A to occurs?

Yes it means this, but it means more than this.
If it only meant this, there would be no difference between bi-implication and simple implication.
Simple implication ( A $\rightarrow$ B) already means by itself that A is sufficient for B and B is necessary for A.

Saying that A is sufficient  for B to be true means than $ A \rightarrow B$ is true. ( Which implies, by itself, that B is necessary for A to be true).
Saying that A is necessary for B to be true means that if A is not true, B is not true either , that is : $\neg A \rightarrow \neg B$.
Now, suppose you want the expression $(A \iff B)$ to mean : " A is both sufficient and necessary for B to be true", you will define this expression as follows :

$$(A \iff B)\equiv_{Df_1} [(  A \rightarrow B) \land (\neg A \rightarrow \neg B)]$$.

But, contraposition law ( with double negation) allows you to rephrase the second part of the conjunction as : $(\neg\neg B \rightarrow \neg\neg A) \equiv (B\rightarrow A)$.

So your first definition is equivalent to :
$$(A \iff B)\equiv_{Df_{2}} [(  A \rightarrow B) \land (B \rightarrow A)]$$.
This shows that : saying "A is both sufficient and necessary for B" is equivalent to saying that "(1) A is sufficient for B and (2) B is sufficient for A".

In fact , with contraposition, one can show that $(A\iff B)$ means equivalently :

(1) each sentence is sufficient for the other
OR
(2) each sentence is necessary for the other
OR
(3) each is both necessary and sufficient for the other.


How can we reduce the apk size in flutter

Question: I'm building my apk with flutter build apk --split-per-abi but it still generate 60mb apk. 1# Here is the result of size analyzer 2#pubspec.yaml  all the packages that is used in this project
I tried removing all the unused package but it didn't work after that I created new project same result .It should not be that large for ios it goes to 900+mbs
Comment: run `flutter clean` then build your app
Comment: @eamirho3ein Thanks But I already did that many time but it result same.
Answer: if your plan is publish to google play you can export appbundle for android devices
<code>flutter build appbundle
</code>


Sets of measure zero and the Lebesgue differentiation theorem.

Question: This is an exercise from Stein-Sharachi Chap. 3 Exx. 25
$\textbf{Problem Statement}$ Let $E$ be a set of measure zero in $\mathbb{R}^d$. Show that there exists a non-negative integrable $f$ in $\mathbb{R}^d$, so that $$\liminf_{m(B) \to 0} \frac{1}{m(B)} \int_{B} f(y) dy = \infty$$ for each $x \in E$ and $B$ is any ball containing $x$.
$\textbf{My Attempt:}$. From the hint, let $f(x) = \sum_{n=1}^{\infty} \chi_{\mathcal{O}_n} (x)$, where $\mathcal{O}_n \supset E$ and $m ( \mathcal{O}_n) < \frac{1}{2^n}$. We can do this since $E$ has measure zero.
Then $$\int_{\mathbb{R}^d} f(x) dx = \sum_{n=1}^{\infty} \int \chi_{\mathcal{O}_n}(x) = 1$$ and so $f$ is integrable.
I know  have left out some details but the above is not where I am having difficulties.
Let $B$ be any ball. From above we have that $E \subset \mathcal{O}_n$. Thus for any $x \in E$, there exists a ball $B_n \subset \mathcal{O}_n$ such that $x \in B_n$.
$$ \int_B f(y) dy = \sum_{n=1}^{\infty} m ( \mathcal{O}_n \cap B) \ge \sum_{n=1}^{\infty} m ( B_n \cap B)$$
Then $$\frac{1}{m(B)} \int_B f(y) dy \ge \sum_{n=1}^{\infty} \frac{m(B_n \cap B)}{m(B)}$$
Since $x \in B_n$ is a point of Lebesgue density I have that $$\lim_{m(B) \to 0} \frac{m(B_n \cap B)}{m(B)} =1$$
This seems useful since then, $$ \sum_{n=1}^{\infty} \lim_{m(B) \to 0} \frac{m(B_n \cap B)}{m(B)} = \infty$$ and I would have my result.
However, how does $\liminf$ ever come in to play? I really do not understand the significance.
And how do I back up moving the limit inside of the summation?
Answer: I'm not exactly sure what you're looking for here, but Fatou's lemma might be it! You'd have
$$
\sum\limits_{n=1}^{\infty} \liminf_{m(B) \to 0} \frac{m(B_n \cap B)}{m(B)} \leq  \liminf_{m(B) \to 0} \sum\limits_{n=1}^{\infty}  \frac{m(B_n \cap B)}{m(B)} \leq \liminf_{m(B) \to 0} \frac{1}{m(B)}\int_B f
$$


How we can find the perpendicular line?

Question: The perpendicular line of a curve at a point $p$ is the line that goes through $p$ and is perpendicular to the tangent line at $p$.
Find the tangent and the perpendicular line of the curve $\gamma (t)=(2 \cos t-\cos 2t, 2\sin t-\sin 2t)$ at the point that correponds at $t=\frac{\pi}{4}$.
I have done the following:
The tangent line of the curve at $t=\frac{\pi}{4}$ is $$l(t)=\gamma (\frac{\pi}{4})+t\gamma '(\frac{\pi}{4}) \Rightarrow l(t)=(\sqrt{2}+(2-\sqrt{2})t, \sqrt{2}-1+\sqrt{2}t)$$
Is this correct?
Could you explain to me how we can find the perpendicular line?
Comment: The vector $$ is perpendicular to $<-y, x>$ in $\mathbb{R}^2$.  Apply this to the direction vector of your tangent line.
Comment: That is correct!
Comment: The direction vector of the tangent line is $\gamma '(t)$ or $\gamma'(\frac{\pi}{4})$ ? @ChocolateAndCheese
Answer: These are the steps you should take:
(1) find a vector parallel to $\gamma$ at $t = \pi/4$
Since you claim to have the tangent line already, simply take the difference of two points on the tangent line.
(2) find a vector perpendicular to the above vector, call it $v$. This bears no explanation.
(3) Then your solution will be
$$ (x_0,y_0 ) + v\cdot t = L(t)$$
Where $(x_0,y_0) = (x,y)\Big|_{t=\pi/4} $.
Comment: The tangent line is $l(t)=\gamma (\frac{\pi}{4})+t\gamma '(\frac{\pi}{4})$. So a vector parallel to the tangent line at $t=\frac{\pi}{4}$ is $\gamma '(\frac{\pi}{4})$, right? So to find the vector $v$ of step $(2)$ we have to do the following: $$v \cdot \gamma '(\frac{\pi}{4})=0 \Rightarrow (v_1, v_2) \cdot (2-\sqrt{2}, \sqrt{2})=0 \Rightarrow (2-\sqrt{2})v_1+\sqrt{2}v_2=0$$ Is it correct so far? Or have I undersood it wrong?
Comment: There are infinitely many vectors that are perpendicular to a given vector. Any and all of them are acceptable (assuming there are no other constraints on the $t$ values). The easiest is: given $(a,b)$ a perpendicular vector is $(-b,a)$. $$(a,b)\cdot(-b,a) = -ab+ab =0 $$ Therefore if $(2-\sqrt{2},\sqrt{2})$ is parallel, then $(-\sqrt{2}, 2-\sqrt{2})$ is perpendicular.
Answer: Notice, we have $$x=2\cos t-\cos 2t \implies \frac{dx}{dt}=-2\sin t+2\sin 2t$$
$$y=2\sin t-\sin 2t \implies \frac{dy}{dt}=2\cos t-2\cos 2t$$
Hence, the slope of the tangent to the curve is given as $$\frac{dy}{dx}=\frac{\frac{dy}{dt}}{\frac{dx}{dt}}=\frac{2\cos t-2\cos 2t}{-2\sin t+2\sin 2t}=\frac{\cos t-\cos 2t}{\sin 2t-\sin t}$$
Hence, the slope of the tangent at $t=\frac{\pi}{4}$
$$=\left(\frac{dy}{dx}\right)_{t=\frac{\pi}{4}}=\frac{\cos\frac{\pi}{4} -\cos \frac{\pi}{2}}{\sin \frac{\pi}{2}-\sin \frac{\pi}{4}}=\frac{\frac{1}{\sqrt 2}-0}{1-\frac{1}{\sqrt 2}}=\sqrt 2+1$$
Now, the point of tangency $(2\cos t-\cos 2t, 2\sin t-\sin 2t)$ at $t=\frac{\pi}{4}$ is $(\sqrt 2, \sqrt 2-1)$ hence, the equation of the tangent is given by point-slope form as follows
$$\color{}{y-(\sqrt 2-1)=(\sqrt 2+1)(x-\sqrt 2)}$$
$$\color{red}{y=(\sqrt 2+1)x+2\sqrt 2+1}$$
Now, the equation of the line perpendicular passing through the point $(\sqrt 2, \sqrt 2-1)$ to the tangent  is given as
$$\color{}{y-(\sqrt 2-1)=\frac{-1}{(\sqrt 2+1)}(x-\sqrt 2)}$$
$$\color{}{y-(\sqrt 2-1)=-(\sqrt 2-1)(x-\sqrt 2)}$$
$$\color{red}{y=-(\sqrt 2-1)x+1}$$

How we can find the perpendicular line?


Possible to check mutex is locked before calling pthread_cond_wait()?

Question: I'd like to add some debugging code to an abstraction of pthread_cond_wait in my code to check that the calling code really holds the mutex, as it should. This is to check correctness of the rest of the callers.
Is there a way to check if the mutex is locked, or enable a debug mode in the pthreads implementation (on Linux) to tell me if it's not?
Comment: If it's not completely obvious that you own the mutex at this point, your code needs serious fixes...
Comment: @R.. For simple cases, fine. As the code grows and becomes more complex, and is worked on over time by different people, less obvious. Verification is preferable to relying on "obvious" correctness.
Comment: If the scope in which a lock is held is so poorly defined that you're not sure whether it's held or not when you get to `pthread_cond_wait`, then the code is almost surely full of deadlocks. In good code, at any particular point where you might call a synchronization primitive, the set of relevant locks you hold should be a static constraint (relative to variable parameters reflecting which objects you're working on).
Answer: If you create the mutex as an error-checking mutex, using:
pthread_mutexattr_t attr;
pthread_mutex_t errchkmutex;

pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&errchkmutex, &attr);

...then pthread_cond_wait() will return EPERM if the mutex is not locked by the calling thread.
(of course you would add error-checking to that mutex initialisation code).
I think error-checking mutexes are exactly the kind of "debugging mode" that you're looking for.
Answer: pthread_cond_wait will fail unless the mutex is locked by the calling thread. Are you checking return values of pthread functions?  If not, this is a recipe for disaster, moreso with threading than with other system calls.
Comment: `EPERM` is only relevant for error-checking mutexes (and perhaps recursive ones but opengroup.org is down at the moment and I don't have a local copy of POSIX handy). For normal mutexes, calling `pthread_cond_wait` without holding the mutex is UB. Thus, if you mention that you need to make the mutex an error-checking one, this answer would exactly solve OP's problem!
Comment: Your manpage is wrong (linux doc has always been crap), or you are running some obscure version of linux that does not implement POSIX semantics. pthread_cond_wait is specified to return EPERM if "The mutex was not owned by the current  thread  at the time of the call."  See, for example, here: http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?pthread_cond_wait+3  (in any case you can make a simple test program.)
Comment: I tested. pthread_cond_wait() works fine and returns 0 if the mutex is not locked by the calling thread, on both my development Linux machine and my embedded Linux target.
Comment: My man page says "pthread_cond_init, pthread_cond_signal, pthread_cond_broadcast, and pthread_cond_wait never return an error code."
Comment: Then you should report a bug to libc and kernel maintainers.
Comment: @zvrba: It is not a bug, because [POSIX only requires](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html) the `EPERM` return for `PTHREAD_MUTEX_ERRORCHECK` or robust mutexes.
Answer: The answer, pieced together from zvrba and "R" and some other research, is to create the mutexes with error-checking attributes and check the return value of pthread_cond_wait().
pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_ERRORCHECK);

Other relevant info:

My glibc requires #define _GNU_SOURCE before any includes to enable pthread_mutexattr_settype()
I found I do have the POSIX manpages installed as well as the "LinuxThreads" ones. I'm not sure what (ubuntu) packages the various ones came from, but editing /etc/manpath.config to put "3posix" first means I get the right ones now.


Restful URL - how to design a URL to update a resource based on property, not id

Question: If book is a resource, and the server assigns an id to every single book, we can think of the id as a resource id.
<code>/POST /books/  - create a new book resource
/GET  /books/12345  - retrieve book resource with id 12345
/POST /books/12345  - update book 12345
</code>
But book resources can have some properties, like ISBN.
If I want to update a book resource based on given ISBN, how do I design the URL?
Answer: <code>/POST /books/isbn/{isbn_id}
</code>
or if you project just need isbn for the book identification, and not the id of each book, you can just replace book id with isbn id.
<code>/POST /books/{isbn_id}
</code>
Comment: Hi Shukri, Thanks for your suggestion. If I am using both /POST /books/{id} and /POST /books/{isbn_id}, service can't know it's id or ISBN. If use /POST /books/isbn/{isbn_id}, looks like isbn is a type of resource, but it's just a property of book resource.
Comment: it's up to you how you want to design it, as long as you can handle it. another solution pass the isbn_id itself via POST form payload. so  it just `/POST /books/isbn`. isbn_id and all other information, you can pass on the body.


chkconfig not automatically starting mysql

Question: I have mysql set in chkconfig to automatically start when the system reboots:
root@myserver:~#chkconfig mysql
mysql  on

However, this does not seem to be the case. When the system reboots, I get the following error on my PHP pages:
SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

If I run service mysql start, the PHP pages begin to work (the above error does not appear, and queries return values). Is this an inappropriate configuration on my part? What else do I need to do to get mysql to start correctly after a reboot?
Note: I'm running mysql on a SLES VM.
Comment: Is it able to start at all? Are you getting errors in the mysql logs?
Comment: It starts fine if I run `service mysql start`, but not at boot. My `/var/log/mysqld.log` file only shows from the point I ran `service mysql start`.
Comment: `ps aux |grep mysql`. It there another MySQL daemon running already?
Comment: No mysql process was running until I started it myself.
Answer: Perhaps something went wonky when the init script was installed. I'd recommend the following:
chkconfig --del mysql
chkconfig --add mysql
chkconfig mysql on

Certainly can't hurt.
Comment: chkconfig mysqld ...
Comment: Not necessarily, it depends upon the distribution.
Answer: Are you starting up MySQL at the correct init level ? the network services should be up before mySQL can be started .
S
Comment: Are you talking about runlevels? If so, both `network` and `mysql` are set to 2,3, and 5
Answer: mysql is the client. If you have installed mysql server before, you can start it with

service mysqld start

Please check:

chkconfig mysqld


how database relationship work in databases

Question: I have started a new job recently as .Net Developer, in that for the projects that I am working on requires strong understanding of relationships like
1-N, 1-1 and N-N. I have completely understood 1-1 relationship with real life example like In a Tablets and Billing table if Billing table has TabletId as a foreign key then there is 1-1 relationship between them, but talking about 1-N and N-N relationship regarding same tables how the real life example can be put forward. I have not completely understood.
Tablet
TabletId
Name
description
Maker
ExpiryDate
Billing
BillingId
TabletId F.K
TDate
so from above table structure it is clear that one bill can have one tablet only. but if i want one bill can have multiple tablets then how will i achieve that.
Please give me example of Tablets and Billing table for 1-N and N-N relationships
Comment: This is a faq. Before considering posting please always google your error message or many clear, concise & precise phrasings of your question/problem/goal, with & without your particular strings/names, & read many answers. If you post a question, use one phrasing as title. See [ask] & the voting arrow mouseover texts. PS What examples have you seen in any presentation of these notions?
Answer: When talking about relationships in a database, one could be more precise by stating the minimum and maximum links. The relations we usually see in a database are:

1:1 implemented as {1}:{0,1} Example: a user has or doesn't have one address. So, each user has 0 to 1 addresses; an address belongs to one user.
1:n implemented as {1}:{1,n} Example: a user has one or more or no phone numbers. So, each user has 0 to n phone numbers; a phone number belongs to one user.
m:n implemented as {0,m}:{0,n} Example: a product in one or more or no shops; a shop sells one or more or no products.

And here is how we omplement these relations:

The address table has a user ID and it's the table's primary key.
The phone table has a user ID.
There is a bridge table linking product and shop consisting of these two columns: product ID and shop ID.

Of the three relations the first (1:1) is rare. Usually we would rather store the values in a single table. But in the address example we could use it to easily guarantee that a user either has a full address with both street and city and country given or none at all.
The 1:n and m:n relations are both frequent in databases.


Python envio de múltiplos e-mail com anexos diferentes

Question: Estou criando um bot em python, para envio de e-mails para algumas pessoas com anexo diferentes, o código está assim:
    import win32com.client as win32
    import time
    import os

    #Informações do e-mail
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = 'firstname.lastname@example.com'

   #Percorre o diretório de anexos
for attachment in  os.listdir(r"pasta_anexos"):
      #Agrengando os arquivos da pasta a uma string
      file = (os.path.join(r"pasta_anexos",str(attachment)))
      if str(file).endswith('test1.txt'):
          #Anexando test1.txt
          mail.Attachments.Add(file)
          #Percorrendo novamente o diretorio, para nexar o segundo arquivo
          for attachment2 in os.listdir(r"pasta_anexo"):
              #Agrengando os arquivos da pasta a uma string
              file2 = (os.path.join(r"pasta_anexo",str(attachment2)))
              if str(attachment2).endswith("test2.txt"):
                  #Anexando test2.txt
                  mail.Attachments.Add(file2)
          #informações finais do e-mail, para quem e assunto
          mail.To = 'firstname.lastname@example.com'
          mail.Subject = "Empresa X " + attachment
          mail.display()
          time.sleep(5)
          mail.Send()
          break

print('------------------ Primeiro e-mail ------------------')

Atualmente estou enviando um e-mail com dois anexos, mas precisaria enviar mais um com dois anexos diferentes, no primeiro e-mail vai dois arquivos test1.txt e test2.text, no segundo iria test3.txt e test4.text, mas quando tento colocar outro For o spyder da erro que não achou o segundo o test3.txt
Answer: você cria o objeto "email" na linha mail = outlook.CreateItem(0) - é só colocar essa linha e as seguintes dentro do for - para criar e enviar um e-mail para cada arquivo.
Você não falou que precisa enviar os arquivos para emails diferentes, mas não disse como vai saber esses e-mails. Se forem baseados no nome do arquivo, dá para fazer um dicionário, por exemplo, mapeando cada extensão de arquivo para um endereço  -
ou se forem endereços em sequência, poderia usar a chamada  zip no for para ter um endereço de e-mail diferente, junto com um arquivo diferente em cada chamada do for - mas isso basicamente vai juntar pares aleatórios de arquivos e emails, dificilmente é o que você gostaria na vida real.
De qualquer forma, pra mandar 4 e-mails diferentes, com cada um com um arquivo, e mudando o acesso a arquivos para usar a pathlib - o novo jeito do Python de acessar pastas e arquivos, fica assim:
from pathlib import Path
import win32com.client as win32
import time
import os

#Informações do e-mail
outlook = win32.Dispatch('outlook.application')

folder = Path(r"pasta_de_anexos")

#leitura documentos em anexo
for attachment in folder.iterdir():
    #envio de e-mail
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = 'email@example.com'
    mail.HTMLBody = "
Olá,

Segue documentos em anexo.

Atenciosamente.
"
    mail.Attachments.Add(str(attachment))
    # coloca o nome do arquivo, sem a extnsão, como endereço do email antes do "@"
    mail.To = firstname.lastname@example.com'
    mail.Subject = str(attachment)
    mail.display()
    time.sleep(5)
    mail.Send()

Usando o pathlib.Path nãp é mais necessário ficar chamando os.path.join -
por outro lado, para tratar o caminho do aquivo como uma string, precisa
fazer a chamada str(...) como fiz acima.
Além disso, o jeito que você estava tentando testar o nome do arquivo na linha
do "if" era essencialmente aleatório - você foi jogando coisas sem entender
o que estava fazendo e esperando que funcionasse: em programação nada funciona
assim.
Python ficou famoso por ser fácil de aprender há mais de 15 anos
atrás por causa de uma funcionalidade que hoje as pessoas
não percebem que existe, talvez por que os
cursos e documentação não deem enfase: há o modo interativo
onde você pode testar as coisas.
Use o Python no terminal, no app idle, ou embutido na IDE
que você está usando, se estiver usando alguma para testar
as coisas direto - vendo o resultado, antes de
tentar por no programa.
Se entrar no Python e chamar o método .startswith de uma
string dá pra entender como ele funciona, e não
vai ficar tentando colocar "=="
In [33]: "teste23".startswith("teste")
Out[33]: True

In [34]: "tosto23".startswith("teste")
Out[34]: False

Fazer isso também vai te deixar mais familiarizado com for, if e outros
comandos e chamadas básicas - quando for colocar no programa,
você já vai te tentado, de jeitos certos e errados umas 10, 20 vezes
no modo interativo e vai saber como funciona. É muito mais tranquilo
do que não ter ideia de como é pra ser no código, e aí rodar e ver uma
mensagem de erro e ficar tentando adivinhar o que o erro
quer dizer.
Comment: Sobre os emails, só para citar, test1 deve ser enviado ao firstname.lastname@example.com, test2 para o email@example.com, eu estava pensando em colocar cada e-mail dentro do if
Comment: Nao = a[i é só extrair o nome do destinatário do e-mail do próprio nome do arquivo. Se o nome do arquivo fosse uma string, como no seu código, era só fazer `.split('.')[0]` - com a pathlib é só usar o atributo "stem" (o nome do arquivo sem a extensão) - vou atualizar acima


Updating Shared Preferences while updating user information

Question: I am using a Shared preferences class to hold the information of the user after login, for later updating I am using the information I have kept in the Share preferences class but when I update user information I have to log out from the profile and then log in the see the changes. Can anyone help me to in how to change the information in the SharedPrefManager class while I update the user info? Bellow is the SharedPrefManager Class and user updating Class.
public class SharedPrefManager {

    private static SharedPrefManager mInstance;
    private static Context mCtx;

    private static final String SHARED_PREF_NAME = "mysharedpref";
    private static final String KEY_USERNAME = "name";
    private static final String KEY_USER_EMAIL = "email";
    private static final String KEY_USER_ID = "id";
    private static final String KEY_USER_DESCRIPTION = "description";

    private SharedPrefManager(Context context) {
        mCtx = context;

    }

    public static synchronized SharedPrefManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefManager(context);
        }
        return mInstance;
    }

    public boolean userLogin(int id, String name, String email , String description){

        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putInt(KEY_USER_ID, id);
        editor.putString(KEY_USERNAME, name);
        editor.putString(KEY_USER_EMAIL, email);
        editor.putString(KEY_USER_DESCRIPTION, description);
        editor.apply();

        return true;
    }

    public boolean isLoggedIn(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        if(sharedPreferences.getString(KEY_USERNAME, null) != null){
            return true;
        }
        return false;
    }

    public boolean logout(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        return true;
    }

    public String getUsername(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USERNAME, null);
    }

    public String getUserEmail(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USER_EMAIL, null);
    }

    public String getUserDesc(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(KEY_USER_DESCRIPTION, null);
    }

}

This the User Updating Class.
public class EditProfile extends AppCompatActivity implements View.OnClickListener {
    EditText name, description;
    String email;
    private ProgressDialog progressDialog;
    Button update, delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        name = (EditText) findViewById(R.id.editText);
        description = (EditText) findViewById(R.id.editDes);
        update = (Button) findViewById(R.id.editUpdate);
        delete = (Button) findViewById(R.id.DeletePro);
        name.setText(SharedPrefManager.getInstance(this).getUsername());
        description.setText(SharedPrefManager.getInstance(this).getUserDesc());
        email = SharedPrefManager.getInstance(this).getUserEmail();
        progressDialog = new ProgressDialog(this);
        update.setOnClickListener(this);
        delete.setOnClickListener(this);
    }

    private void updateUser() {
        final String username = name.getText().toString().trim();
        final String desc = description.getText().toString().trim();

        if (username == "" || desc.length()>100) {
            Toast.makeText(getApplicationContext(),"Invalid User Name or Description is exceeding thr limit",Toast.LENGTH_SHORT).show();
        } else {

            progressDialog.setMessage("Updating Information ...");
            progressDialog.show();
            StringRequest stringRequest = new StringRequest(Request.Method.POST,
                    Constants.URL_updatePro,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            progressDialog.dismiss();

                            try {
                                JSONObject jsonObject = new JSONObject(response);

                                Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            progressDialog.hide();
                            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("name", username);
                    params.put("email", email);
                    params.put("description", desc);
                    return params;
                }
            };

            RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
            finish();
        }

    }

    @Override
    public void onClick(View v) {
        if (v == update) {
            updateUser();
        }
        if (v == delete)
        {
            startActivity(new Intent(EditProfile.this, DeleteProfile.class));
            finish();
        }
    }
}

Answer: Check this link: Answered here
I showed a guy how to implement sharedPrefs, It's fairly simple to update the preferences and every time you re-initialize an activity or fragment your code should automatically retrieve whatever is stored in the SharedPrefs. That means that if you update the user's name in Activity A, when you load Activity B, it will fetch the sharedPrefs and find this new name (Assuming your getSharedPrefs code is within the onCreate or onResume method for your fragments/activities).
If you're not seeing the sharedPrefs info update within your activity, it may be because the activity is not refreshing (either because you haven't told it to, or because something has broken). You could try adding a 'refresh' button to the activity to test this, which would restart the activity, rather than logging out/in - which does the same thing as refreshing.
Answer: I think here u getting the update profile info.
 @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("name", username);
                params.put("email", email);
                params.put("description", desc);
                name.setText(username);
                description.setText(desc);
                return params;
            }

Hope this will work
Comment: sorry to say, Shared preference have no auto call method. U have to do everything by u ..