A problem on finding some covering space

Question: Describe three pairwise non-homemorphic two-fold coverings of $RP^{2}\vee S^{1}$.  $RP^{2}$ is the real projective plane and $\vee$ represents the wedge product of topological spaces.
I know that map $S^{2}\rightarrow RP^{2}$ is a two-fold covering. So the space $S^{2} \vee S^{1} \times S^{1}$ is one desired space.But I have some difficult to find the other two.
Comment: Hint/suggestion: Do you know any two-sheeted coverings of the circle?
Answer: here they are:

the second and third are homotopy equivalent to $S^2\vee S^1\vee S^1$, but are not homeomorphic to.
these three coverings correspond to three different subgrups of $\pi_1(\mathbb RP^2\vee S^1)=\mathbb Z*\mathbb Z_2$ of index $2$. denote the generators of $\mathbb Z$ and $\mathbb Z_2$ by $a$ and $b$. then these subgroups are the normal closures of
$\langle a^2,b \rangle$
$\langle a, bab \rangle$ and
$\langle ab \rangle$.
Comment: I've read your proof for several days and find as many relative theorems as possible to understand your proof.But I still don't understand it.Can you specify your answer a little bit.I'm really grateful and I'm sorry for my silliness. For example,can you give me some hints about how to prove the figures you pictured are the covering space in strict way and how to calculate the fundamental group of these spaces ?


RTK Toolkit how to use builder syntax with action creators with createSlice?

Question: I'm experienced in Redux but I'm totally new to Redux Toolkit (RTK) and createSlice. I'm trying to follow tutorials on official RTK Query docs but I'm getting lost.
I've created my actions: (assume there is a type called 'Model')
const setModel = createAction<Model>('setModel');

Then I've defined my state:
type MyState = {
  model: Model;
}

const initialState: MyState = {
  model: models[0], // points to a valid object of type Model
};

Then I try to create my slice:
export const mySlice = createSlice({
  name: 'x',
  initialState,
  reducers: {

  },
  extraReducers: builder => {
    builder.addCase(setModel, (state, action) => {
      state.model = action.payload;
      return state;
    });
  },
});

The docs seem to recommend the extraReducers approach to use with action objects and builder directly, which also seems to implicitly support Immer. So I wrote my simple case for setModel. However, when I try to use it in a component:
const dispatch = useDispatch();
dispatch(mySlice.actions.setModel(pickedItem));

mySlice.actions is empty and doesn't include an entry named setModel. It's not a TypeScript issue, putting a breakpoint when running also reveals that it's indeed empty:

Then I've read more and heard that extraReducers doesn't create action creators, whereas reducers does (which probably explains why my actions are empty). However, then I can't use the builder syntax which RTK Toolkit recommends in the first place.
At this point I'm totally lost.
How can I use createSlice with strongly-typed and autogenerated action creators, or if that's not possible, what's the recommended pattern for createSlice?
Answer:
How can I use createSlice with strongly-typed and autogenerated action
creators?

You can type the payloads of the reducers in the slice, the actions will be generated for you, and be correctly typed.
Example:
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

type MyState = {
  model: Model;
}

const initialState: MyState = {
  model: models[0],
};

const mySlice = createSlice({
  name: 'x',
  initialState,
  reducers: {
    setModel: (state, PayloadAction<Model>) => {
      state.model = action.payload;
    },
  },
});

export const {
  setModel
} = mySlice.actions;

export default mySlice.reducer;

The extraReducers are primarily used to handle external actions, e.g. asynchronous actions and actions generated by other slices.


Characterisation of compact subsets of Banach spaces

Question: I have the following homework question:
Characterize the compact subsets of the following Banach spaces:
(1) The space $c_0$ of null sequences (that is, sequences $(x_n)$ of scalars with $ | x_n | \rightarrow 0$ as $n \rightarrow \infty$) with the norm $\|(x_n)\| = \sup_{n \geq 1} |x_n| = \max_{n \geq 1} |x_n|$.
What I think could be an answer:
If $(c_0, \| \cdot\|_\infty)$ is compact then by Ascoli-Arzelà a set is compact if and only if it is closed, bounded and equicontinuous. So I need to show that $c_0$ is compact and once I have that I claim that the closed bounded sets have the basis the closed balls in the metric induced by $\|\cdot\|_\infty$. Then I need to show that the sequences in these balls are equicontinuous.
Edit
Using your comments:
Let $\mathbb{N}_\infty$ denote $\mathbb{N} \cup \{ \infty \}$. Then this space is compact (it is homeomorphic to $\{ 0 \} \cup \{ \frac{1}{n} | n \in \mathbb{N} \}$). Then $c_0$ is homeomorphic to $\{ x | x( \infty ) = 0 \} \subset C(\mathbb{N}_\infty)$. Therefore $K \subset c_0$ is compact iff $K$ is compact in $C(\mathbb{N}_\infty)$. Now Ascoli-Arzelà applies and so $K$ is compact iff $K$ is closed, bounded and equicontinuous.
So I need to write down what closed, bounded, equicontinuous sets look like. I claim that they have the basis the closed balls in the metric induced by $\|\cdot\|_\infty$.
Many thanks for your help.
Comment: Following @kahen's idea: You can apply Arzelà-Ascoli. Let $\mathbb N_\infty = \mathbb N \cup \{\infty\}$ denote $\mathbb N$'s one-point compactification. Then $c_0 \cong \{x \in C(\mathbb N_\infty) \mid x(\infty) = 0\}$. Now $A \subseteq c_0$ is compact, iff it is compact seen as subset of $C(\mathbb N_\infty)$.
Comment: In your edit you probably mean $C(\mathbb{N}_\infty)$ instead of $\mathbb{N}_{\infty}$ several times. I also suggest **not** to use Arzelà-Ascoli (which is somewhat overkill) in the final solution, but to redo the argument **by hand**. You will understand Arzelà-Ascoli much better if you spell out the translation in the explicit case at hand here.
Comment: Hint: a real sequence that tends to $0$ is the same thing as a function from the one-point compactification of $\mathbb{N}$ to $\mathbb{R}$ that sends $\infty$ to $0$.
Comment: (now it is fixed and ok). Here's another thing you should think about. The unit ball is **not** compact. The sequence $(1,0,0,\ldots), (0,1,0,\ldots), (0,0,1,\ldots),\ldots$ is a closed and bounded set (and contained in the unit ball) but it does *not* have a convergent subsequence (any two distinct elements have distance $1$, so there is no Cauchy-subsequence). So your *"I claim that they have the basis the closed balls in the metric induced by $\|\cdot\|_\infty$."* must be incorrect.
Comment: The reason why you can't apply Arzelà-Ascoli here is that $c_0 = C_0(\mathbb{N})$ and $\mathbb{N}$ is not compact
Comment: You forgot to take the point at infinity into account! Remember that the basic neighborhoods $U_N$ of infinity are the sets $U_{N} = \{\infty\} \cup \{n \geq N\,:\,n\in\mathbb{N}\}$, so you need to add a condition that guarantees that the set is equicontinuous there...
Comment: What this exercise wants you to find is a propostion like Arzelà-Ascoli, but for $c_0$, not for $C(K)$, i. e. sth. like: "A subset $A \subseteq c_0$ is compact iff $A$ is bounded, closed and .....".
Comment: @martini: thanks! That's clever : )
Comment: You now should try to figure out what equicontinuous means for $K \subseteq c_0$ ...
Comment: It is not clear to me if the first edit is a mess because of misunderstanding of the question or because of carelessness (you mix up $\mathbb N_{\infty}$ and $C(\mathbb{N}_\infty)$ quite badly). Try to fix that! Concerning your second edit: Make it *explicit* what your condition gives. You can't improve upon closed and bounded, but you should be able to say: "A set of sequences is equicontinuous if and only if ..."
Comment: @t.b.: thanks! I think I've corrected it. Maybe it's your browser's cache if you can still see $\mathbb{N}_\infty$?
Comment: @t.b.: I think every subset is equicontinuous: for any $\varepsilon$ choose $\delta := 1 / 2$ then $|x(n) - x(n^\prime)| = 0 < \varepsilon$ if $|n - n^\prime| < \delta$.
Answer: I'd like to redo the argument used in the proof of Arzelà-Ascoli by hand for this homework:
For $S \subset c_0(\mathbb{N})$ we want to show that $S$ is compact if it is closed, bounded and such that for $\varepsilon > 0$ there exists an $N$ such that for $n > N$ we have $|s(n)| < \varepsilon$ for all $s$ in $S$.
Let $S \subset c_0(\mathbb{N})$ be such a set. We'll show that $S$ is compact by showing that every sequence $s_n$ in $S$ has a convergent subsequence $s^\prime_n$. ($c_0(\mathbb{N})$ is a metric space so compactness and sequential compactness coincide.) For $s^\prime_n$ to be convergent in $S$ it is enough to show that it is Cauchy because $c_0(\mathbb{N}) $ is complete so every Cauchy sequence converges in it. $S$ is closed by assumption so it contains all its limit points, in particular the limit of $s^\prime_n$.
$S$ is also bounded by assumption, i.e. there exists an $M \in \mathbb{R}$ such that $\|s \|_\infty \leq M$ for all $s$ in $S$. So in particular, $s_n(1)$ is a bounded sequence in $\mathbb{R}$ hence by Bolzano-Weierstrass contains a convergent subsequence $s_{n1}(1)$. $s_{n1}(2)$ is again a bounded sequence in $\mathbb{R}$ hence again contains a convergent subsequence $s_{n2}(2)$ which converges at $1$ and $2$. Repeating this argument we get $s_{nk}$, a sequence of functions converging at $1, \dots , k$.
Now we define $g_k (i) := s_{kk}(i)$ then $g_k$ is a function that converges pointwise on all of $\mathbb{N}$. To finish the proof we show that $g_k$ is a Cauchy sequence with respect to $\|\cdot \|_\infty$.
We can use the triangle inequality to get the following:
$$ |g_k(n) - g_j(n)| \leq |g_k(n)| + |g_j(n)|$$
By assumption on $S$ there exists an $N_\varepsilon$ such that for $n > N_\varepsilon$ we have $|g_k(n)| < \frac{\varepsilon}{2}$ and $|g_j(n)| < \frac{\varepsilon}{2}$ for all $j,k$.
For $n \leq N_\varepsilon$ we know that by construction $g_k(n)$ is a Cauchy sequence in $\mathbb{R}$ so there exists an $N_n$ such that for $k,j>N_n$ we have $|g_k(n) - g_j(n)| < \varepsilon$.
Hence we have that for all $j,k > \max \{ N_1, \dots, N_{N_\varepsilon}, N_\varepsilon \}$ and all $n$:
$$ |g_k(n) - g_j(n)| < \varepsilon $$
and hence $\sup_{n \in \mathbb{N}} |g_k(n) - g_j(n)| = \| g_k - g_j\|_\infty \leq \varepsilon$ which means that $g_k$ is Cauchy with respect to $\|\cdot\|_\infty$.
So $S$ is compact.


Drupal 7 Site for Displaying PPT or JPG

Question: I am relatively new to Drupal and am about to develop a tribute site.  It will have a few informational pages but it's main focus is photographs.
There are about 150 photographs which have been sorted into about 10 categories.  I have these in raw form, and also in a powerpoint deck.  My preference would be to display the photos individually, but I'll use the powerpoint if it proves too difficult.
Ideally users would be able to navigate to a category of photos, then flick through them one at a time, or 'play' a slideshow.  Also, if it was not too difficult, I'd like to annotate some or all of the photos.
Where should I start with this?  I have installed Drupal 7 but see there is a wide range of modules and approaches for displaying photos.  I have experience with CSS, jQuery and PHP...
Any pointers much appreciated!
Answer: There are many, many ways to do this in Drupal but I'll outline two basic approaches for D7.
First, you'll definitely have a much easier time working with .jpg than .ppt.  As Drupal is open source, it supports open file formats (jpg) much better than proprietary ones (ppt).
Warning: this is not a complete tutorial; writing one would have far too many steps and is out of scope for this site.
APPROACH 1
Views Slideshow:  This relies on the Views module.  If you're new to Drupal, you should definitely learn how to use Views first; Node One has an excellent tutorial on Views.  Using Views slideshow, you would roughly do the following:

Create a content type for your images.
Create a vocabulary Categories using the Taxonomy module and add each individual category as a term.
Create a node of content type image for each picture.
Configure Views Slideshow to show each gallery on its own page.

Why use this approach?  Each picture will be its own node.  This allows you to later add different fields to each picture such as a rating (with Fivestar) or the name of the photographer, etc.
APPROACH 2
Field Slideshow: This approach allows you to store all of the pictures for each gallery on a single node.  To do this:

Create a content type for galleries and add a field to hold the pictures.  Make sure it allows for multiple values.
Create a node of content type gallery for each category.
Configure Field Slideshow.

Why use this approach?  It is somewhat simpler to set up and requires less tinkering with Views.  However, it is less flexible.

Drupal 7 Site for Displaying PPT or JPG


Cannot find '.exec_blind' in object /KLauncher at org.kde.klauncher

Question: I recently rebooted my ubuntu environment (kde-plasma, running ubuntu 18.04), and now I'm having trouble launching a command I had previously aliased.  I typed the command itself manually, and get this issue:
Cannot find '.exec_blind' in object /KLauncher at org.kde.klauncher
Command ran was: qdbus org.kde.klauncher /KLauncher exec_blind "/usr/bin/dolphin" "/home/username"
I cannot seem to figure out via google fu or otherwise how to go about fixing this.
Any suggestions?  I know that it worked prior to reboot, and I know the command should in theory exist still.

Link to KLauncher class api from kde.  The method exists, but I've no idea why my setup is confused.

Link to where I originally had the idea to launch dolphin via dbus/ sourced my modified script from.
Answer: The correct commmand is the following:
qdbus org.kde.klauncher5 /KLauncher exec_blind "/usr/bin/dolphin" "/home/username"


Elements of order $9$ in $C_{135} \times C_6 \times C_9$

Question: Ok, so I first split everything up into powers of primes and get
$$C_{27} \times C_5 \times C_2 \times C_3 \times C_9$$
Now, I want to find elements of order 9 in each of these cyclic groups. This means I get:

$\varphi(27) = 18$ in $C_{27}$
None in $C_5$
None in $C_2$
Pick arbitrary $3$ for $C_3$
$\varphi(9) = 6$ in $C_9$

And so the number of elements of order $9$ in my group is $18 \cdot 3 \cdot 6 = 324$.  IS this correct?
Comment: Also, there can be elements of order 9 in the product such that one component has order 9 and the other components have orders that are divisors of 9.
Comment: The number of elements of order $9$ in a cyclic group does not depend on the order of that group other than to check whether $9$ divides the order (it will always be $6 = \varphi(9)$ as long as that is the case). Come to chat, it is slow anyway.
Comment: Basically, you want elements of $C_{27}$ and $C_9$ whose maximum order is $9$. Then you can pick any element of $C_3$. The best way to do this is a simple inclusion-exclusion
Comment: Oops.  The "Also" in my previous comment referred to Tobias's comment.  Thomas's comment, which he added while I was  typing mine, already incorporates what I said.
Comment: @AndreasBlass Yeah, but yours is more general. :)
Comment: @ThomasAndrews Is the maximum number of elements of order $9$ in $C_9 = 9$? I didn't know if it was $9$ or $6$.
Comment: @Tobias I don't understand your point, are you saying that there are only $6$ elements of order $9$ in the whole group as $9$ divides $135 \times 3 \times 9$?
Comment: Come to chat. That is a better place to explain these things.
Answer: For the total element $x = (x_{27}, x_5, x_2, x_3, x_9)$ to have order $9$, all of the $x_n$ need to have order a divisor of $9$, and at least one of them have to have order exactly $9$. In the case of $x_5$ and $x_2$, the only element it could be is the respective identity elements. So we need to pick:

An element $x_{27}\in C_{27}$ of order $1$ (one element), $3$ (two elements), or $9$ (six elements).
An element $x_3 \in C_3$ (three elements)
An element $x_9 \in C_9$ of order $1$ (one element), $3$ (two elements) or $9$ (six elements)
At least one of the two elements from 1. and 3. has to be of order $9$.

And there we have it. So we count: If $x_{27}$ has order $9$, then the rest can be chosen freely, and we end up with $6\times 3\times 9 = 162$ different elements. If $x_{27}$ does not have order $9$, then $x_9$ must be of order $9$, and we get $3 \times 3 \times 6 = 54$ different elements. In total we get $162 + 54 = 216$ elements of order $9$ in your group.
Comment: There are only three elements of order $1,3$ in $C_{27}$, I think, not $4$


Is an intersection of prime ideals equal to their product?

Question: Suppose $R$ is a commutative ring with identity, and let $P_1 , P_2, ..., P_n$ be distinct prime ideals in $R$.
Is it then true that
$$ P_1 P_2 \cdots P_n = P_1 \cap P_2 \cap \cdots \cap P_n?$$
My hunch is that this is not true.
The inclusion $P_1P_2\cdots P_n\subset P_1\cap P_2\cap\cdots \cap P_n$ certainly holds (as this holds for any ideals in $R$). Also, I know that the equality holds if the ideals are maximal. So, in pursuit of a counterexample, I've been looking at rings in which prime ideals are not maximal; and so, PIDs and finite rings are out. My first thought was, of course, $\mathbb{Z}$; but the equality seems to hold in that case.
Am I on a wild goose chase here?
Comment: I think your given inclusion should go the other way. Here is a type of counterexample which maybe doesn't interest you: take $R = \mathbb{Z}[X], P_{1} = \langle X \rangle, P_{2} = \langle X, 2 \rangle$. Then $P_{1} \cap P_{2} = P_{1}$, but $P_{1}P_{2} = \langle X^{2}, 2X \rangle \neq \langle X \rangle$.
Comment: It is true if they are pairwise comaximal $\, P_i + P_j = (1)\,$ for $\,i\neq j,\,$ which is true in one dimensional rings, i.e. when nonzero prime ideals are maximal.
Comment: This is always going to fail if the Krull dimension is bigger than one. For, take a proper inclusion of non-zero primes $P\subset Q$. Then $P\cap Q=P\neq PQ$.
Comment: https://proofwiki.org/wiki/Product_of_Coprime_Ideals_equals_Intersection
Answer: A counterexample is in the ring $R=\mathbb{R}[X,Y]$. Take $P_1=XR$ and $P_2 = XR+YR$. Then $P_1\cap P_2 = P_1$. And $X\in P_1$ is not an element of $P_1 P_2$.
Now let me prove something that does work: $\sqrt{P_1\dots P_n}=P_1\cap\dots \cap P_n$. And for that, the prime $P_i$'s do not need to be distinct. For the inclusion $\subset$, let $x\in R$ such as $x^k\in P_1\dots P_n$. As you said yourself, we have $x^k\in P_1\cap \dots\cap P_n$. And then $x\in P_1\cap \dots\cap P_n$ because each $P_i$ is prime. For the inclusion $\supset$, let $x\in P_1\cap\dots\cap P_n$. Now suppose for the sake of contradiction that for all $k\in\mathbb{N}, x^k\notin P_1\dots P_n$. By Krull's theorem, there exists a prime ideal $Q$ such as $P_1\dots P_n\subset Q$ and $x\notin Q$. Because $Q$ is prime we get $P_i\subset Q$ for a certain  $i\leq n$. That contradicts $x\in P_i$.


On the uniform convergence of the Fourier series of the sawtooth wave

Question: The series $ \ \large \sum_{n=1}^{\infty} \frac{\sin (nx)}{n} \ $
(i) converges uniformly on $ \ [2 \pi-5,5] \ $
(ii) converges uniformly on $ [2 \pi-10,10] \ $
(iii) converges uniformly on $ \ \left[\frac{\pi}{2}, \frac{3 \pi}{2} \right] \ $
(iv) does not converge uniformly .
Answer:
Here we can use Dirichlet's test.
Take $ \ \ a_n=\frac{1}{n} \ $ and $ b_n=\sin (nx) \ $
where $ a_n \ $ is monotonically decreasing .
and
$ \left| \sum_{n=0}^{k} \sin(nx)\right | =\left| \sin (x)+ \sin (2x)+\dots+ \sin (kx) \right| \ \leq \csc \left(\frac{x}{2}\right ) < \infty \ \ \text{if} \ x \neq 0,\pm 2\pi,\pm 4\pi, \dots $
Thus the series converges uniformly 0n $ \ \left[\frac{\pi}{2}, \frac{3 \pi}{2} \right] \ $
The option (i) is wrong because $ [5, 2 \pi-5]=[5, 1.14] \ $ , which is absurd .
Thus option (iii) is true.
But I need better reason why the other options are not correct .
Comment: Concerning (i), one could argue that $[5,2\pi - 5] = \varnothing$, and every sequence of functions vacuously converges uniformly on $\varnothing$. The same for (ii).
Comment: Where does the inequality $\sin x+\sin2x+\cdots+\sin kx\leqslant\csc\left(\frac x2\right)$ come from?
Comment: It is actually absolute value.  $ | \sin x+\sin 2x+...........+\sin kx | =| \frac{\cos (x/2)- \cos (n+1/2) x}{2 \sin (x/2)} |  \leq  cosec (x/2) \ $
Comment: option (i) and (ii) should be incorrect because only one answer can be correct and option (iii) is already correct
Comment: Why isn't the answer accepted?
Answer: Dirichlet's test is pretty useful, but in dealing with pointwise convergence only.
It is well known that
$$ f(x)=\sum_{n\geq 1}\frac{\sin(nx)}{n} $$
is the Fourier series of a sawtooth wave, a $2\pi$-periodic function which equals $\frac{\pi-x}{2}$ on the interval $(0,2\pi)$. We may notice that $f(x)$ is not continuous at the origin, since $f(0)=0$ but $\lim_{x\to 0^\pm}f(x)=\pm\frac{\pi}{2}$ (do you need a formal proof of this fact? If this is the case, please notify me in the comments). The same applies at every element of $2\pi\mathbb{Z}$. A uniformly convergent series of continuous functions is convergent to a continuous function, hence the given Fourier series cannot be uniformly convergent over any closed interval containing $[2\pi k-\varepsilon,2\pi k+\varepsilon]$ for some $k\in\mathbb{Z}$ and $\epsilon>0$. On the other hand the convergence is uniform over any compact set with a positive distance from $2\pi\mathbb{Z}$.


Mean deviation gives better results when deviations are taken from the median, why?

Question:
The mean deviation gives better resuls when deviations are taken from the median instead from the mean, because the sum of the deviations from the median is less than the sum of the deviations from the mean

$$
\operatorname{M.D.}(M)=\frac{\sum|x_i-M|}{N}=\frac{\sum f_i|x_i-M|}{\sum f_i}
$$
This is a widely used statement when defining mean deviation. I understand the proof by which we can say the mean deviation is minimized when deviations are taken from the median. But how come that somehow leads to the statement "mean deviation gives better resuls when deviations are taken from the median instead from mean as the former minimizes the sum of absolute deviations" ?
Screen shot of sample reference
Please check link for the reference.
Comment: I have no idea what "better" is supposed to mean, unless it just means that the sum of the distances is less, which isn't a terribly interesting observation.  Like I say, I frequently use MAD, or other median based results,  when I suspect that my data has bad outliers (but where I don't want to simply strike those from the data set).  Analytically, I prefer to use squared distances as the derivative of the absolute value is problematic at $0$.
Comment: Yes, I understand that this is what you are asking.  As I said, "better" is simply not defined and changes depending on goals and circumstances.  To stress:  these are not $\textit {error}$ estimates, there is no a priori advantage in getting a smaller result.  As I mentioned, if you believe that part of the standard deviation in your data is attributable to unreliable outliers, then this is truly a "better" measure since it cuts down on that effect.  But if you trust your outliers then cutting down their influence is not an obvious plus.
Comment: Well, "better" is obviously subjective.  People sometimes prefer the median deviation because it is less sensitive to outliers.  But you should clarify what you mean.  Oftentimes people speak of MAD, the [Median Absolute Deviation](https://en.wikipedia.org/wiki/Median_absolute_deviation).  That's just the sum of the absolute distances to the median.  That is clearly less sensitive to outliers than the standard deviation, which, after all, squares those extra large distances.  But perhaps you meant something else?
Comment: @lulu pls check the link where this statement is added as the 2nd point in the listing of limits of mean deviation : https://books.google.co.in/books?id=Zifa38x3YzYC&pg=PA114&lpg=PA114&dq=mean+deviation+gives+best+result+when+taken+from+median+why+?&source=bl&ots=6eYLEcxkoc&sig=ACfU3U1Vmfe_SG0MsOTuEE_Y8wU3Rc8iEg&hl=en&sa=X&ved=2ahUKEwiqyLDzlbnpAhVNAXIKHerbAbQQ6AEwEXoECAkQAQ#v=onepage&q=mean%20deviation%20gives%20best%20result%20when%20taken%20from%20median%20why%20%3F&f=false
Comment: @lulu my doubt how can we say the mean deviation gives better results when taken from median instead of mean, certainly not about median absolute deviations ?
Comment: @lulu it says MD from median is better than MD from mean since former is the lowest, doesnt make much sense to me, that is the actual doubt. this statement is found in many books on statistics, which is really confusing.
Comment: @lulu: If the aim is to minimise the mean absolute deviation about a point then that point is the (or a) median.  If the aim is to minimise the mean square of the deviation about a point then that point is the mean, if it exists.  In either case, less is seen as better
Comment: @Henry u said "less is seen a better", why is it better, thats the confusing part here ?
Comment: @ss1729  Henry's point, which is perfectly correct as far as it goes, is this:  if you want to summarize the data with a single point AND if you define the accuracy of a point by the sum of the absolute differences, then the median is the right point to use.  That, of course, is precisely what is meant by saying that the sum is minimized by taking the median.  However, why you would use that metric is very subjective,  As I say, there are times when it is a good idea and times when it is a bad idea. Nothing absolute about it.
Comment: @lulu ,Henry okay, can you give me a sample situation where it somehow benefits ?
Comment: I have given you one.  If you want to the most accurate single number to describe the data, where the accuracy is defined by the absolute difference, then use the median.  That really is something.  After all, most people would measure the accuracy of an estimate by taking absolute difference, not squared distance.  Also, as I have said, if you want to estimate the data but you are concerned that the values you have for the outliers are unreliable, use this method instead.
Comment: @lulu so are you saying that if we suspect the outlier data points are possibly unreliable, minimizing the deviations would benefit somehow ? since median minimizes the absolute deviations, choosing it over mean can benfit in that case ?
Comment: No, the outlier benefit is derived by taking absolute differences instead of squares.
Comment: I don't understand what you are after here.  "Better" is subjective, period. The usual thing to do is to take squared distances to the mean.  There are a number of excellent reasons to do that but it is not the only possible measure.  Switching to absolute differences lowers outlier sensitivity (which is either good or bad depending on you attitude towards outliers).  Then, having done that, switching to median improves the quality of the estimator.  Once again, I wouldn't call either of these things "better" but there are times when they might be good properties to have.
Comment: To stress:  if you use squared distances then the mean is the best estimator.  After all, if $f(x)=\sum (x_i-x)^2$ then $f'(x)=-2\sum (x_i-x)$ which is $0$ when $x$ is the mean.  It's only when you switch to absolute differences that the median becomes the better estimator, so any notion of "better", however subjective, has to hinge on using absolute differences.
Comment: @lulu the effect of outlier points get amplified in the process of squaring in the case of standard deviation, $\sigma$. So if we suspect the outlier points are unreliable we can reduce its effect by taking the absolute values instead of squaring, ie. the mean deviation, right ? This is clear i think.
Comment: @lulu last comment you are showing "mean" minimizes "standard deviation". how this fact lead it to be the best estimator in that case ?
Comment: My point was that the mean minimizes the least squared error.  That is to say, the mean is the best estimator if you measure the accuracy of the estimator by least squares, just as the median is the best estimator if you measure the accuracy of the estimator by absolute difference.
Answer: Whether item 3 under "merits" is a merit depends on what the purpose is.
Item 3 under "limitations" is nonsense. It does in fact not take into account whether an observation is more than the mean or less, at least after the point where the mean is computed, but why would that be a reason to consider anything mathematically incorrect?
Item 2 under "limitations" also depends on what the purpose is.
Item 1 under "limitations" may be subtle.
Now imagine a normally distributed population has standard deviation $\sigma,$ and $\sigma$ is not observable but a finite random sample of $n$ observations is available. The expect value of the mean absolute deviation of the sample is a known scalar multiple of $\sigma.$ Multiplying the mean absolute deviation of the sample by the reciprocal of that known scalar yields an unbiased estimator of of $\sigma.$ Similarly, multiplying the sample standard deviation by another known scalar yields an unbiased estimator of $\sigma.$
Theorem: The one based on the standard deviation has a smaller variance than the one based on the mean absolute deviation.
So that's one thing that could be called a demerit of the mean absolute deviation.
However if the population distribution is only slightly different from normal, that is no longer true.
These lists of "merits" and "limitations" look like something written by a person with little understanding of the subject matter.
Comment: You mean M.D$\leq \sigma$ ? "One based on the standard deviation has a smaller variance than the one based on the mean absolute deviation" how can it be a demerit of the M.D ?
Comment: @ss1729 : No, that's not what I meant. When I wrote about a smaller variance, I meant the variance of the sampling distribution of the estimator would be smaller.
Comment: You said "Item 2 under "limitations" also depends on what the purpose is", could you suggest an example where abs deviations taken from median is beneficial ?
Comment: ss1729 : When you're trying to estimate dispersion in a population whose distribution is far from normal, especially if it has heavy tails. For example, with the Cauchy distribution, the sample mean is not at all a good estimator of location, since its distribution is not more concentrated near the center than is the distribution of a single observation; it does not get more reliable as the sample size grows. In that case using the sample median, and the median absolute deviation of observations from the sample median, is immensely better than trying to do anything involving means.


Which type of regression model for count data should I use for log-series?

Question: I am attempting to identify the effects of mealtime habits on fast food consumption. In this case, the dependent variable is number of times per week a respondent reported eating fast food. As this is count data, I'm using a Poisson or Poisson-related distribution. However there are a few issues with this data. First, tests for overdispersion revealed that my dependent variable is indeed overdispersed:
Overdispersion test
data:  model8.poisson
z = 8.2298, p-value < 2.2e-16
alternative hypothesis: true dispersion is greater than 1
sample estimates:
dispersion
  1.950116

So, a poisson regression is inappropriate.
I also estimated quasipoisson and zero-inflated models, and tested for model fit versus the poisson models. Both the quasi-poisson and zero-inflated were better fits.
Ord plot shows a positive slope (1.62) and a negative intercept (-1.82) which suggests that I should use a log-series model. I have a rudimentary understanding of poisson quasi-poisson distribution models, and negative binomial models. However, I can't find anything on log-series models.
Are there specialized models for these types of data, or should I use one of the other Poisson-related distributions or models (quasipoisson, zero-inflated, negative binomial)?
If there are specialized models, is there an r package for them?
If there are not, which type of model would best fit these data?
Comment: Please describe your models in more detail. This sounds very odd.
Answer: Another natural extension to the Poisson GLM is the negative binomial GLM, which is implemented in R using the glm.nb function in the MASS package.  The negative binomial distribution is a two-parameter distribution which generalises the Poisson distribution, with an additional parameter that controls "overdispersion" in the variance.  The distribution has a natural association with count data through mixtures of Poisson distributions, or through counts of a binary outcome until its opposite.
The quasi-Poisson and negative binomial GLMs are both two-parameter extensions of the Poisson, but they have different functional relationships between the mean and variance.  The former has a variance that is a linear function of the mean, while the latter has a variance that is a quadratic function of the mean.  This means that the distributions weight small and large counts differently.  It is best to fit both these models and see which fits the data better.  Finally, the zero-inflated Poisson model is also a two-parameter extension of the Poisson, but it involves a generalised allowance for more weight at zero, but the shape of the rest of the distribution remains unchanged.  This latter distribution is appropriate where there is a mixture of Poisson counts, plus additional zeros.
Answer: you can try package 'COMPoissonReg', this package includes Zero-inflated CMP regression, has computation of estimates (including pscl for ZIP regression). Here is documentation  https://cran.r-project.org/web/packages/COMPoissonReg/COMPoissonReg.pdf


Visual Studio 2015 Preview , While creating Web Projects throwing Unspecified error HRESULT:0x80004005 (E_FAIL)

Question: I downloaded the VS2015 Preview and tried to create a Web Project.
I am getting the following errors when creating the project itself.
I get a Watson error first 'Unspeciifed error HRESULT:0x80004005 (E_FAIL)' ,
Then When I tried to open the Project Directly from the physical location it is throwing the other error 'Unable to create the Virtual Directory Localhost:5544 ...Error:Filename:redirection.config'
Comment: Problems in beta versions are usual, and it makes not sense to find a general solution for them,because usually there isn't. Make the usual things: install it on another system, try to find a working virtual machine that includes this tool...
Answer: I had tried each of the steps recommended and didn't work. So, my last resource was to review the registry to find out if my user was pointing to a temp or cache folder.
Some posts were suggesting to check on HKEY_LOCAL_MACHINE; but nothing there. So, I finally found it by going into the HKEY_CURRENT_USER as recommended by boilers222.

Opened registry (CTRL+R, regedit, OK)
Navigated to
KEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\
Found out the Personal key was pointing to
\OurServer\RedirectedFolders\MyName\MyDocuments
Selected the Personal key, right clicked on it, and selected Modify
Entered a location pointing to my user's documents file:
%USERPROFILE%\Documents\
Clicked OK and closed the registry editor

When I opened Visual Studio and opened my solution, it loaded without the "unable to access the IIS metabase" error.


Get values from the service class to the activity

Question: I have TrackingService component to track the location of the buses in my city based on Crowdsourcing. In the TrackingService class I have variable pLong, pLat to stored the latitude and longitude when they are calaculated in the onLocatiochChanged(). The TrackingService is operating in the background, where the data is transmitted to the server.
I have an Map Activity to display the location of the buses, the user selected in the MainActivity( as Filter).
Everything is working great but when I try to display the user's current location in the map activity  the received double lng = ts.pLong;double lat = ts.pLat; in the displayMyLocation() are 0.0 although they have values when I dubbuged them and the values are being sent to the server but when I invoke them in the displayMyLocation() they are 0.0
I cant start the map activity from the onLocationChanged() by passing an intent to the map activity.
How can I get these values in my Map activity?
TrackingService class:
public class TrackingService extends Service implements AsyncTaskCallback,
        LocationListener {
    public double pLong;
    public double pLat;
    ...
        @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        detectLocation();
        return START_STICKY;
    }
    private void detectLocation() {
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 0,
                this);
    }
    @Override
    public void onLocationChanged(Location location) {

        if (location != null) {
            pLong = location.getLongitude();
            pLat = location.getLatitude();
           .....

     }

}

Map activity:
public class Map extends FragmentActivity implements OnMapReadyCallback {
  .....
    private void displayMyLocation() {

        TrackingService ts = new TrackingService();
         double lng = ts.pLong;
         double lat = ts.pLat;
         LatLng ll = new LatLng(lat,lng);
         MarkerOptions markerOpt = new MarkerOptions().title("My Location")
                    .position(ll);
         myLocatMarker = map.addMarker(markerOpt);

    }
  ...

  }

Answer: Just because you create the TrackService object, does not mean that the service is started.
You need to start it via context's
startService(<Intent>);

When it gets the GPS info is when it will update, which can take a little time.
What you should do is in your service, you should pass the Activity instance or a callback to the service so it can notify the Activity when it has new info and you can update accordingly.
Answer: is your service(TrackingService) bounded to your activity ?
Comment: The TrackingService is being started from the MainActivity when the app launches.


remove or change metatags in masterpage

Question: I have a masterpage and I wrote metatags in masterpage.master.cs.
In the category page which is generated from the masterpage every category has their own metatags.
When the user visits category.aspx I want to change the metatags.
All metatags are dynamically created and they don't have an id or runat because I create them dynamically with a for loop (reading data from the db).
So I can't change title of the page and metatags. How can I do this?

Thanks David. But if user want to add meta tags how can user do it?
My DB design like that and I have to create tags with for loop. Is it not good?
http://img843.imageshack.us/img843/6940/metadb.png
Is there any other way to write these tags?
@lvo, thanks for answer. But this.Title is not working. I wrote it but nothing change.
Also I didn't put any literal or label in ContentPlaceHolder which ID's head. Because if I put literal or something and I write it meta tags there will be 2 description or keywords in the page. Which one is OK for SEO?
Is there any other way to remove all meta tags?
Answer: To change the title use:

this.Title

To change the metatag, put a placeholder in the head of the masterpage.

<code><head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder> </head>
</code>

You can also place a literal in that placeholder then fill the "text" property of this literal server side with the meta values from the database
Comment: +1 that is exactly his problem, he needs the child pages to control the metatags in the masterpage.  Excellent answer.
Comment: +1. I agree with Achilles, this is the way to go if you're not willing to just use a different Master Page.
Answer: Change your program design.  The first two choices that come to mind are:

Don't generate the META tags in a loop from the DB
Use a different master page for this one page. <-- better choice for simplicity sake.

I know this seems like a flippant answer, but really, why make things harder on yourself (and the poor maintenance programmer who will come along after you) than they have to be?  Keep it simple.
Comment: +1 I was and still am at times a poor maintenance programmer...I cry before I go to sleep...
Comment: I bet you've got just as many horror stories as I do  about maintenance programming.  :)
Answer: I fix my problem. I was wroted metatags in masterpage.master.cs. So other pages which are generated by this masterpage they all take the metatags from main masterpage. We already can't change the tags. Maybe we can change but I couldn't find any code.
I wrote my metatags in default.cs and other pages are normal right now.
Thanks for replies.

remove or change metatags in masterpage


Fourier coefficients for an arbitrary period, different forms?

Question: In three books, the Fourier series coefficients are in different forms.
I don't understand why they are equivalent.
From book 1:
\begin{align}
a_n&=\frac{1}{L}\int_ {-L}^{L}f(t)\cos\Big(\frac{\pi n}{L}t\Big)\, dt\tag 1 \\
b_n&=\frac{1}{L}\int_ {-L}^{L}f(t)\sin\Big(\frac{\pi n}{L}t\Big)\, dt\tag 2
\end{align}
From book 2:
\begin{align}
a_n&=\frac{2}{L}\int_ {-L/2}^{L/2}f(t)\cos\Big(\frac{2\pi n}{L}t\Big)\, dt\tag 3 \\
b_n&=\frac{2}{L}\int_ {-L/2}^{L/2}f(t)\sin\Big(\frac{2\pi n}{L}t\Big)\, dt\tag 4
\end{align}
From book 3:
\begin{align}
a_n&=\frac{2}{L}\int_ {0}^{L}f(t)\cos\Big(\frac{2\pi n}{L}t\Big)\, dt\tag 5 \\
b_n&=\frac{2}{L}\int_ {0}^{L}f(t)\sin\Big(\frac{2\pi n}{L}t\Big)\, dt\tag 6
\end{align}
Eq. $(1)-(2)$ don't have the extra factor of 2, why?
Can we find $(5)-(6)$ by changing the limits $[-L/2,L/2]=[0,L]$ in $(3)-(4)$?
Comment: L is typically T/2, where T is the time period. I suspect (3), (4) should have T not L. Then (1),(2) and (3),(4) would be the same thing. (5) and (6) apply when $f(t)$ is even or odd respectively (though (5) should include $b_n = 0$ and (6) should include $a_n = 0$). The 2 should not be inside the sin or cos though so they are wrong as written.
Answer: Context is all. In the case of Fourier series there are several variations depending on the context. We assume we have a function $f(t)$ with period $T$. The Fourier series coefficients depend on the values of $f(t)$ on an interval of length $T$. In the case of book 1, $T=2L$ and the interval is $[-L,L]$. For the other two books, $T=L$. For book 2 the interval is $[-L/2,L/2]$ and for book 3 $[0,L]$. The common factor for all the integrals is $2/T.$ Expressing that in terms of $L$ yields some variations.


HTML5  does not load

Question: I'm creating a webpage that is using HTML5 for videos. I tried one video, and it loaded and played successfully. But then, the other video does not even load. How can I fix this? The code is the same for the  working video and the not working video
<video src="SnakeVids/sukyandaru.mp4" width="350" height="300" controls="controls" type="video/mp4"></video>

Btw, the difference is that the first video is a .mp4, and the other one I converted from .flv to .mp4.
Comment: what browser did you test this in?
Comment: As @EduardGamonal said - in which browser are you testing your video? Also: Does the browser play the video, when you enter the URL directly into the address bar?
Comment: i'm testing it on google chrome . and @insertusernamehere, it does not even play .
Comment: In that case it seems that the file is corrupt or the URL is wrong.
Comment: how about the codecs you used when you converted flv to mp4? the video tag doesn't support all codecs, although chrome has support for mp4 and firefox doesn't.
Comment: the file plays when i play it on a media player(vlc, windows media player). does it have something to do with renaming ? i renamed the second file .
Comment: you mean that the name of the file doesn't match the `src` attribute?
Comment: in the src, i used the name that it is currently renamed .
Answer: After reading the comments, it looks like your video was converted into a format that is not compatible with Google Chrome. MP4 supports some codecs but only a small subset is widely supported, and Chrome supports these video formats for the <video> tag.
You should encode your video using a supported codec.
Additionally, you might want to provide different sources for compatibility with other browsers and platforms.ogg is a safe choice. A simplified example extracted from w3schools:
<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

You can also use third-party libraries, like videoJS, that will help you with video formats support. Some of them even have a flash fallback.

HTML5  does not load


Azure Functions node PM 4 doesn't detect my functions

Question: I just switched my existing project to the new programming model v4 using this migration guide. I love the idea that I can structure my directories and files as I want, but it doesn't seem to work.
My folder structure (src is in the root of the function project, alongside dist):
src
+---functions
|   +---criteria
|   |   |   create.ts
|   |   |   getall.ts
|   |   |   getone.ts
|   |   |
|   |   \---types
|   |           createCriteria.dto.ts
|   |
|   +---events
|   |       getall.ts
|   |
|   \---ratings
|       |   create.ts
|       |   getcriteria.ts
|       |   rateone.ts
|       |
|       \---types
|               createRating.dto.ts
|
\---lib ...

The main property in package.json (and yes, there is an src directory inside dist):
"main": "dist/src/functions/**/*.js"

However, when I start the app locally, I get the following warning:
"No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.)."

My function files all look simething like this...
import { HttpRequest, HttpResponseInit, InvocationContext, app } from '@azure/functions'

export const getCriteria = async (req: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> => {
  ...
  return { body: ... }
}

app.http('ratings-getcriteria', {
  methods: ['GET'],
  route: 'ratings/{id}',
  handler: getCriteria
})

What am I missing?
I also tried creating a function in src/functions and using the same glob patter as in the tutorial (dist/src/functions/*.js), but that didn't work either.
Answer: The problem was that Azure Functions Core Tools was too old on my machine. Programming model v4 requires v4.0.5095 or newer.


Compare $L^1$ and $L^2$ metrics on $C[0 ,1]$

Question: $d_2$ = $\sqrt{\int_{0}^{1}|f(x) - g(x)|^2}$ is a metric on $C[0 ,1]$ and  $d_1 =\int_{0}^{1}|f(x) - g(x)|$.
Now let's consider two metric spaces one is $X_1$ = $(X, d_1)$ and another one is $X_2$ = $(X, d_2)$ where $X = C[0 , 1]$
Now my question is whether $X_1$ and $X_2$ are homeomorphic or not. I know $d_1$ and $d_2$ have to be equivalent. But how can I prove or disprove. Can anyone help me out to find whether identity functions, one from $X_1$ to $X_2$ and another from $X_2$ to $X_1$ are continuous or not.
Thank You
Comment: May be Cauchy Schwarz inequality should help you get the equivalence you are looking for
Comment: What is $X?\,\,$
Comment: how?? Can u plzz firstname.lastname@example.com
Comment: Why do you say "I know $d_1$ and $d_2$ have to be equivalent."?
Comment: I meant $d_1$ and $d_2$ have to be equivalent to be homeomorhism
Comment: That's false for general homeomorphisms
Comment: how can u plzz explain? @zhw
Comment: $\mathbb R$ with its usual metric, and $\mathbb R$ with the metric $d(a,b) = |a-b|/(1+|a-b|).$
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/59940/discussion-between-cmi-and-zhw).
Comment: I don't do chat, sorry.
Comment: okk..so what happened? they are equivalent and id maps are continuous..Are not they?

????????????

where r u?? I am too curious to know.. I may have a big misconception...
Comment: They are homeomorphic, but not using the identity map.
Answer: Let $f_n(x) = \sqrt n x^n.$ Then $f_n \to 0$ in $(X,d_1)$ but not in $(X,d_2).$
Comment: @cmi Of course there exists a continuous function from $X_2$ to $X_1.$ A constant function for example.
Comment: So there does not exist any continuous function from $X_1$ to $X_2$...what about $X_2$ to $X_1$ @zhw
Comment: sorry...@Demophilus 'S last example prove that  identity map from $X_2$ to $X_1$ is not continuous.... Am I wrong?
Comment: No, the identity going from $X_2$ to $X_1$ is t continuous. My example above shows the identity going from $X_1$ to $X_2$ is not continuous.
Comment: t continuous??@zhw
Comment: The t was a typo. Pretend it's not there.
Comment: $$
f_n = \left\{ \begin{matrix} 0 & \text{ if } x > 1/n^2 \\
n-xn^3 & \text{ if } x \leq 1/n^2 \end{matrix}\right.$$ take this sequence...then it will converge in$X_2$ but not in $X_1$..Is not it?
Comment: I'm done here. I've given you a very simple example. If you have questions on the answer of @Demophilus, then you should ask Demophilus.
Comment: no no u did not tell me why the identity map from $X_2$ to $X_1$  not continuous?
Answer: Note that $d_2$ metric comes from the inner product
$$
\langle f, g \rangle = \int_0^1 f(x) \overline{ g(x)} dx.
$$
So you can apply the Cauchy-Schwarz inequality to
$$
\int_0^1 \lvert f(x) \rvert dx = \langle \lvert f \rvert, \chi_{[0,1]} \rangle,
$$
to find the first inequality.
But do you think another inequality $\lVert f \rVert_2 \leq \alpha \lVert f \rVert_1$ will hold for some $\alpha> 0$? Consider for example
$$
f_n = \left\{ \begin{matrix} 0 & \text{ if } x > 1/n^2 \\
n-xn^3 & \text{ if } x \leq 1/n^2 \end{matrix}\right.
$$
Will this converge to zero in both topologies?
Comment: I thought I already was being very elaborate. Simply apply the Cauchy-Schwarz inequality to $\langle \lvert f \rvert, \chi_{[0,1]} \rangle$ and you will find it.
Comment: WHAT IS first inequality? Can u plzzz elaborate little bit.. It is so short for a first reader..@Demophilus
Comment: Can u plzz clearly mention how the identity map from $X_2$ to $X_1$ is not continuous.......


What are alternatives to malloc() in C?

Question: I am writing C for an MPC 555 board and need to figure out how to allocate dynamic memory without using malloc.
Comment: @dmckee: Are suggesting malloc does not manufacture memory from the elements in the vicinity of the CPU?
Comment: @GregS: I remember in Win16/DOS times some compilers supported so called *FAR* pointers, which allowed `malloc` to manufacture memory from elements located quite far from the CPU. I wich you could see what it once did to my power supply!
Comment: `malloc` is not magic, it is just the conventional name for the dynamic memory manager in c and or unix.
Comment: @GregS: Well, at least not until glibc13 is released.
Comment: @AndreyT: what happened to the power supply?
Comment: It might be helpful to provide a few more details: what kind of dynamic memory management system are you looking for? Are you looking to download something already working, or are you looking for ways of creating your own system? etc...
Comment: Maybe he can't use malloc because of the specialized compiler/IDE. There are many variations on C. Some people call their product C because it appears that way in convention but the syntax and library functions are sometimes different
Comment: Unless and until you explain what features you need of an allocator that malloc() does not provide, or why you cannot use malloc(), there is little likelihood of getting a useful answer other than luck that someone else's necessary assumption matches your requirements.
Answer: Typically malloc() is implemented on Unix using sbrk() or mmap().  (If you use the latter, you want to use the MAP_ANON flag.)
If you're targetting Windows, VirtualAlloc may help.  (More or less functionally equivalent to anonymous mmap().)
Update: Didn't realize you weren't running under a full OS, I somehow got the impression instead that this might be a homework assignment running on top of a Unix system or something...
If you are doing embedded work and you don't have a malloc(), I think you should find some memory range that it's OK for you to write on, and write your own malloc().  Or take someone else's.
Pretty much the standard one that everybody borrows from was written by Doug Lea at SUNY Oswego.  For example glibc's malloc is based on this.  See: malloc.c, malloc.h.
Comment: I get the vibe from the question that @patrick isn't using a full-fledged OS, or memory allocation would already be working for him.
Comment: In that case, you'd be looking at statically allocating a huge buffer and managing that yourself.
Comment: Good observation, Carl.  I put a  around my old answer and wrote a different suggestion.
Comment: dlmalloc assumes a POSIX operating system environment, specifically, by making calls to sbrk() and mmap().  It is unclear whether the OP may utilize an sbrk() function.  The absence of malloc implies the possibility that sbrk() is disallowed.
Comment: @Heath Hunnicutt - It's been a while since I've looked at it, but IIRC dlmalloc has comments that say something along the lines of, "rewrite this part to provide `morecore` type functionality".  Doing this is probably simpler than writing a new malloc.
Comment: @asveikau - Doing so probably would be simpler than writing a new malloc.  There are other alternatives, such as not implementing malloc(), but rather a dynamic allocator suitable for his purpose and yet not conformant to malloc() API.  If dlmalloc were a 'drop in' solution, that would solve his problem.  Depending on his requirements, which OP hasn't fully explained, dlmalloc might be good enough.
Answer: You might want to check out Ralph Hempel's Embedded Memory Manager.
Answer: If your runtime doesn't support malloc, you can find an open source malloc and tweak it to manage a chunk of memory yourself.
Answer: malloc() is an abstraction that is use to allow C programs to allocate memory without having to understand details about how memory is actually allocated from the operating system.  If you can't use malloc, then you have no choice other than to use whatever facilities for memory allocation that are provided by your operating system.
If you have no operating system, then you must have full control over the layout of memory.  At that point for simple systems the easiest solution is to just make everything static and/or global, for more complex systems, you will want to reserve some portion of memory for a heap allocator and then write (or borrow) some code that use that memory to implement malloc.
Answer: You should explain why you can't use malloc(), as there might be different solutions for different reasons, and there are several reasons why it might be forbidden or unavailable on small/embedded systems:

concern over memory fragmentation.  In this case a set of routines that allocate fixed size memory blocks for one or more pools of memory might be the solution.
the runtime doesn't provide a malloc() - I think most modern toolsets for embedded systems do provide some way to link in a malloc() implementation, but maybe you're using one that doesn't for whatever reason.  In that case, using Doug Lea's public domain malloc might be a good choice, but it might be too large for your system (I'm not familiar with the MPC 555 off the top of my head).  If that's the case, a very simple, custom malloc() facility might be in order.  It's not too hard to write, but make sure you unit test the hell out of uit because it's also easy to get details wrong.  For example, I have a set of very small routines that use a brain dead memory allocation strategy using blocks on a free list (the allocator can be compile-time configured for first, best or last fit).  I give it an array of char at initialization, and subsequent allocation calls will split free blocks as necessary. It's nowhere near as sophisticated as Lea's malloc(), but it's pretty dang small so for simple uses it'll do the trick.
many embedded projects forbid the use of dynamic memory allocation - in this case, you have to live with statically allocated structures
Comment: Doug Lea's public domain malloc, used in Linux, assuems a POSIX operating system environment.  Specifically, dlmalloc makes calls to sbrk() and mmap().  It is unclear whether the OP may utilize an sbrk() function.
Comment: dlmalloc is included in newlib which runs on quite a few platforms, including at least MMU-less OS-less ARM.  It doesn't need mmap, but at least with newlib you provide your own sbrk, as in this project: https://github.com/elua/elua/blob/master/src/newlib/stubs.c  and discussed here: http://www.eetimes.com/discussion/guest-editor/4023922/Embedding-GNU-Newlib-Part-2
Answer: An answer really depends on why you might need to dynamically allocate memory.  What is the system doing that it needs to allocate memory yet cannot use a static buffer?  The answer to that question will guide your requirements in managing memory.  From there, you can determine which data structure you want to use to manage your memory.
For example, a friend of mine wrote a thing like a video game, which rendered video in scan-lines to the screen.  That team determined that memory would be allocated for each scan-line, but there was a specific limit to how many bytes that could be for any given scene.  After rendering each scan-line, all the temporary objects allocated during that rendering were freed.
To avoid the possibility of memory leaks and for performance reasons (this was in the 90's and computers were slower then), they took the following approach:  They pre-allocated a buffer which was large enough to satisfy all the allocations for a scan-line, according to the scene parameters which determined the maximum size needed.  At the beginning of each scan-line, a global pointer was set to the beginning of the scan line.  As each object was allocated from this buffer, the global pointer value was returned, and the pointer was advanced to the next machine-word-aligned position following the allocated amount of bytes.  (This alignment padding was including in the original calculation of buffer size, and in the 90's was four bytes but should now be 16 bytes on some machinery.)  At the end of each scan-line, the global pointer was reset to the beginning of the buffer.
In "debug" builds, there were two scan buffers, which were protected using virtual memory protection during alternating scan lines.  This method detects stale pointers being used from one scan-line to the next.
The buffer of scan-line memory may be called a "pool" or "arena" depending on whome you ask.  The relevant detail is that this is a very simple data structure which manages memory for a certain task.  It is not a general memory manager (or, properly, "free store implementation") such as malloc, which might be what you are asking for.
Your application may require a different data structure to keep track of your free storage.  What is your application?
Answer: Write your own.   Since your allocator will probably be specialized to a few types of objects, I recommend the Quick Fit scheme developed by Bill Wulf and Charles Weinstock.  (I have not been able to find a free copy of this paper, but many people have access to the ACM digital library.)  The paper is short, easy to read, and well suited to your problem.
If you turn out to need a more general allocator, the best guide I have found on the topic of programming on machines with fixed memory is Donald Knuth's book The Art of Computer Programming, Volume 1.  If you want examples, you can find good ones in Don's epic book-length treatment of the source code of TeX, TeX: The Program.
Finally, the undergraduate textbook by Bryant and O'Hallaron is rather expensive, but it goes through the implementation of malloc in excruciating detail.
Comment: I am confused by the link you posted.  The code there seems to wrap malloc(), calloc() functions.
Comment: @Heath: I was the one confused.  In fact, total brain cramp.  I was thinking of something else Hanson had written that did not make it into the book.
Answer: Write your own. Preallocate a big chunk of static RAM, then write some functions to grab and release chunks of it. That's the spirit of what malloc() does, except that it asks the OS to allocate and deallocate memory pages dynamically.
There are a multitude of ways of keeping track of what is allocated and what is not (bitmaps, used/free linked lists, binary trees, etc.). You should be able to find many references with a few choice Google searches.
Answer: malloc() and its related functions are the only game in town.  You can, of course, roll your own memory management system in whatever way you choose.
Answer: If there are issues allocating dynamic memory from the heap, you can try allocating memory from the stack using alloca(). The usual caveats apply:

The memory is gone when you return.
The amount of memory you can allocate is dependent on the maximum size of your stack.
Answer: You might be interested in: liballoc
It's a simple, easy-to-implement malloc/free/calloc/realloc replacement which works.
If you know beforehand or can figure out the available memory regions on your device, you can also use their libbmmm to manage these large memory blocks and provide a backing-store for liballoc. They are BSD licensed and free.
Comment: liballoc states that it requires a "standard UNIX environment" which it seems the OP does not have.  I imagine liballoc calls sbrk() and mmap().
Comment: liballoc doesn't require much. It requires a way to allocate pages of memory(*very* trivial to implement a page manager). mmap and sbrk has nothing to do with it.
Answer: FreeRTOS contains 3 examples implementations of memory allocation (including malloc()) to achieve different optimizations and use cases appropriate for small embedded systems (AVR, ARM, etc).  See the FreeRTOS manual for more information.
I don't see a port for the MPC555, but it shouldn't be difficult to adapt the code to your needs.
Answer: If the library supplied with your compiler does not provide malloc, then it probably has no concept of a heap.
A heap (at least in an OS-less system) is simply an area of memory reserved for dynamic memory allocation.  You can reserve such an area simply by creating a suitably sized statically allocated array and then providing an interface to provide contiguous chunks of this array on demand and to manage chunks in use and returned to the heap.
A somewhat neater method is to have the linker allocate the heap from whatever memory remains after stack and static memory allocation.  That way the heap is always automatically as large as it possibly can be, allowing you to use all available memory simply.  This will require modification of the application's linker script.  Linker scripts are specific to the particular toolchain, and invariable somewhat arcane.
K&R included a simple implementation of malloc for example.

What are alternatives to malloc() in C?


How do I render content "as is" from custom controller

Question: I've created a custom controller that pulls content from another node (the body). That content is defined in the node as Raw HTML.
  public function page(Request $request): array {

    $nid = $request->attributes->get('_nid');
    $node_storage = $this->entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);
    $content = $node->get('field_content')->value;

    // Load Entity using passed NID from key.
    $build = $content;
    // Return new Response($build);
    $render_array['snippet'] = [
      '#theme' => 'webpart_snippet',
      '#content' => $build,
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    return $render_array;

  }

I would like to render that content as if it were a native Symfony response. (e.g., correctly parse and HTML tags AND scripts)
In the node that I'm pulling in, I have, for example

This is text

and that is exactly what is showing on the page
It should be
This is text
I have defined a custom theme as well as twig template
/**
 * Implements hook_theme().
 * Declare a new theme
 */
function custom_webpart_snippet_theme() {
  return [
    'webpart_snippet' => [
      'variables' => [
        'content' => '',
      ],
    ],
  ];
}

Comment: Could you not skip the theme hook and twig, and simply do `#type => markup, #markup => $build` ?
Comment: What is `$render_array['snippet']`? Shouldnt it just be $render_array['content'] and some renderable arrays?
Answer: Since this is a text area field, you need to specify a type of render element, processed_text.
$render_array['snippet'] = [
  '#theme' => 'webpart_snippet',
  '#type' => 'processed_text',
  '#text' => $node->field_content->value,
  '#format' => $node->field_content->format,
  '#prefix' => '
',
  '#suffix' => '
',
];

Comment: it contains `` elements?  I can't think offhand why, if an `` is now being interpreted as a heading and not quoted/escaped as markup, a script tag would behave any differently.  I would expect it to work (yucky as it is).  Not sure what else to suggest without setting up a whole environment to replicate your data etc, I'm afraid.  Maybe drupal has some safety mechanisms I'm not aware.  Actually, come to think of it, are you sure the script tags survive into `$build` and are not being filtered by field text format settings?  No, wait, they must do if you see it displayed
Comment: @stevekeiretsu I tried that and it gets me very close. The problem that still remains with that is that the node contains javascript (yup, I know - bad idea, but I have to work with it for now).  So... the remaining issue is that the javascript simply gets displayed (rather than being executed)...

So - what now?
Comment: @sea26.2 is your field's format set to full html? You could try hard coding it, `'#format' => 'full_html',`
Comment: @NoSssweat It is set to Raw HTML.
Comment: @stevekeiretsu You're right about Drupal Safety mechanism. According to api.drupal.org "#markup: (string) During rendering, this will be set to the HTML markup output. It can also be set on input, as a fallback if there is no theming for the element. This will be filtered for XSS problems during rendering; see also #plain_text and #allowed_tags."
Comment: Ah makes sense.  Well I suppose you could bypass drupal by doing something like `return new Response()->setContent($build)` but then you would be losing the whole drupal page template / theme / caching etc unless you reimplemented loads of it.
Answer: The problem was in the template (twig)
Simply the raw filter
see doc description here
Non-working code

{{ content }}

Working code

{{ content | raw }}

Comment: Since it contains user entered text maybe escape it fist for security reasons. See https://drupal.stackexchange.com/a/290957/15055. `{{ content | escape | raw }}`.
Comment: Nice to know you found a solution. Although, I will say that it's not best practice to have scripts on your field. Ideally, you should include the script via a library.
Comment: @NoSssweat Thanks!  And I agree. It is actually a really bad idea to put scripts inline within a field.  It wasn't my idea and I didn't do it :)


How to filter out file names from a .File.Glob in a Helm Chart

Question: I have the following snippet in a helm library which is supposed to add in all the files in a folder into a ConfigMap except for those ending in .tz.
{{- /*
  add the contents of every file in the config folder of this IOC helm chart
  into the config map - this must include start.sh the startup script.
  The files must be text only. Any files ending in .tz are explicitly ommitted
*/ -}}

{{ (.Files.Glob "config/*[!.tz]").AsConfig | indent 2 }}
  version.txt: |
    IOC {{ .Release.Name }} version {{ .Chart.AppVersion }}

This does not quite work in that it filters out all files ending in . or t or z.
I cant see how to do this with Go globbing. I also cannot work out the syntax for using 'without' for the list created by .Files.Glob.
Can anyone enlighten me? Thanks!
Answer: Thanks @David Maze. This almost worked but the reference to .Files.Get failed and I think that is because the . context becomes the range counter within the range loop.
Adding $ to .Files within the loop got it working.
Also to fully replicate AsConfig I needed to extract the basename from
the path which I did by adding regexReplaceAll.
data:
{{- range $path, $_ := .Files.Glob "config/*" }}
{{- if not (hasSuffix ".tz" $path) }}
  {{ regexReplaceAll "(.*)/" $path "" }}: |
{{ $.Files.Get $path | indent 4 }}
{{- end }}
{{- end }}

Answer: The Helm documentation references the Go "github.com/gobwas/glob" package for the supported glob syntax; that doesn't support any sort of "except" cases, except for single characters.
What you can do instead is iterate over all of the files, and then use a normal conditional to exclude the ones you don't want.  You have to construct the ConfigMap structure yourself rather than relying on the AsConfig helper.
data:
{{- range $path, $_ := .Files.Glob "config/*" }}
{{- if not (hasSuffix ".tz" $path) }}
  {{ $path }}: |
{{ .Files.Get $path | indent 4 }}
{{- end }}
{{- end }}


how to handle exception in angularjs

Question: I have an angular application. It has n controllers. I know about $exceptionHandler. This is custom expception handler.
'use strict';

angular.module('exceptionHandlingApp')
.config(function($provide) {
$provide.decorator('$exceptionHandler', ['$log', '$delegate',
  function($log, $delegate) {
    return function(exception, cause) {
      $log.debug('Default exception handler.');
      $delegate(exception, cause);
    };
  }
]);
});

Controller
 app.controller('cust1Controller',function($scope,$exceptionHandler)
 {
    //ajax request or anything
 }

 app.controller('cust2Controller',function($scope,$exceptionHandler)
 {
    //ajax request or anything
 }

If any exception occurs in any of the controller, how do I call my custom handler?
Comment: If you write `throw 'error'` in any controller. does it not go to the custom handler?
Comment: A [demo here](http://jsfiddle.net/stever/pypdm/);
Comment: @YinGang, that I know. It is throwing error manually by using throw statement.
Comment: @mJunaidSalaat, if I use throw it throws exception irrespective of the exception occurence, Its like throwing exception manually
Answer: You shouldn't call the handler of an exception. It is called automatically by AngularJS.
To make sure, you can use debugger keyword. Let me show an example.
angular
    .module("app")
    .config(logExceptionToAPIServer);

function logExceptionToAPIServer($provide) {
    $provide.decorator("$exceptionHandler", ["$delegate",
        function ($delegate) {
            return function (exception, cause) {
                debugger;
                var http = angular.injector(['ng']).get('$http');
                debugger;
                var request = {
                    Message: exception.message,
                    StackTrace: exception.stack
                };
                http.post('yourAddress//', request);
                $delegate(exception, cause);
            };
        }
    ]);
};

how to handle exception in angularjs


How to change string of ^ type to char* type in vc++ CLR window application?

Question: I'm working on a vc++ CLR window application.In this application when I browse the local file system for file selection, the input file path is coming in string^ type ...now I want to change this ^ type to char* type. Help me. Thank you.
Answer: You probably want Marshal::StringToHGlobalAnsi
<code>IntPtr p = Marshal::StringToHGlobalAnsi(managedString);
char* c = (char*)p.ToPointer();
...
Marshal::FreeHGlobal(p);
</code>
See msdn for more.


Function holomorphic in the neighb. of zero, bounded by exponent is equal 0

Question: I want to prove that if $f$ is a holomorphic function in a neighbourhood of $0$ and $|f(\frac{1}{n})| \le \frac{1}{e^n}$ for $n$ sufficiently big, then $f =0$.
I know that if $f$ is holomorphic in a neighb. of zero, then it has the form $f(\frac{1}{x}) = \sum _{n=0} ^{\infty} \frac{f^{(n)} (0)}{n! x^n}$
$$
\mathrm{e}^{-x} = 1-x + \frac{x^2}{2} - \frac{x^3}{6} +\cdots
= \sum_{n=0} ^{\infty} \frac{(-1)^n x^n} {n!}$$
I thought I could use the identity principle which says that if $f,g \in \mathcal{O}(\Omega), \ f=g $ on $A \subset \Omega$ s.t. $A' \cap \Omega \neq \emptyset$, then $f=g$ on $\Omega$, but I have trouble determining the set $A$ in this case.
Could you help me a bit?
Comment: Try showing that $f^{(n)}(0) = 0$ for all $n$.
Comment: I don't think the identity principle can directly be used to prove this, as you are trying to do.
Comment: So I should prove that $|f|$ has a local maximum in the neighb. of zero?
Answer: As $f$ is continuous at $z=0$, and
$$
\left|\,\,f\left(\frac{1}{n}\right)\,\right|\le \frac{1}{\mathrm{e}^n},
$$
then $\,f(0)=\lim_{n\to\infty} f\big(\frac{1}{n}\big)=0$. If we assume that $f\not\equiv 0$, then $f$ is expressed as
$$
f(z)=z^mg(z),
$$
where $m$ is a positive integer and $g$ an entire function with $g(0)\ne 0$.
But then we would have that
$$
\left|\,\,f\left(\frac{1}{n}\right)\,\right|=\frac{1}{n^m}\left|\,g\left(\frac{1}{n}\right)\,\right|\le \frac{1}{\mathrm{e}^n},
$$
and hence
$$
\left|\,g\left(\frac{1}{n}\right)\,\right|\le \frac{n^m}{\mathrm{e}^n},
$$
which means that $\,\lim_{n\to\infty} g\big(\frac{1}{n}\big)=0$, and as $g$ is continuous at $z=0$, then $g(0)=0$, which is a contradiction.
Thus $f\equiv 0$.
Comment: Yes. Thanks. I have corrected it.


Footer styling not being applied for footer

Question: I am trying to add a footer to my page exactly as they do here. I am using a div with the same class defined for it but it still will not show the footer at the bottom. What am I missing here. Thank you. Full code at this codepen.

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: red;
   color: white;
   text-align: center;
}

Footer

Comment: works fine for me in this snippet. There is nothing wrong. to pin down the error, you should include all of your code.
Comment: Please create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) via the code snippet function.
Comment: Sorry but I didn't see any footer in your ``codepen.io`` link and if what I see their is a footer then its quite unique. Your code is not clean pls provide minimal reproducible example via code snippet here.
Answer: Placing your CSS styling right before:
$custom-file-text: (
    en: "Browse",
    es: "Elegir"
);

seems to achieve the desired effect. See here.


PowerShell Equivilent to Select-Object "-ExpandProperty" for Where-Object To Query Nested Objects

Question: I have the following code:
<code>$results = Invoke-RestMethod -Uri "XXX" -Credential $cred

$results.value | Where-Object releaseDefinition.name -eq "XYZ"
</code>
For some reason isn't not returning any results, when I run a equivilent "Select-Obejct" query on it, the issue becomes clear:
<code>$results.value | Select-Object releaseDefinition.name
</code>
All empty.. and google says I need to use the "-ExpandProperty" tag to do this:
<code>$results.value | Select-Object releaseDefinition -ExpandProperty name
</code>
So I try to do the same for my "Where-Object" statement:
<code>$results.value | Where-Object releaseDefinition -ExpandProperty name -eq "XYZ"
</code>
and it error's... Because that property doesn't exist. So I need to find a different way to accomplish this task, how can I accomplish the code above without using this parameter? Also why does this parameter exist on the select and not on the where clause?
Comment: The [`Select-Object`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7) cmdlet selects specified **properties** of an object or set of objects.
The [`Where-Object`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-7) cmdlet selects **objects** that have particular property values from the collection of objects that are passed to it. I guess `releaseDefinition` is an embedded object. Please, add a (sample) of the input object (`$Result | ConvertTo-Json`) to the question.
Answer: I found a bit of a workaround, if you wrap you statement in parenthesis and reference the base element($_) you can access element at any level of the object:
<code>$results = Invoke-RestMethod -Uri "XXX" -Credential $cred

$results.value | Where-Object { $_.releaseDefinition.name -eq "XYZ" }
</code>
Comment: Thanks for this example David. The example seems to currently be missing parenthesis.


Border color of margin instead of element

Question: Can I style the border of the margin box instead of the element box itself?
Example:
|-------------------------------|
|                               |
|    |--------------------|     |
|    |                    |     |
|    |---box-color: red---|     |
|                               |
|---margin-border-color: blue---|

Comment: Margins, Padding and borders in one illustration: http://www.w3.org/TR/CSS2/images/boxdim.png. **EDIT:** While you can't have a border on the "margin box" you can wrap it with another `div` and set a border. **BTW**, consider adding a jsfiddle.
Comment: dont think so, use padding instead
Comment: @Tasos the problem is that I can't do `padding: auto;` instead of `margin: auto;`, which I'm using to center the content of the box element.
Comment: It's really not clear what you are trying to do...a better explanation would be required. It's sounds to me more like you should be coloring the background of the **parent** rather than the element itself.
Comment: @Ofir Baruch: If the OP were able to create a working fiddle then they'd have answered their own question. It's pretty obvious why the OP chose to use ASCII art rather than a fiddle to illustrate their desired result.
Comment: @alexandernst, can you please provide a feedback regarding the provided answers? Is there a good answer that works for you or not?
Comment: @OfirBaruch Sorry, was AFK for a moment. The content of the box doesn't occupy the entire height/width of the box so I can't do the bg color trick. Anyways, I might do it with a nested box that would then hold all the elements.
Answer: You should use padding if you need something like that.
For example:

         some text here

And then you can use border-color - which will work as normal border. And also padding on the element - to get the same effect. Like this.
.box {
   padding: 10px;
   border: 1px solid #ccc;
}

If you want to center that element - then it is different question.
You can use some other method to center element. Like this:
.box-around {
    text-align: center;
}
.box {
    display: inline-block;
}

JsFiddle added: http://jsfiddle.net/zqr8113y/
Comment: The problem is that I can't do padding: auto; instead of margin: auto;, which I'm using to center the content of the box element
Comment: I updated my answer - it includes explanation how to center that box.
Comment: @alexandernst there is also jsfiddle now attached to the answer
Answer: You may also use pseudo elements:
.borders {
  position: relative;
  border: 5px solid #f00;
}
.borders:before {
  content: " ";
  position: absolute;
  z-index: -1;
  top: 5px;
  left: 5px;
  right: 5px;
  bottom: 5px;
  border: 5px solid #ffea00;
}

look here for more detail
Comment: This might work, I need to try it. Will provide feedback after done testing.
Answer: AFAIK, margin has no border. If you want to set border to the outside box since you want to use margin: 0 auto, you need to wrap your element and add border to the parent element. Example:

.wrapper {
  width: 100%;
  border: 1px solid blue;
  padding: 10px;
  box-sizing: border-box;
}
.inner {
  width: 200px;
  background: red;
  margin: 0 auto;
  text-align: center;
}

Lorem ipsum dolor

Comment: This uses fixed height, which I can't use.
Comment: Whats the problem with fixed height?
Comment: The problem with fixed height is... well... the fixed height itself. Fixed values are useless most of the time; even more in this particular case as I don't know how high the content will be.


KarateDSL: Using proxy for UI automation, does not open url using that proxy

Question: I know the UI automation is in experimental state.
When I am trying to open an url using proxy, its not opening the right version of the URL. Is this isn't supported yet? Or is there anything I am missing?
<code>Background:
   * configure proxy = 'http://URL:PORT'
   * configure driver = { type: 'chrome', headless: false }
...

  Given driver <url>
  And driver.input("input[id=XYZ]", 'NAME')
...
</code>
Answer: Thanks for raising this, we have indeed missed this and opened an issue. Do try contribute ! https://github.com/intuit/karate/issues/924
Comment: I tried to use selenium-server to create a workaround for my job. When I am trying to call my java method from feature file I am getting the following error: Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V. Can you help me in resolving this, so that I can use my temporary solution to complete my task?
Comment: @ShafiqulKabir we don't support selenium server, sorry


Como executar um comando via proc_open e não aguardar o término da execução?

Question: Possuo um projeto Symfony2 que gera um PDF a partir de um HTML com o bundle KnpSnappyBundle, que tem como dependência o bundle KnpSnappy e que, por sua vez, faz a abstração com o executável wkhtmltopdf.
Esse binário é executado com os devidos parâmetros por meio da função proc_open do PHP conforme linha abaixo:
$process = proc_open($this->command, $descriptorspec, $pipes, null, $this->env);

Nos testes que fiz, notei que o processo fica preso ao processo do Apache. Logo, se o servidor estiver sobrecarregado, a resposta do Apache pode demorar muito, o que não é uma opção.
Trocar a função também ou a funcionalidade do bundle também não é uma opção. As únicas coisas que posso fazer são modificar os parâmetros da função proc_open de modo que o processo não fique preso ao Apache – isso se essa opção existir.
Alguém já fez algo do tipo ou conhece algum workaround?
Comment: Olha, já passei por esse problema também, um workaround que eu fiz na época, foi utilizar um proc_open em um SSH e executar o comando que eu desejava no SSH atribuindo o processo ao background, em seguida desconectando. Mas é uma gambiarra daquelas. Porém funciona, até porque eu estava levantando serviços e não dava pra deixar minha aplicação pendurada neles.
Comment: @GabrielGartz a solução que achei seria colocar um `&` ao final do comando, mas como processo de geração está bastante encapsulado, não tenho como fazer isso.
Comment: É o problema de usar o & no final, que vc roda em background mas o processo fica atrelado a quem o disparou, isso é, se você matar o processo do PHP (que tende a terminar no fim do script) ele vai parar o processo pendurado e se este não tiver terminado, vai ser cancelado.
Answer: Olá, eu tive um problema similar e resolvi utilizando um sistema de queue e colocando o script para rodar de forma assíncrona.
Dá uma olhada no Gearman e veja como é simples de utilizar: GearmanClient::doBackground
Comment: Realmente o Gearman resolve para alguns casos mas no meu caso específico eu preciso que funcione de acordo com os parâmetros que eu passar para o `proc_open`.


How to display an image in a Views RSS feed

Question: I am trying to display an image in a Views RSS feed.

I have added the following fields to my View: field_image,
field_title, field_twitter (These fields come from my node).
I then set all fields to "Exclude from display".
I then create a new field in Views called "RSS Content".
I then place tokens for all the fields (from step 1) into "RSS Content".
Finally, I go to "Views >> Show >> Settings". In the drop down menu for "Description field", I select "RSS Content".

When I look at my RSS feed, the image field is displayed like this:
    <description>
<img src="http://example.com/sites/files/nodes/content/images/intro/two-hearts-1312984-1280x960_0.jpg" />
</description>

How do I get the image to display properly, instead of the image tags being escaped?
Comment: In the view where you have set the fields not to display, what are the settings for the field? Is it displaying the file's URL or the image? Whichever one it is, try switching it.
Comment: @Ruby It was image. I tried file but it still escapes the  tag
Comment: Hmm. Well if it helps, on my main site we have set up the display of the RSS feed as a display on the content type. Then the view that generates the feed is in content mode using that display rather than specifying fields.
Comment: Please test with a RSS reader. Even if you see the escaped image html tag in the code preview of Views, the RSS reader should convert this code and display the image properly.
Answer: First add the Media RSS namespace to your views-view-rss.tpl.php
<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?> xmlns:media="http://search.yahoo.com/mrss/">

Then add the  tag to your views-view-row-rss.tpl.php
<media:content url="<?php print image_style_url('my_img_style_id', $node->field_image['und'][0]['uri']); ?>" type="image/jpeg" medium="image" height="800" width="600" lang="en" />

Lastly make the field data available to your theme's template
function mytheme_preprocess_views_view_row_rss(&$vars) {
  $view     = &$vars['view'];
  $options  = &$vars['options'];
  $item     = &$vars['row'];

  // Use the [id] of the returned results to determine the nid in [results]
  $result = &$vars['view']->result;
  $id   = &$vars['id'];
  $node   = node_load( $result[$id-1]->nid );
  $vars['node'] = $node;
}

Original article: https://blog.sam-thompson.info/images-in-drupal-rss-feed-without-additional-modules/
Answer: I have come across similar problems and somehow CDATA wrapping didn't work for me. I had to override the rss view and create the cdata tag and wrap image inside it programmatically.
I have done this by overriding the RSS view created by views_rss and views_data_export.
Here is how my view setup looks like:

To RSS via custom tpl display I created another display called as Feed which is a data export view of first display.
Here is how the feed display look like which I have overridden.

Next I overrode the Feed display tpl's and created the CDATA image field programmatically.
Here is the view tpl files that I overrode.

Now you would need to preprocess rss view in template to make node's nid available to the views.
Here is how I did that.

function bootstrap_preprocess_views_view_row_rss(&$vars) {
$view     = &$vars['view'];
$options  = &$vars['options'];
$item     = &$vars['row'];

// Use the [id] of the returned results to determine the nid in [results]
$result = &$vars['view']->result;
$id   = &$vars['id'];
$node   = node_load( $result[$id-1]->nid );

$vars['title'] = check_plain($item->title);
$vars['link'] = check_url($item->link);
$vars['description'] = check_plain($item->description);
//$vars['description'] = check_plain($node->teaser);
$vars['node'] = $node;
$vars['item_elements'] = empty($item->elements) ? '' :
format_xml_elements($item->elements);
}

Lastly here is how I created the CDATA tag programmatically with my custom image style.
Code for two view templates:
1. Display template
<?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces;
?>>
<channel>
<title><?php print $title; ?></title>
<link><?php print $link; ?></link>
<description><?php print $description; ?></description>
<language><?php print $langcode; ?></language>
<?php print $channel_elements; ?>
<?php print $items; ?>
</channel>
</rss>

Row template. Here I am creating CDATA and item tag programmatically.

Hope this helps.
Answer: In case someone is looking for a Drupal 9 version of this, here's the code considering your image field is named field_image and you want to use an image style which is called large in this case:
In your mytheme.theme:
use Drupal\node\Entity\Node;

function mytheme_preprocess_views_view_row_rss(&$variables) {
  if($variables['view']->id() == 'your_view_id'){
    $node = Node::load($variables['item_elements'][2]["value"]->__toString());
    $style = \Drupal\image\Entity\ImageStyle::load('large');
    $variables['media'] = $style->buildUrl($node->field_image->entity->getFileUri());
    $variables['media_size'] = $node->field_image->entity->getSize();
  }
}

Then in your Twig file views-view-row-rss.html.twig:
<item>
  <title>{{ title }}</title>
  <link>{{ link }}</link>
  <description>{{ description }}</description>
  {% for item in item_elements -%}
    <{{ item.key }}{{ item.attributes -}}
    {% if item.value -%}
      >{{ item.value }}</{{ item.key }}>
    {% else -%}
      {{ ' />' }}
    {% endif %}
  {%- endfor %}
  <media:content url="{{ media }}" fileSize="{{ media_size }}" type="image/jpeg" />
</item>

Answer: wrap it on CDATA  tags.
CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.


Help with UIPageControl and UIScrollView

Question: I need help with UIPageControl. In my application I've made an UISCrollView

Width: 640
Height: 300
Paging enabled
Horizontal Scroll Only

- (void)viewDidLoad
{
    [ScrollView setContentSize:CGRectMake (640, 300)];
    [super viewDidLoad];
}

I want UIPageControl to change the number of the page when the users scroll the view and surpass 320 pix, like in the iPhone Springboard.
Answer: Try this tutorial,
http://www.edumobile.org/iphone/iphone-programming-tutorials/pagecontrol-example-in-iphone/
Comment: Whilst this may theoretically answer the question, we would like you to include the essential parts of the linked article in your answer, and provide the [link for reference](http://meta.stackexchange.com/q/8259). Failing to do that leaves the answer at risk from link rot.


Significance and credibility intervals for interaction term in logistic regression

Question: I fitted a Bayesian logistic regression in WinBugs and it has an interaction term. Something like this:
$$\mathrm{Prob}(y_{i}=1) = \mathrm{logit}^{-1} (a + b_{1}*x_{i} + b_{2}*w_{i} + b_{3}*x_{i}*w_{i})$$
where $x$ is a standardized continuous variable, and $w$ is a dummy variable.
In reality the model is more complicated, but I wanna keep things simple.
It happens that the interaction term is "significant", but not the single predictors. For instance,
$\mathrm{mean}(b_{1}) = -.2$ and $95%$ quantile: $(-1.3$ and $.7)$
$\mathrm{mean}(b_{2}) = -.4$ and $95%$ quantile: $(-1.3$ and $.5)$
$\mathrm{mean}(b_{3}) = 1.4$ and $95%$ quantile: $(.4$ and $2.5)$
Do you guys have any advice on how to react to this finding? I thought that I could compute 95% credibility intervals for the whole effect of $x$ when $w=1$. This would be:
95% quantile for total effect of x, conditional on $w=1$: $(-1.3+.4$ and $.7+2.5) = (-.9 + 3.2)$
Is this correct? If not, what should I do?
Any references on the subject?
Answer: No, your calculation isn't correct, because:
a) $b_1$ and $b_3$ are probably correlated in the posterior distribution, and
b) even if they weren't, that isn't how you would calculate it (think of the law of large numbers).
But never fear, there is a really easy way to do this in WinBUGS. Just define a new variable:
b1b3 <- b1 + b3
and monitor its values.
EDIT:
For a better explanation of my first point, suppose the posterior has a joint multivariate normal distribution (it won't in this case, but it serves as a useful illustration). Then the parameter $b_i$ has distribution $N(\mu_i,\sigma_i^2)$, and so the 95% credible interval is $(\mu_i - 1.96 \sigma_i,\mu_i + 1.96 \sigma_i)$ - note that this only depends on the mean and variance.
Now $b_1+b_3$ will have distribution $N(\mu_1 + \mu_3,\sigma_1^2 + 2 \rho_{13}\sigma_1\sigma_3 + \sigma_3^2)$. Note that the variance term (and hence the 95% credible interval) involves the correlation term $\rho_{13}$ which cannot be found from the intervals for $b_1$ or $b_3$.
(My point about the law of large numbers was just that the standard deviations of the sum of 2 independent random variables is less than the sum of the standard deviations.)
As for how to implement it in WinBUGS, something like this is what I had in mind:
model {
  a ~ dXXXX
  b1 ~ dXXXX
  b2 ~ dXXXX
  b3 ~ dXXXX
  b1b3 <- b1 + b3

  for (i in 1:N) {
    logit(p[i]) <- a + b1*x[i] + b2*w[i] + b3*x[i]*w[i]
    y[i] ~ dbern(p[i])
  }
}

At each step of the sampler, the node b1b3 will be updated from b1 and b3. It doesn't need a prior as it is just a deterministic function of two other nodes.
Comment: I'm not sure I understand your commnet. If b1 and b3 are correlated, why does it matter? I  mean, their joint distribution has to characterized with some correlation parameter, but so what? I do have their marginal distributions. 2. I didn't understand you mention about the  the law of large numbers. Could you expand on it? Finally, are you sugesting that I should add b1 + b3 in the main loop? And I just need to use a vague prior to this new parameter? Thank you!
Answer: A few thoughts:
1) I'm not sure whether the fact that this is Bayesian matters.
2) I think your approach is correct
3) Interactions in logistic regression are tricky. I wrote about this in a paper that is about SAS PROC LOGISTIC, but the general idea holds.  That paper is on my blog and is available here
Comment: I agree that it's likely that bayesian or not doesn't matter. I just said it was Bayesian just in case it matters.
Answer: I'm currently having a similar problem. I also believe that the approach to calculate the total effect of w is correct. I believe this can be tested via
h0: b2 + b3 * mean(x) = 0;
ha: b2 + b3 * mean(x) != 0
However, I stumbled upon a paper by Ai/Norton, who claim that "the magnitude of the interaction effet in nonlinear models does not equal the marginal effect of the interaction term, can be of opposite sign, and its statistical significance is not calculated by standard software." (2003, p. 123)
So perhaps you should try to apply their formulas. (And if you understand how to do that, please tell me.)
PS. This seems to resemble the chow-test for logistic regressions. Alfred DeMaris (2004, p. 283) describes a test for this.
References:
Ai, Chunrong / Norton, Edward (2003): Interaction terms in logit and probit models, Economic Letters 80, p. 123–129
DeMaris, Alfred (2004): Regression with social data: modeling continuous and limited response variables. John Wiley & Sons, Inc., Hoboken NJ
Comment: Thanks for the reference. I'll take a look at it and will report here if I make any progress on the matter. Regarding your suggested test, I don't think it will do the job. Remember first that the interaction is two-way, from x with w and w with x. By this I mean that even if h0 is true, it's still possible that say h2: b1 + b2*mean(w) is not zero. Moreover, In general I know ahead of time that the null hipothesis is false, i.e., in general there is no such a thing as a zero effect. With a sufficient big sample I can find any effect to be significant.
Comment: And another point. Even if h0 and h2 are true, it's still possible that say h3: b2 + b3*(mean(x)+sd(x)) != 0. In other words, we should teste not only for the mean of x (or w), but for the whole distribution of values, since an interaction terma is a way to say that predictive effect vary by subgroups of predictors.
Comment: I don't fully understand what you mean. When testing whether or not b2 + b3 * mean (x) == 0, you always compare to some test statistic to determine whether the result is significantly different from zero, standard deviation of x is not the only relevant factor.
Comment: About what you said... I'm not sure if I fully understand you either.  In  any case, one of my points was: even if we fail to reject the null hypothesis that b2 + b3 * mean (x) == 0, it means only that we can't say that the average effect of W, conditional on average values of x, isn't zero. However, the whole point of an interaction term is because we want to condition the effect of W not only on the average x, but on the whole distritubion of x!
Comment: Alright. I see what you mean. (English isn't my first language either.) I believe what you wrote is true and it is also why Ai/Norton plot the interaction effect against the whole distribution of prob(x) – for some values of x, the interaction effect is positive, for some others it is not.

However, I believe that the fact that you calculate the effect of W, which is a dummy, might(?) make things easier, because it can be interpreted as chow-test, structural break, subpopulation etc. (Do you want to calculate the step-effect of w 0→1, or are you interested in the interaction effect?)


Android Textview setText inner Layout

Question: I want to settext like this
String Result = "Customer Name :"+getSpace()+CustomerName+System.getProperty ("line.separator")+
    "Customer Age :"+getSpace()+CustomerAge+System.getProperty ("line.separator")+
    "Money  :"+getSpace()+CustomerMoney+System.getProperty ("line.separator");
        ExampleTextView.setText(Result );

Function Code
public String getSpace(){

 String Space="";
 for(int i=0;i<getSpaceCount();i++)
 {
  Space+=" ";
 }

}

After than i want to result Like this
| <- is Layout border
|Customer Name :        Akshan Ormani To|
|Customer Age :                       19|
|Money :                           20.0€|

Answer: I guess you can use AlignmentSpan.Standard for this. I'm not sure though, didn't try it myself.
See here for an example

Android Textview setText inner Layout