Topology, locally-compact Hausdorff space

Question: I already asked this question here: locally-compact Hausdorff space, equivalent, compact, continuous
So if this repost is not apprechiated, please just delete this thread, but I would really like to get further help, since the question is not fully answered yet.
Let $X$ be a locally-compact Hausdorff space and $f\in C(X)$. Show that the following statements are equivalent:
a) For every $\epsilon>0$ is the set $\{x\in X:|f(x)|\geq\epsilon\}$ compact
b) The function $\overline{f}:X^+\to\mathbb{C}$ defined through $\overline{f}_{|X}=f$ and $\overline{f}(\infty)=0$ is continuous
"$\Rightarrow$"
The topology of the one-point compactification is defined through
$\tau^+:=\{U\subseteq X: U\quad\text{open}\}\cup\{U\cup\{\infty\}:U\subseteq X\quad\text{open}, U^c\quad\text{quasicompact}\}$
Since $X$ is Hausdorff quasicompact=compact for subsets of $X$. So the open neighbourhoods of $\infty$ are the complements of compact subsetes of $X$.
Let $U$ be an open neighbourhood of $\infty$.
Hence $U\subseteq X$ open and $U^c$ compact.
By assumption is for every $\epsilon>0$ the set $\{x\in X:|f(x)|\geq\epsilon\}$ compact. Therefor for every $x\in U^c$ and every $\epsilon>0$ is $|f(x)|\geq\epsilon$. Then for every $x\in U$ exists an $\epsilon'>0$ with $|f(x)|<\epsilon'$.
Let $\epsilon>0$ be given. I need to find a neighbourhood of $\infty$, such that $|\overline{f}(x)-\overline{f}(\infty)|<\epsilon$.
If $x=\infty$, then $|\overline{f}(\infty)-\overline{f}(\infty)|=0$ and there is nothing to show.
If $x\neq\infty$, then $|\overline{f}(x)-\overline{f}(\infty)|=|f(x)-0|=|f(x)|<\epsilon'$.
So I can now choose $\epsilon=\epsilon'$, and the proof is done.
This is what I got out of the linked thread, with the help of Daniel Fischer and  Luiz Cordeiro.
Have I converted their help right?
Thanks in advance.
Answer: There's a mistake at the very beginning: if $U$ is an open nbhd of $\infty$, $U$ is not a subset of $X$, though it is certainly true that $U\cap X$ is open in $X$ and that $X\setminus U$ is compact. The main problem, though, is that your argument is very badly organized and leaves out some important things. In particular, it's not enough to show that $\overline f$ is continuous at $\infty$: you have to show that it's continuous on all of $X^+$. Even if you just appeal to the continuity of $f$ (and you really should do a bit more than that, since there are a couple of details to be checked), your proof should at least mention this point.

Let $x_0\in X^+$; to show that $\overline f$ is continuous at $x_0$, for each $\epsilon>0$ I need to find an open nbhd $U_\epsilon$ of $x$ in $X^+$ such that $\left|\overline f(x)-\overline f(x_0)\right|<\epsilon$ for each $x\in U_\epsilon$.

Now you can split this into two cases, one for $x_0\in X$ and one for $x_0=\infty$. In each case you should explain how to get the desired $U_\epsilon$.

If $x_0\in X$, the continuity of $f$ ensures the existence of such a $U_\epsilon$. If $x_0=\infty$, let $$K_\epsilon=\{x\in X:|f(x)|\ge\epsilon\}\;;$$ by hypothesis $K_\epsilon$ is compact, so $X^+\setminus K_\epsilon$ is an open nbhd of $x_0=\infty$. Let $U_\epsilon=X^+\setminus K_\epsilon$, and suppose that $x\in U_\epsilon$. Then either $x=x_0=\infty$, in which case $$\left|\overline f(x)-\overline f(x_0)\right|=0<\epsilon\;,$$ or $x\in U_\epsilon\cap X=X\setminus K_\epsilon$, in which case $$\left|\overline f(x)-\overline f(x_0)\right|=\left|\overline f(x)\right|=|f(x)|<\epsilon\;.$$ Thus, $\left|\overline f(x)-\overline f(x_0)\right|<\epsilon$ for each $x\in U_\epsilon$, as desired.

Added: For the opposite implication, suppose that $\overline f$ is continuous, fix $\epsilon>0$, and let $K=\{x\in X:f(x)\ge\epsilon\}$; we want to show that $K$ is compact.
Let $B=\{z\in\Bbb C:|z|<\epsilon\}$, and let $U=\overline f^{-1}[B]$; since $\overline f$ is continuous, $U$ is open in $X^+$. Moreover, $\infty\in U$, since $\overline f(\infty)=0\in B$, so $U$ is an open nbhd of $\infty$ in $X^+$. By definition, then, $X\setminus U$ is compact in $X$, and
$$\begin{align*}
X\setminus U&=X^+\setminus U\\
&=\{x\in X^+:\overline f(x)\notin B\}\\
&=\{x\in X:f(x)\notin B\}\\
&=\{x\in X:|f(x)|\ge\epsilon\}\\
&=K\;,
\end{align*}$$
so $K$ is compact.
Comment: Do you have a hint to the other implication as well? Is my try false again?
Comment: @MrTopology: I've added that direction to my answer.
Answer: I am not very long a member to this site and I am not sure about every rule yet. I would like to discuss the other implication b) $\Rightarrow$ a) now, and would not like to do that in the "comment section", because the space is not enough.
Is this not apprechiated in general? I will adapt that in future question then.
b) $\Rightarrow$ a)
Let $\overline{f}:X^+\to\mathbb{C}$ with $\overline{f}_{|X}=f$ and $\overline{f}(\infty)=0$ be continuous.
I have to show, that for every $\epsilon>0$ the set $C_{\epsilon}:=\{x\in X:|f(x)|\geq\epsilon\}$ is compact.
Therefore that for every open cover of $C_{\epsilon}$ exists a finite subcover.
Let $V_\epsilon$ be an open cover of $f(C_{\epsilon})$. Hence $V_\epsilon\supseteq f(C_{\epsilon})$.
Since $f$ is continuous $f^{-1}(V_{\epsilon})\supseteq C_{\epsilon}$ is an open set.
Because $X$ is locally-compact, every point $x\in X$ has a compact neighbourhood $K_x\ni x$.
Hence there exist finite subcovers $U_x$ of $K_x$ for every $x\in f^{-1}(V_{\epsilon})$.
Therefore there exist indices $x_k$ with $k=1,...,n$ and
$\bigcup_{k=1}^n U_{x_k}\supseteq\bigcup_{x\in f^{-1}(V_{\epsilon})} K_x\supseteq f^{-1}(V_{\epsilon})\supseteq C_{\epsilon}$ is a finite supcover.
Thus $C_{\epsilon}$ is compact for every $\epsilon>0$
Comment: Could someone give a feedback to this try?
Comment: You've taken $V_\epsilon$ to be a single open set containing $f[C_\epsilon]$; an open *cover* of $f[C_\epsilon]$ can consist of any number of sets, and you'd need to show that only finitely many of those sets are needed in order to cover $f[C_\epsilon]$. I'll add a proof of this implication to my answer.


OOP and object parametrization

Question: I am supposed to develop a program, which will heavily depend on input data at runtime (data for initialization, read from XML) and I would like to ask for good OOP practice regarding object/architecture design.
Situation
I have the following objects, object_A, object_B, object_C, each of them has a specified objective.
object_A = evaluation of equations, requires input, produces output
object_B = evaluation of equations, requires input, produces output
object_C = requires data from object_A and object_B as input, produces output
Then there is object_D, which passes the data and calls functions among these objects_A/B/C.

There are 2 ways to tackle this situation that I know of :
a) Inheritance
object_D inherits from object_A, object_B, object_C. Data are passed by appointing appropriate structures in objects_A/_B/_C using "this->", virtual functions in objects_A/_B/_C can then call back to object_D.

hierarchical approach
objects are concealed
difficult to parametrize the object_A/_B/_C (parameters need to travel all the way up in the hierarchy to base classes)

b) Passing pointers
Create object_A/_B/_C, by passing parameters in constructor. Then pass pointers of these objects to constructor of object_D.

no information hiding, all objects are visible
hierarchy might be unclear, especially when there are more levels
easy to pass initialization parameters

Question
What is an appropriate way of handling software architecture, where many objects require passing initialization parameters at runtime?
Answer: I think your question is broad and can have more than one good answer. However, I think your scenario can be solved in one of two ways:

Eventing: Instead of tightly coupling your classes using inheritance, you can use events. For instance when Object A finishes processing it raise an event called 'ClassAFinished'. Then you have to create an event handler for ClassAFinish Event that will in turns pass objectA's output to other objects that rely on Object A output.

Second way is Chain of Responsibility design pattern. Since your question is related to OOP I think it's reasonable to use this design pattern. In a nutshell Chain of Responsibility is a design pattern that you use it when you have a series (chain) of objects, each of which will do specific processing (responsibility), but each one of them can't begin processing until it received data from the previous object. When it finishes processing it'll send its output to the next object and so forth.

These are 2 main ideas that I wanted to share with you.

OOP and object parametrization


How to find MLE for multinomial distribution and Expectation of X1 and X2

Question: There are 3 types of flowers that can grow from planting a seed.
$$P(\text{Daisy}) = \theta_1$$
$$P(\text{Rose}) = (1-\theta_1)\theta_2$$
$$P(\text{Sunflower}) = (1-\theta_1)(1-\theta_2)$$
The total number of flowers at the end is $n.$ If $X=(X_1, X_2, X_3)$ is the number of daisies, roses and sunflowers respectively, find the MLEs for $\theta_1$ & $\theta_2$ and $E[X_1]$ and $E[X_2]$ in term of the parameters $\theta_1$ & $\theta_2$.
I am aware that this is a multinomial distribution but I don't know how to go about finding the estimators for the parameters since there are 2 of them.
Comment: Are you able to write down the likelihood for a sample $X=\left(X_1, X_2, X_3\right)$ with $n=X_1+X_2+X_3$?
Comment: @assumednormal no:( I don't know how to do that
Comment: If this is self study, I would recommend adding the self study tag, and then reading the guidelines about submitting those types of questions.
Answer: If we're given that $X=\left(X_1,X_2,X_3\right)$ follows a multinomial distribution with parameters $\theta=\left(\theta_1,\left(1-\theta_1\right)\theta_2,\left(1-\theta_1\right)\left(1-\theta_2\right)\right)$, then the likelihood is
\begin{align*}
L\left(X; \theta\right) &\propto \theta_1^{X_1}\left(1-\theta_1\right)^{X_2}\theta_2^{X_2}\left(1-\theta_1\right)^{X_3}\left(1-\theta_2\right)^{X_3}\\
\end{align*}
The log-likelihood is then
\begin{align*}
\ell\left(X; \theta\right) &\approx X_1\log\left(\theta_1\right)+\left(X_2+X_3\right)\log\left(1-\theta_1\right)+X_2\log\left(\theta_2\right)+X_3\log\left(1-\theta_2\right)\\
\end{align*}
Taking derivatives gives
\begin{align*}
\frac{\partial \ell}{\partial \theta_1} &= \frac{X_1}{\theta_1}-\frac{X_2+X_3}{1-\theta_1}\\
\frac{\partial \ell}{\partial \theta_2} &= \frac{X_2}{\theta_2}-\frac{X_3}{1-\theta_2}\\
\end{align*}
Setting the derivatives to 0 and solving gives
\begin{align*}
\hat{\theta}_1 &= \frac{X_1}{X_1+X_2+X_3}\\
\hat{\theta}_2 &= \frac{X_2}{X_2+X_3}\\
\end{align*}


Infinite number of apples in a box

Question: Imagine I have an infinite source of numbered apples and a box of an infinite size. I take two apples from the source, put them in the box, then take one apple out:
Step $1$: apples $1$ and $2$ in - apple $1$ out
Step $2$: apples $3$ and $4$ in - apple $2$ out
Step $3$: apples $5$ and $6$ in - apple $3$ out
...
Step $N$: apples $(2N-1)$ and $2N$ in - apple $N$ out
...
With each step the number of apples $S$ in the box increases, so:
$$ \lim_{N\to\infty}S=\infty  $$
However, once I have gone though the infinite number of steps, the box ends up empty:
$$ S_{N=\infty}=0 $$
Proof: If the box is not empty, it must contain at least one apple numbered $N$. This is impossible, because I removed this apple in the step number $N$ according to the above procedure.
Where is a flaw in this logic and how is this apparent paradox resolved?
Comment: I believe the flaw is you're treating $\infty$ as a natural number with the $N = \infty$ in $S_{N = \infty} = 0$. However, $\infty$ is *not* a natural number.
Comment: I believe the problem is we're mixing different kind's of infinities here. The answer depends on what type of infinity you stop at. Since the apples are labelled in order, they have ordinals as labels. However the tricky thing about ordinals is that $\infty+1$ actually larger than $\infty$. So no matter what type of infinity you stop at, there will always be an ordinal larger than such infinity, which is still in the box.
Comment: Furthermore, technically you ARE allowed to perform an infinite number of operations such as this in mathematics, however the problem here is that there is no ordinal infinity that is larger than all other ordinal infinities. Which means that after completing an infinite number of steps, there is still many infinities worth of infinities to go through. See [ordinals](https://en.wikipedia.org/wiki/Ordinal_number).
Comment: Take an easier example. At step $1$, you put in apple $1$. At step $N\geq 2$, you put in apple $N$ and remove apple $N-1$. After, every step, there will always be exactly one apple in the box, but you cannot talk about \textit{the} apple, since it always changes.
Comment: @Graviton Thanks for the link. I am using the definition of infinity as an [Extended Real Number](https://en.wikipedia.org/wiki/Extended_real_number_line). According to Wiki, $\infty+1=\infty$. Is the article wrong?
Comment: @JohnOmielan I am treating $\infty$ as an [Extended Real Number](https://en.wikipedia.org/wiki/Extended_real_number_line).
Comment: @Hiroyashu See my answer for why using $\infty$ (even as an extended real number) isn't very helpful for this specific paradox.
Answer: Although I'm posting this an an answer, it's more of a continuation and clarification of the comments I added earlier. Regardless, I will attempt to aid in a solution to the "paradox". I hope you enjoy or find some of the following as fascinating as I do.
This question is actually really ellegant as it delves into the nature of infinity. I'm sure anyone invested in mathematics has heard something like the phrase "some infinities are larger than others". This eludes to there being a great variety in different types of infinities. Despite there being many types, often we simply use the symbol $\infty$ to denote all of them.
This works for most scenarios, like most of calculus. However, even a new undergrad will quickly be introduced to the difference between "countable" and "uncountable" infinities.
Ordinals & cardinals
Before I touch on infinity, I'd like to introduce the concepts of "ordinal numbers", and "cardinal numbers".
In brief, most numbers we're familiar with can be used with different intention to be either an ordinal or cardinal. When we're using numbers to represent size/magnitude/amounts of something, we're dealing with cardinals. But when we're using numbers to represent an index/placement, we're dealing with ordinals.
For example, the amount of apples in your box $S$, is a cardinal. Meanwhile the apple at index $N$, is an ordinal. Hence, there could be a time where $S=5$ and another when $N=5$, but in one case 5 is a cardinal and in the other 5 is an ordinal.
Infinite ordinals
Since ordinals deal intrinsically with placement/order, if you were to label an "infinite" number of apples, there's nothing stopping you from labeling one more. Let me introduce $\omega$, the smallest ordinal infinity.

In this diagram each line is labelled with it's corresponding ordinal. Notice how once we've labelled the lines using all the natural numbers $1,2,3\rightarrow\dots$, we can start labeling a second batch of infinite lines starting with $\omega, \omega+1,\omega+2\rightarrow\dots$.
Side note: In this context, that plus sign in $\omega+1$ doesn't exactly mean we're adding 1 to $\omega$, it might be better to say we're simply referring to the ordinal that is directly after $\omega$.
Anyways, after that second batch can start our third batch with $2\omega$ and so on. As you can see, we can proceed to label an infinite amount of infinitely-sized batches. Here is one of my favorite diagrams depicting the same line labeling game spiraling towards $\omega^\omega$

But it does not stop there! You could continue the labeling game to $\omega^{\omega^\omega}$ then $\omega^{\omega^{\omega^\omega}}$, and so on. Current mathematics literally has no limit to the size of ordinal infinities. In fact, we've tried several times to define the "largest possible ordinal" and nearly every time another mathematician comes along and defines a larger one. See Large countable ordinal on Wikipedia for some of these attempts.
Infinite cardinals
Slowly looping back to your question, let's go back to a more familiar type of infinity. Mathematician's use the symbol $ℵ_0$ to denote the cardinality of the set of natural numbers. I.e; the type of infinite to represent the amount of numbers in a countable set. It is the smallest cardinal infinity.
This type of infinity may be seen as more intuitive, as $ℵ_0+1=ℵ_0$. Even though adding a finite number to $ℵ_0$ doesn't change it's value, there are still bigger infinities. For example, the cardinality of the set of real numbers is $2^{ℵ_0}$, often denoted in some theories as $$ or $ℵ_1$. See Aleph numbers and Cardinality of the continuum.
Back to your question
To reiterate your question, we start with an apple with ordinality one and an box with cardinality zero. At step $n$ ($n$ is an ordinal!), we put apples $2n-1$ and $2n$ into the box, then take apple $n$ out. With each step, the carnality of the box goes up by 1.
Let's say we now go through an "infinite" number of steps. That really doesn't mean anything unless you specify which infinity.
Solving the paradox
Suppose we stop after $\omega$ steps, the smallest ordinal infinity. At step $\omega$, we've taken out all apples labelled $\omega$ or less. However we have now just put in apples labelled $2\omega-1$ and $2\omega$. Thus within the box there are still apples apples labelled $\omega+1$ through $2\omega$. Therefore the cardinality (amount) of apples in the box is $S=ℵ_0$. This is intuitive as despite removing an infinite number of apples, there's an equal amount still in the box. No paradox here!
But indeed, could a paradox arise after more than $\omega$ steps? That's where it gets a little more confusing. This MathSE question shows that no matter what step $n$ we stop at, since $n$ is a countable ordinal (because we're counting apples), the amount of apples in the box is still $ℵ_0$. Therefore, for a paradox to arise, we'd have to label apples beyond all countable ordinals, which is not even close to being a comprehensible idea. What would it mean to label apples so far beyond infinity, that we've run out of infinities?
From what I understand (and that's very little), it is not possible to "run out" of ordinals, especially in this very linear step-by-step process. What this means is that if we stop at any countable point after $\omega$ steps, there will always be $ℵ_0$ apples in the box. Attempting to wrap my head around going beyond countable ordinals, it could be possible to have more than $ℵ_0$ apples in the box (which wouldn't be paradoxical), but I'm probably already far beyond the scope of this question (let alone my understanding).
The paradox returns
All that said, if I recall correctly from a VSauce video How To Count Past Infinity on the subject (highly recommended), there is a number denoted $\Theta$ (possibly this number), which describes an ordinal so incredibly beyond $\omega$ and $\omega^{\omega^{\omega^\omega}}$, etc, that it is not possible to be reached with current methods of transfinite labeling.
If it's possible to even conceive of $\Theta$ steps, then it is possible for a paradox to arrive where you've exhausted all countable ordinals. In that case the number of apples left in the box may indeed be zero. If true, then such paradox only arrived because we pushed the bounds of infinity to it's breaking point. Here, mathematics dissolves. The nature of this type of infinity does what it pleases.
Concluding remarks
In conclusion, as far as mathematics is concerned, there's no paradox; the logic works out. Though as math is built on logic, going beyond the infinities that math can handle, logic no longer applies.
Comment: Also, I suggest that if OP wishes, you should request to reopen the question, as my answer doesn't entirely apply to the question that this is marked a duplicate of.

Infinite number of apples in a box


Paypal Instant Payment Notifications - Add a role but not as a subscription upon purchase

Question: Here's my use case: I have a Paypal "Buy now" button that I have created using Paypal's Website Payments Standards utility.  This provides an Instant Payment Notification when a user successfully makes a purchase.
What I would like to do is automatically give a user a role upon a successful purchase.  I installed the lm_paypal module, but it is a full-featured subscription solution which I don't need; all I want to do is give users a specific role.  (It's impossible to configure lm_paypal to simply give a user a role; it wants to turn the role into a subscription, but my use case is not a subscription.)
At worst, I can just add the role to user accounts manually when I receive payment, but I'd like to find a way to do it automatically.
Answer: I'm not sure the PayPal button is the way forward - you're probably better off using one of the cart modules (Ubercart, Drupal Commerce) so that when the IPN comes in the order status will be updated.
Then using Rules or Conditional Actions you can set up an event (triggered by the status update) to fire off an action that will add the role to the user.
Make sure to add conditions so that this only happens if the order balance is <= 0 (fully paid for) and if a certain product is in the cart. Also to make sure that it only occurs on updates between the two particular statuses (In Checkout -> Payment Received).
If there is no built-in action to actually add the role then you can use the "Custom PHP" action (or similar).
If you find the idea of writing that chunk of php yourself, don't fret. Just search for "drupal add user role programmatically" (without quotes) and you'll be on your way.
I don't know it off the top of my head, but I know that it isn't long.
One thing I have found very useful is to add an "email" action to my conditional actions, with myself as the recipient. Set the input format to PHP and put this in the body:
<?php print_r($order); ?>
This gives you the $order array from which you can extract values such as the user ID to use in your PHP action.


Is there for modules the same as theme_get_setting() for themes?

Question: I am using variable_get('name-of-setting', 'default-value') to retrieve module/theme settings in several locations in code.
The purpose is to keep default settings in one locations preferable in .info file. I am able to this for themes:
variable_get('name-of-setting', theme_get_setting('name-of-setting'));

Here the theme_get_setting() retrieves the settings from the theme-name.info file:
settings['name-of-setting'] = some_value

Can i do the same for modules? What is the API to retrieve settings from module .info file? If not, how do you handle module default settings to avoid it scatter around code?
Answer: You're probably looking for drupal_parse_info_file()

Parses Drupal module and theme .info files.
Info files are NOT for placing arbitrary theme and module-specific settings. Use variable_get() and variable_set() for that.

Pay attention to the second paragraph - it applies to you :)


I want to make a button swap two div wrappers and their children elements

Question: I am trying to make a button change two divs and their children elements. Their children elements include an  and  with text. I just want to click the button and make the entire content swap places.
Here is the html and javascript.

function switchTokens() {
  var obj1 = document.getElementById('from_token_select').value;
  var obj2 = document.getElementById('to_token_select').value;

  var temp = obj1;
  obj1 = obj2;
  obj2 = temp;

  // Save the swapped values to the input element.
  document.getElementById('from_token_select').value = obj1;
  document.getElementById('to_token_select').value = obj2;
}

  from_token_text

<button onClick="switchTokens()" id="swap_token_address" class="fa-solid fa-arrows-up-down">switchTokens Btn</button>

  to_token_text

Comment: Are you trying to change the class?
Comment: use `.innerHTML` instead of `.value`
Comment: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
Comment: If you wrap these elements in a flex or grid container you could use the CSS [order](https://developer.mozilla.org/en-US/docs/Web/CSS/order) property on the parent to reverse their rendered positions without changing any markup.
Comment: Thank you all, and yes, I also want to swap the classes as when I refer to swapping everything is every single element contained in the divs.
Answer: As I understand you'd like to swap the entire contents of the divs? If that's the case, this JS does the trick:
function switchTokens() {
  var obj1 = document.getElementById('from_token_select').innerHTML;
  var obj2 = document.getElementById('to_token_select').innerHTML;

  // Save the swapped values to the input element.
  document.getElementById('from_token_select').innerHTML = obj2;
  document.getElementById('to_token_select').innerHTML = obj1;
}


Confidence of uniformity from a sample of a binary state collection

Question: The system:

I have a bag filled with 1,000 balls
All of them are either red or blue

I want to gain some amount of confidence that all the balls are blue, but I'm very lazy and I only want to examine a sample as small as possible.
Question: How large must the sample be to say with P confidence that N balls are blue?
I'm looking for a generic answer, but here are two specific questions:

How large must the sample be to say with 95% confidence that all 1,000 of the balls are blue?
How large must the sample be to say with 95% confidence that 990 (99%) of the 1,000 balls are blue?

It's been a while with no response, so if my question is missing information or just bad for some reason, please let me know how I can improve it.
Answer: Sorry if this answer is incomplete, but I can't fit it all in a comment.
If you specify a level of statistical power you want to achieve, you can use the following formula as an approximation: $n=\frac{1}{2}(b-\sqrt{b^2 + 4b(Z_p + Z_{\alpha})^2})$ where $n$ is your sample size, $b$ is the number of blue balls in the sample, $Z_p$ is the Z score for your power, and $Z_{alpha}$ is the Z score for your confidence level. Note I used $\alpha$ instead of $\alpha/2$ because it's one-tailed.
This comes from the standard power calculation for a difference in means. I just set one of them equal to 1 and ran it in Wolfram Alpha. However, this does not take the finite population into account and I don't know what the error will be like if you're sampling more than a few dozen balls at a time. In this case, "power" means the "probability of finding a red ball given that there is at least one red ball in the bag." More technically, it's the probability of rejecting the null hypothesis that the sample proportion $\hat{p}$ is equal to 1.
This is what Wolfram Alpha gave me when I slapped the finite population correction into the same formula, and it's not pretty. It's no better if you plug in $N=1000$, and no solution exists for n=b (i.e. your entire sample is blue). It reduces a bit if you plug in $N=1000$ and $.99*n=b$. I hope that helps, but I'm sure there's a better way to go about this.
Answer: Condition (2) implies you only need a sample of size 1.
If it is known that all the balls are one color, you only need to observe a single ball to know the color of all of them.
If it is not known that all the balls are one color, you cannot a priori rule out the possibility that exactly one ball is of a different color, in which case you should work on that worst-case -- you will need a very large random sample to be reasonably sure you haven't missed it by chance.
In particular, if you're sampling without replacement, you would need to sample 95% of the balls to be 95% sure that there's not a single ball of a different color there. (If you sample with replacement and only take one ball each time, you need to sample almost 3000 times!)
You should clarify what is known to the person who has to decide how large a sample to take.
Comment: To restate the known parameters: 1) The number of balls is known (1,000), and 2) each ball can be only one of two colors (red or blue). The exact number of each color is unknown. There could be 0 red and 1,000 blue or there could be 600 red an 400 blue, etc. In this problem I am sampling without replacement.

Although your answer is making me think that I might *need* to make an assumption about the exact number of each color in order to show how likely it is given the outcome of a certain number of randomly drawn balls.
Comment: Okay, thanks. The situation you describe is one of the possibilities covered in my answer (which is that in the worst case you need 95% of the population).
Comment: Starting with your worst-case scenario where one ball is red and 999 are blue, I'd say the chance of drawing the one red ball on the first try is 1/1000. But on the second draw, the odds improve to 1/999, the third is 1/998 and so on. The odds of drawing 100 blue balls in a row out of the bag in this scenario should actually be a little under 90% if you add up the probability of each independent event. The probability of drawing 614 blue balls in a row without drawing the red one should be just under 5% if I did the math right. Am I missing anything?
Comment: You call those events independent, but they aren't; you're forgetting the second draw is conditional on getting a blue ball the first draw. Consider the much simpler case of 3 blue and  1 red, and place them in the first of two adjacent boxes, then draw two and place them in the second box. By your argument, there's a 7/12 chance that the red ball is in the second box and a 5/12 chance it's in the first box... [if that seems fine to you, I have a nice sequence of bets for you which - if you're right - should make you rich in short order.]
Comment: You might like to consider the 4 balls sitting in a row (numbered 1,2,3,4, representing the order we will draw them). Can you see the red has equal chance to be in any of the 4 positions?


Where does the opening solo of the Rite of Spring come from?

Question: In Tom Service's commentary to the BBC Proms 2013 performance of the Rite of Spring, he starts off with something I had no idea of:

The best bassoon solo ever? It sounds otherworldly: but it's actually a Lithuanian wedding song… (TS) #riteofspring
@bbcproms on twitter

I'm really curious to listen to this Lithuanian wedding song. Is it known, or relatively easy to reach?
Comment: Cool- I'd never heard that, but multiple website articles verify that claim.  I'd recommend you go to such sites and track down the scholarly articles & published books they reference.   Or marry a Lithuanian :-)
Comment: I heard an interview with bass player Pino Palladino, who said that his bass line at the beginning of the Paul Young recording of 'Wherever I lay my hat' is based on that same Rite of Spring basson line.
Comment: @Brian That's a healthy dose of mind-blowingness for today. Thank you very much for that.
Comment: @E.P. yeah, I thought that was pretty awesome, too, so just had a listen to the track (first time in *many* years). Bit of a disappointment - only about 4 notes make it into the bass part for the intro...!
Answer: The song Tu, manu seserėlė was taken from Anton Juszkiewicz's Melodje ludowe litewskie, (number 157 in the collection. You can see a copy of the tune.
In abc format:
<code>X:157
T:Tu, manu seserėlė
C:Trad.
M:3/4
K:B
L:1/4
edB|G2d|1c2d:|2c2c|:edc|f2e|d2c|edB|G2d|c2c:|
</code>
Answer: Supposedly the song is: "Tu, manu seserėlė" (from: http://www.orchestralbassoon.com/stravinsky-the-rite-of-spring/ (link now dead; archived version here)).
I can't figure out hot to link to the original tune but it's on the linked web page.


How to add margin to a Button at run time?

Question: I have to add more than one buttons on a LinearLayout. But I want to put those buttons say 5px apart. I could not find a way to set a margin of a Button. Any idea?
Answer: Use the layout_margin property of the button element. Does that not work?
<Button android:layout_margin="5px" (...)/>

Edit
When creating a button in java, LayoutParams is used to specify margins and so.
Button button = new Button();
(....)
params = new LinearLayout.LayoutParams();
params.leftMargin = 5;
(set params as you need)
parent.addView(button, params);

The LayoutParams you use must match the Layout you add your button in (see http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html). For a LinearLayout, use a LinearLayout.LayoutParams and set the *Margin fields accordingly.
Comment: Thank much for your help. I'm sorry that

It doses not do what I want!

Say,

LinearLayout.LayoutParams lParam  = new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT );

        lParam.setMargins(20, 20, 20, 20);

It adds margin to the LinearLayout. Not to the button. For example, it there is 2 buttons, side by side, it does *not* add space between the buttons! Which is my goal!

Thanks!
Comment: I am new to Android!

I am confused, if I have it in XML, then how can I use while

creating dynamically?

My code looks like this,

  btnSend = new Button(this);

        btnSend.setText("Send...");

        btnSend.setBackgroundResource (R.drawable.red_button);

        btnSend.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    // TODO Auto-generated method stub

    // Code here...

   }

  });
Comment: I edit my post with informations regarding dynamic button creation
Comment: This is getting complicated. Can you post the code you have? Also, make sure the layoutParams is either set to the button or used in the addView method
Answer: Try this:
//Assuming your button is in a LinearLayout as stated
LinearLayout.LayoutParams params = myButton.getLayoutParams();
params.setMargins(0, 0, 0, 0) //left, top, right, bottom
myButton.setLayoutParams(params);

Comment: I'm not writing a program to pass testing here, it's a general idea of what is required. As I stated in the comment, I'm assuming his button is in a LinearLayout, as he stated in his original post. In this link: http://developer.android.com/reference/android/view/View.html#getLayoutParams(), it is stated that `When a View is attached to a parent ViewGroup, this method must not return null`. Ergo, it will not be null in this instance.
Comment: that works too, except the setLayoutParams is useless. and getLayoutParams may be null. and how do you know it is a LinearLayout.LayoutParams that the button has ?
Comment: @kcoppock,

Thanks, I think you are right that it will not return null, according your assumption that it is in LinearLayout. But, since the button is added to that layout later; in this case, it returns null. Thank you all!
Comment: @kcoppock, how to write if am using Relative Layout
Answer: MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;
vector8.setLayoutParams(params);

Need use type of: MarginLayoutParams
Comment: this is helpfull for me
Answer: Adding padding to the buttons would also solve your problem.  Check this out
http://developer.android.com/resources/tutorials/views/hello-formstuff.html#CustomButton
Comment: Thanks, but padding adds space inside the button area, say space between the edge and the text of the button.
Comment: try this :   setGravity(int): Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view.
Answer: use this code to set margin at runtime
  LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btnContainer.getLayoutParams();
        params.setMargins(5, 50, 10, 0); //left, top, right, bottom
        view_whwre_set_margin.setLayoutParams(params);


detect Card in visual basic

Question: anyone can help me. i build system registration using I/C Card. i also have sdk reader and can read data in i/c card. but my problem now, is how to read i/c card without click any button. user just insert i/c card and system read card and save in database(without user interaction)
i'm using vb 2008 and database sql.
Answer: You could use either a FileSystemWatcher to monitor that location or run a timer event that constantly checks for the card's presence and does nothing until it returns a true result

detect Card in visual basic


Harmonic Function and Subharmonic function

Question: Suppose $u\in C^1(\bar{U})\cap C^3(U)$, where $U$ is a bounded simply connected open set. If $\Delta u=0$ and $u(x)\neq0$ for all $x$ , show that $\varphi=\frac{\vert Du\vert^2}{u^{\frac{2(n-1)}{n-2}}}$ satisfies $\Delta\varphi\geqslant0$
I have calculated that $$\Delta\varphi=2u^{-\frac{2(n-3)}{n-2}}\sum_{i,j=1}^n(u_{ij}^2u^2-4\frac{n-1}{n-2}u_iu_ju_{ij}u+\frac{(n-1)(3n-4)}{(n-2)^2}u_i^2u_j^2)$$
But I don't know what to do next to show $\Delta\varphi\geqslant0$. I also considered that $\varphi=\vert D(u^{-\frac{1}{n-2}})\vert^2$, but I don't make any progress.
How should I do next?
Any answer or counterexample would be appreciated! Thanks for attention.
Comment: It seems this function named P-function in literature. Can anyone provide more information?
Comment: If you get a nice enough coefficient for the last term, I think factorization will give the answer.
Answer: Well my teacher made a mistake on the problem. We only need to show that $\varphi$ satisfies the maximal principle and we do not need to show that $\Delta\varphi\geqslant0$.
To this end, let us first consider $\phi=\frac{\vert Du\vert^2}{u^{\alpha}}$ for $\alpha\in(0,\frac{2(n-1)}{n-2})$. If $\phi$ attains its maximum at $x_0\in U$, then $D\phi(x_0)=0$. Take a special coordinate such that at $x_0$ we have $Du(x_0)=(\vert Du\vert,0,\dots,0)$. Then we can compute$$D_i\phi(x_0)=2\sum_{j=1}^nD_juD_{ij}uu^{-\alpha}-\alpha\vert Du\vert^2D_iuu^{-\alpha-1}=2\vert Du\vert D_{i1}uu^{-\alpha}-\alpha\vert Du\vert^3\delta_{i1}u^{-\alpha-1}$$Now there are two cases. If $Du(x_0)=0$, then $\phi(x_0)=0$ and since $\phi(x_0)=\max_U\phi$, we have $\phi=0$ in $U$ hence  $\phi$ satisfies the maximal principle. Otherwise, we have $2D_{i1}u=\alpha\vert Du\vert^2u^{-1}\delta_{i1}$ at $x_0$. Next we have
\begin{equation}
\Delta\phi=2\vert D^2u\vert^2u^{-\alpha}+2D\vert Du\vert^2\cdot Du^{-\alpha}+\vert Du\vert^2(\alpha(\alpha+1)\vert Du\vert^2u^{-\alpha-2}
\end{equation}At $x_0$, $$\vert D^2u\vert=(D_{11}u)^2+\sum_{i,j=2}^n(D_{ij}u)^2\geqslant(D_{11}u)^2+\sum_{i=2}^n(D_{ii}u)^2\\\geqslant(D_{11}u)^2+\frac{1}{n-1}(\sum_{i=2}^nD_{ii}u)^2=\frac{n\alpha^2}{4(n-1)}\vert Du\vert^4u^{-2}$$Also, $D\vert Du\vert^2\cdot Du^{-\alpha}=-\alpha^2\vert Du\vert^2u^{-\alpha-2}$ at $x_0$. Hence $$\Delta\phi(x_0)\geqslant(\frac{n\alpha^2}{2(n-1)}-2\alpha^2+\alpha(\alpha+1))\vert Du\vert^2 u^{-\alpha-2}>0$$since $(\frac{n\alpha^2}{2(n-1)}-2\alpha^2+\alpha(\alpha+1))=\alpha^2(\frac{1}{\alpha}-\frac{n-2}{2(n-1)})>0$. However, this contradicts the assumption that $\phi(x_0)=\max_U\phi$. As a result, we get $$\max_U\phi=\max_{\partial U}\phi$$Just let $\alpha\rightarrow \frac{2(n-1)}{n-2}$.


msysgit git clone ignores ssh config

Question: I've installed msysgit and git uses proper ssh.exe. All commands are executed in msysgit shell (program files x86 sh.exe).
Then i set my ~/.ssh/config file to this
LogLevel DEBUG1

Host bitbucket.com
  HostName bitbucket.com
  PreferredAuthentications publickey
  IdentityFile /d/ssh/bitbucket.ppk
  IdentitiesOnly yes

Then ssh bitbucket.com works well:
$ ssh bitbucket.com
debug1: Connecting to bitbucket.com [18.104.22.168] port 22.
debug1: Connection established.
debug1: identity file /d/ssh/bitbucket.ppk type -1
debug1: identity file /d/ssh/bitbucket.ppk-cert type -1

but when i try to git clone email@example.com:User/reponame.git ssh debug messages shows me that ssh don't even try to pick bitbucket ppk, instead trying to use default keys:
$ git clone email@example.com:user/reponame.git
Cloning into 'reponame'...
debug1: Connecting to bitbucket.org [220.127.116.11] port 22.
debug1: Connection established.
debug1: identity file /c/Users/bob/.ssh/id_rsa type -1
debug1: identity file /c/Users/bob/.ssh/id_rsa-cert type -1
debug1: identity file /c/Users/bob/.ssh/id_dsa type -1
debug1: identity file /c/Users/bob/.ssh/id_dsa-cert type -1
debug1: identity file /c/Users/bob/.ssh/id_ecdsa type -1
debug1: identity file /c/Users/bob/.ssh/id_ecdsa-cert type -1
debug1: identity file /c/Users/bob/.ssh/id_ed25519 type -1
debug1: identity file /c/Users/bob/.ssh/id_ed25519-cert type -1

I'm out of ideas.
$ where git
C:\Program Files (x86)\Git\bin\git.exe
C:\Program Files (x86)\Git\cmd\git.exe

Answer: git clone email@example.com:User/reponame.git would look for ~/.ssh/id_rsa and id_rsa.pub, not for /d/ssh/bitbucket.ppk.
What should work (since ssh bitbucket.com does work) is:
git clone bitbucket.com:User/reponame.git

That would actually use the parameters defined in the ~/.ssh/config file.
bitbucket.com is the entry in the config file (it could be named anything really), but the HostName must be indeed bitbucket.org, which is the domain where the Git repos are stored.
Answer: The reason was my own inattention. Bitbucket uses bitbucket.org for repos. Afaik, before it used bitbucket.com.
Comment: I agree. I have added that in my answer to be complete.

msysgit git clone ignores ssh config


How to avoid converting URLs to links?

Question: Using CKeditor5 in Drupal site... is there a way to avoid converting a specific URL to link in a specific page or paragraph? How?
Update: explanation
I have a paragraph where I give the bibtex to copy; one of the entries of the bibtex is an url which has to be presented like in this picture:

But CKeditor5 presents it this way:
howpublished = {\href{http://www.chandia.net/corlexim}{http://www.chandia.net/corlexim}},

Note that in this explanation I have entered the line as it should be presented but it has been automatically converted to links...
Comment: I'm pretty sure there's no easy off-the-shelf way to do this.  What's the context?  Is this a spam link? An internal link that should not be exposed?
Comment: I'll put context in the question, thanks for bringing that to mind
Comment: I cannot reproduce it. On Drupal 10, entering that line in CKEditor5, CKEditor5 shows the source as `howpublished = {\href{http://www.chandia.net/corlexim}{http://www.chandia.net/corlexim}}`. If I enable *Convert URLs into links* URLs are shown as links, but CKEditor5 still shows the source as `howpublished = {\href{http://www.chandia.net/corlexim}{http://www.chandia.net/corlexim}}`.
Comment: I checked it and you're right, when the text with the url is between  it remains as it should. My fault, I didn't mention that the text with url is inside , and the one I put in the question above is between
Answer: I can reproduce this only when the node is using the Full HTML input format an the Convert URLs into links filter is enabled for that input format. In this case, a node that contains <textarea>howpublished = {\href{http://www.chandia.net/corlexim}{http//www.chandia.net/corlexim}}</textarea> is rendered as the following screenshot shows.

The only way to avoid that is disabling the Convert URLs into links filter in /admin/config/content/formats/manage/full_html. When I do that, the node is rendered as expected.
Comment: Thanks, you have given me the idea of creating a new text format which have url to link conversion disabled and apply that text format for the page I'm working with...
Comment: Thanks again @apademo, that did it!!!
Answer: Thanks to @apademo's answer I came up with the idea (actually it is so logically obvious) of creating a new "text format" in Drupal which does not have activated "Convert URLs into links" option, but it has all of the others (or the ones you need) that make it a "Complete Html" format.
Then, I have applied that format to the page where I don't want the urls converted into links...
Obviously, if there is some other URL in the same page that you do want to convert into link, you will have to do it manually:
Manualy Linked URL

Thanks for the answers!

How to avoid converting URLs to links?


AppleScript Word Count Service

Question: I am trying to create a service in OSX leopard that counts the number of words of selected text. I have automator set to run an applescript, with the following put in it:
on run {input, parameters}
        count words of input
        display alert "Words: " & input
        return input
end run

When I compile the script, it says it cannot count every word. What am I doing wrong?
Thanks for the help,
Elliott
Answer: First of all, I presume you are testing this in Automator, and that's where the error is taking place? If so, the likely problem is that there is no input—so it can't count the words of nothing. In order to test it successfully, you need to temporarily add a "Get Specified Text" action before the Run AppleScript action, and enter some test text into that field. You'll have to remove the Get Specified Text action before using it as an actual service.
Secondly, you need to use
count words of (input as string)

in order to get a proper count, otherwise it'll return zero.
Comment: Thanks for the answer- I had the issue of not using a string, so thanks for clearning that up.
Answer: I made one here, on Github:
https://gist.github.com/1616556
The current source is:
on run {input, parameters}
    tell application "System Events"
        set _appname to name of first process whose frontmost is true
    end tell
    set word_count to count words of (input as string)
    set character_count to count characters of (input as string)
    tell application _appname
        display alert "" & word_count & " words, " & character_count & " characters"
    end tell
    return input
end run

Use Automator.app to create a new service, and then select the Run AppleScript action. Paste this code in to the text box, and save as Word and Character Count. Now switch to a new app, select some text, and open the context menu to find the new option.

AppleScript Word Count Service


Test of Group Invariance with 3 Groups

Question: Say, we have three groups and we want to run a test of group invariance with the following data.
set.seed(1234)
df <- data.frame(
  id = 1:300,
  group = as.factor(rep(c("a", "b", "c"),each=100)),
  x1 = round(rnorm(300, 3.00, 0.50),2),
  x2 = round(rnorm(300, 3.00, 0.50),2))
  df$dv <- round(.20*df$x1 + .30*df$x2+ rnorm(300, 0, 1),2)

The model with configural invariance is as follows:
library(lavaan)
m1 <- '
dv ~ x1 + x2
'
fit <- sem(m1, estimator="ML", data=df, group="group")
summary(fit, fit.measures=T)

The output we get is
lavaan 0.6.15 ended normally after 52 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        12

  Number of observations per group:
    a                                              100
    b                                              100
    c                                              100

Model Test User Model:

  Test statistic                                 0.000
  Degrees of freedom                                 0
  Test statistic for each group:
    a                                            0.000
    b                                            0.000
    c                                            0.000

Model Test Baseline Model:

  Test statistic                                 6.897
  Degrees of freedom                                 6
  P-value                                        0.330

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    1.000
  Tucker-Lewis Index (TLI)                       1.000

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)               -409.471
  Loglikelihood unrestricted model (H1)       -409.471

  Akaike (AIC)                                 842.943
  Bayesian (BIC)                               887.388
  Sample-size adjusted Bayesian (SABIC)        849.331

Root Mean Square Error of Approximation:

  RMSEA                                          0.000
  90 Percent confidence interval - lower         0.000
  90 Percent confidence interval - upper         0.000
  P-value H_0: RMSEA <= 0.050                       NA
  P-value H_0: RMSEA >= 0.080                       NA

Standardized Root Mean Square Residual:

  SRMR                                           0.000

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Group 1 [a]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1                0.033    0.188    0.176    0.860
    x2                0.143    0.180    0.798    0.425

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.873    0.718    1.215    0.224

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.863    0.122    7.071    0.000

Group 2 [b]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1                0.364    0.195    1.872    0.061
    x2                0.047    0.180    0.259    0.796

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.285    0.806    0.354    0.724

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.999    0.141    7.071    0.000

Group 3 [c]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1               -0.291    0.192   -1.513    0.130
    x2               -0.148    0.199   -0.747    0.455

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                2.847    0.861    3.306    0.001

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.838    0.119    7.071    0.000

Now, let's impose to the above model a path-equality constraint with the following group ordering
Group 1 = [a]
Group 2 = [b]
Group 3 = [c]
Let's call this model, Model abc
fit_abc <- sem(m1, estimator="ML", data=df, group="group",
             group.equal=c("regressions"),
             group.label=c("a","b","c"))
summary(fit_abc, fit.measures=T)

The output is as follows:
lavaan 0.6.15 ended normally after 28 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        12
  Number of equality constraints                     4

  Number of observations per group:
    a                                              100
    b                                              100
    c                                              100

Model Test User Model:

  Test statistic                                 6.665
  Degrees of freedom                                 4
  P-value (Chi-square)                           0.155
  Test statistic for each group:
    a                                            0.387
    b                                            2.699
    c                                            3.579

Model Test Baseline Model:

  Test statistic                                 6.897
  Degrees of freedom                                 6
  P-value                                        0.330

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    0.000
  Tucker-Lewis Index (TLI)                      -3.458

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)               -412.804
  Loglikelihood unrestricted model (H1)       -409.471

  Akaike (AIC)                                 841.608
  Bayesian (BIC)                               871.238
  Sample-size adjusted Bayesian (SABIC)        845.867

Root Mean Square Error of Approximation:

  RMSEA                                          0.082
  90 Percent confidence interval - lower         0.000
  90 Percent confidence interval - upper         0.187
  P-value H_0: RMSEA <= 0.050                    0.255
  P-value H_0: RMSEA >= 0.080                    0.590

Standardized Root Mean Square Residual:

  SRMR                                           0.045

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Group 1 [a]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.179    0.461    2.557    0.011

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.867    0.123    7.071    0.000

Group 2 [b]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.302    0.470    2.768    0.006

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.026    0.145    7.071    0.000

Group 3 [c]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.294    0.469    2.760    0.006

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.869    0.123    7.071    0.000

Now, let's rerun the same model - let's call it Model bac - by changing the order of groups by
Group 1 = [b]
Group 2 = [a]
Group 3 = [c] ```
fit_bac <- sem(m1, estimator="ML", data=df, group="group",
              group.equal=c("regressions"),
              group.label=c("b", "a", "c"))
summary(fit_bac, fit.measures=T)

The output will be exactly the same as above, with the only difference the ordering of the groups
lavaan 0.6.15 ended normally after 28 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        12
  Number of equality constraints                     4

  Number of observations per group:
    b                                              100
    a                                              100
    c                                              100

Model Test User Model:

  Test statistic                                 6.665
  Degrees of freedom                                 4
  P-value (Chi-square)                           0.155
  Test statistic for each group:
    b                                            2.699
    a                                            0.387
    c                                            3.579

Model Test Baseline Model:

  Test statistic                                 6.897
  Degrees of freedom                                 6
  P-value                                        0.330

User Model versus Baseline Model:

  Comparative Fit Index (CFI)                    0.000
  Tucker-Lewis Index (TLI)                      -3.458

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)               -412.804
  Loglikelihood unrestricted model (H1)       -409.471

  Akaike (AIC)                                 841.608
  Bayesian (BIC)                               871.238
  Sample-size adjusted Bayesian (SABIC)        845.867

Root Mean Square Error of Approximation:

  RMSEA                                          0.082
  90 Percent confidence interval - lower         0.000
  90 Percent confidence interval - upper         0.187
  P-value H_0: RMSEA <= 0.050                    0.255
  P-value H_0: RMSEA >= 0.080                    0.590

Standardized Root Mean Square Residual:

  SRMR                                           0.045

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Group 1 [b]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.302    0.470    2.768    0.006

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.026    0.145    7.071    0.000

Group 2 [a]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.179    0.461    2.557    0.011

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.867    0.123    7.071    0.000

Group 3 [c]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  dv ~
    x1      (.p1.)    0.043    0.111    0.384    0.701
    x2      (.p2.)    0.032    0.108    0.293    0.770

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                1.294    0.469    2.760    0.006

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .dv                0.869    0.123    7.071    0.000

If we inspect the equality constraints for Model abc through lavTestScore
lavTestScore(fit_abc)

we get this
$test

total score test:

   test    X2 df p.value
1 score 6.565  4   0.161

$uni

univariate score tests:

   lhs op   rhs    X2 df p.value
1 .p1. == .p10. 3.899  1   0.048
2 .p1. == .p19. 4.054  1   0.044
3 .p2. == .p11. 0.008  1   0.930
4 .p2. == .p20. 0.856  1   0.355

My take is that for this model (Model abc, where the group order is a, b, c),
line #1 compares the first regression coefficient of group a with group b and
line #2 compares the first regression coefficient of group a with group c
If, however, we inspect the equality constraints for Model bac through lavTestScore
lavTestScore(fit_bac)

we get this
$test

total score test:

   test    X2 df p.value
1 score 6.565  4   0.161

$uni

univariate score tests:

   lhs op   rhs    X2 df p.value
1 .p1. == .p10. 0.002  1   0.963
2 .p1. == .p19. 4.054  1   0.044
3 .p2. == .p11. 0.610  1   0.435
4 .p2. == .p20. 0.856  1   0.355

Based on the above logic,
line #1 compares the first group with the second (so, again, "b" with "a"), and
line #2 compares the first with the third group (i.e., now "b" with "c").
I would expect lines #1 from the two lavTestScore outputs to be the same and lines #2 to differ. But it seems that this is not the case.  Instead, lines #2 are the same, and lines #1 differ.
Obviously, I miss a piece of critical information about how comparisons are conducted, but I could not find any hint about this issue. Any hint or help will be much appreciated.
Thanks for your consideration.
Comment: A reproducible example (reprex) includes enough data and syntax to create the output, not merely the output about which you have a question.  Your response on the lavaan forum also did not provide a reprex, so it is not clear whether you understood and implemented my suggestion.  If you cannot provide your own real data to post a reprex, you can use simulated data or some other public data (e.g., from the lavaan package) to show the same issue.
Comment: Cross-posted on the lavaan forum, where an answer was provided: https://groups.google.com/g/lavaan/c/h5S5BUZM1v0
Comment: No answer has been provided there, either. The full output is exhibited above, and despite the comment that the above issue has been posted elsewhere, the question remains: Why do the results not match when changing the group order?
Answer: Without seeing your syntax, it is difficult to understand what you actually specified. Also, have you considered running a nested model comparison first (as an omnibus test of differences in path coefficients between all 3 groups)? That is, specify two models: one in which the path coefficients are free to vary across groups and one in which they are constrained to be equal across groups. Then, you can run a chi-square difference test between the two models to see if there are any differences between the groups regarding the path coefficients.
Comment: Thanks Cristian for the feedback. I tried to clarify my question by adding more info (and the output)
Answer: Thanks to Yves Rosseel (the founder of lavaan), we found why this seeming inconsistency in the chi-square univariate test appears when group ordering is changed.
In a sequence of grouping a-b-c, the first chi-square value corresponds to the release constraint of the group "a" vs. the other two groups, combined (i.e., "b" and "c"). So, when the group ordering changes to b-a-c, the release constraint refers to group "b" against the groups "a" and "c", combined.
Yves has cross-checked it and confirmed that this is the case.
So, everything seems fine and in good order.

Test of Group Invariance with 3 Groups


What is the file path to the data directory of the latest version of PostgreSQL installed in my mac?

Question: There are two versions of PostgreSQL installed in my Mac: 9.6 and 10.1. Currently, when I use the psql command, it's using 10.1 version of the database. I want to figure out the location of the data directory for the latest version. The following command returns the filepath for the version 9.6, not 10.1.
ps auxwww | grep postmaster

What should my terminal command be to get the data directory of the latest version?
Comment: Start `psql`, login as the superuser (to the running version 10), run `show data_directory`
Answer: https://www.postgresql.org/docs/current/static/storage-file-layout.html

PG_VERSION    A file containing the major version number of PostgreSQL

so to find all possible $PGDATA, run as root:
find / -name PG_VERSION


Solving $3\sqrt3 = \sqrt{3x} $ for $x$

Question: If I have one square root that involves a coefficient, and one square root that doesn't, how do I solve for $x$?
$$3\sqrt3 = \sqrt{3x} $$
I tried to simplify it like:
$$ \frac{3\sqrt3} {\sqrt3} = \sqrt x$$
But ran into a dead end...what do I do next?
Comment: After seeing it happen many times, I can't help reminding you to be sure you're not confusing $\sqrt{3x}$ with $\sqrt{3}x$, which are two quite different things.
Comment: Do you see that $\dfrac {3 \sqrt 3}{\sqrt 3} = 3 \sqrt {\dfrac{3}{3}} = 3 \sqrt 1 = 3$?
Comment: I would immediately square both sides and get rid of the square root.
Answer: Note that: $$\dfrac {3 \sqrt 3}{\sqrt 3} = 3 \sqrt {\dfrac{3}{3}} = 3 \sqrt 1 = 3$$
But we can think of approaching the original equation by first noting:
$$3\sqrt3 = \sqrt{3x}  \iff 3\sqrt 3 = \sqrt 3 \times \sqrt x$$
and "canceling" $\;\sqrt 3\;$ from each side of the equation.
$$3\sqrt 3 = \sqrt 3 \sqrt x \quad \iff \quad 3 = \sqrt x$$
Now simply square both sides of the equation: $$(3)^2 = \left(\sqrt x\right)^2 \quad \iff \quad 9 = x$$
Answer: You have
$$
\sqrt{x} = \frac{3\sqrt{3}}{\sqrt{3}}.
$$
Note here that $x$ must be positive. You can now simply square both sides:
$$
x = (\sqrt{x})^2 = \left(\frac{3\sqrt{3}}{\sqrt{3}}\right)^2.
$$
Left for you to do is to simplify things.

Solving $3\sqrt3 = \sqrt{3x} $ for $x$


Admissions per year before and after antibiotics?

Question: I need to compare hospital admissions per year before and after the introduction of antibiotics in 100 patients (antibiotics introduced at various time points in the past).
Eg.
Before antibiotics: admissions: 2   start: Jan-09   end: Dec-13   years: 4.92   admissions/year: 0.4
After antibiotics: admissions:0     start: Dec-13   end: June 19  years: 5.5    admissions/year: 0
If I use a t test then 0 admissions in 1 month equals to 0 admissions in 5 years, which is not correct.
Would you recommend any specific software?
Comment: Do you have 100 patients before antibiotics and another 100 after? If only 100 altogether, how many before antibiotics and how many after?
Comment: These are 100 altogether and they are the same patients before and after antibiotics- just different time intervals for each: eg patient A was not on antibiotics for 2 years and then took them for 5 years while patient B was not on antibiotics for 7 years and then took them for 1 year.
Comment: Duplicate of [your previous question](https://stats.stackexchange.com/questions/434992/comparing-variables-that-involve-time)
Answer: I would start with Poisson regression, maybe with a random effect for patient. First, present the data in the following long format (you will need some transformations):
ID     Antibiotics   Admissions_total   Time_length ...
1      without         10                  3
1      with            8                   3
2      without         11                  4
2      with            3                   1
 ...

so you have to calculate total admissions, not per year, and length of period with/without in years/months. The length will then enter as an offset, that is, a variable with a known coefficient of 1. See Scaling vs Offsetting in Quasi-Poisson GLM.  The model can then be written as
$$
   \text{Admissions-total}_i \sim \mathcal{Poisson}(e^{\lambda_i})
$$
where $\lambda_i= \mu + \tau_i + \text{Antibiotics}_i +\text{offset}(\log{\text{Time_length}})$. Here $\tau_i$ (if included in the model) is a patient random effect.
A simpler model without the random effect can be implemented in R with
mod_glm <- glm(Admissions_total ~ Antibiotics + offset(log(Time_length)), family=poisson, data=your_data_frame)

but as there might be large differences between patients, it is probably better to include random effects, which in R could be
library(lme4)
mod_lme4  <- glmer(Admissions_total ~ Antibiotics + offset(log(Time_length)) +(1 | ID), data=your_data_frame, family=poisson)

This could at least be a starting point.  The model is called a Poisson rate regression.
While I used R in my example, this could be done with most statistical software.


How do I prevent a user from accessing a server's API directly and instead force them to use the UI?

Question: More of a theoretical question, but I'm really curious!
I have a two part application:

Apache server hosting my UI
Back-end that services all http requests from the UI

The apache service proxies all http requests from the UI to the server. So, if the user is reasonably adept, they can reverse engineer our API by inspecting the calls in the browser's developer tools.
Thus, how do I prevent a user from using the server API directly and instead force them to use the UI?
The server can't determine whether a call came from the UI or not because a user can make a call to myapp.com/apache-proxy/blah/blah/blah from outside of the UI, apache will get the request and forward it to the server, which will have no idea it's not coming from a UI.
The option I see is to inject a header into the request from the UI, that indicates the origin of the request as the UI. This seems ripe for exploitation though.
Comment: Why do you want to restrict the user from accessing your API directly in the first place? They shouldn't be able to do anything using the API that they can't do in the application.
Comment: Completely agreed -- it's a bogus requirement. I think I will get a request to build it though so that eventually the user has to pay for the convenience of an API
Answer: To me, this is more of a networking question since its something I'd resolve at the network level.  If you run your backend application in a private network (or on a public network with firewall rules) you can configure the backend host to only accept communication from your Apache server.
That way the end-user can't connect directly to the API, since its not accessible to the public.  Only the allowed Apache server will be able to communicate with the backend API.  That way the Apache server acts as an intermediary between the end-user (client side) and the backend API server.
An example diagram from AWS.
Comment: Aside doing something like a captcha or behavioral analysis as "validation" of a user on the other end of the browser I don't know of another way.    This is an issue many company encounter when dealing with online fraud. For example, bypassing merchant checkout by doing direct POST of purchase data to automate testing validity of stolen credit card info.  So you can either try capthca or a behavioral monitoring script, or have some TOS policy to say you must use the UI and If you are able to detect users bypassing them, you ban them.
Comment: I think you mean to configure the backend server to only accept connections from the Apache server, not the UI, which is running on the client machines.
Comment: Maybe I am misunderstanding your answer, but right now, by design, all client requests from the UI are always proxied through Apache to the backend server via a path param in the url, like "myapp.com/proxy-to-apache/blah". There's really nothing to stop a user from figuring that out and proxying their calls to Apache, in which case, the server won't know where the call originated from.
Comment: Got it, so you literally want to force a user to interact using a web browser.  I thought you wanted to ensure the request was funneled through the Apache server, and not bypassed by hitting an exposed API.    Maybe we should take a step back. What are you trying to achieve by doing this?
Comment: Exactly @Cyph. So, it's a requirement I am getting from the business side.  Our app validates stuff and the business doesn't want it to be "too convenient" for the user to submit things to be validated. They are hoping to charge for that convenience.
Comment: Thank you -- I didn't think of things like captcha or behaviorial monitoring but it definitely applies to my use case.

TOS is probably the best, however, because even though I can make it difficult for them to hit the API directly, it really is more of a business agreement because the customer and the service provider.
Answer: You could make the backend server require connections to be authenticated before accepting any requests from them.  Then make it so only the Apache server can successfully authenticate in a way that end users cannot replicate.  For example, by using SSL/TLS between Apache and the backend, where the backend requires client certificates to be used, and then issue Apache a private certificate that the backend will accept.  Then end users will not be able to authenticate with the backend directly.


htaccess directory listing

Question: I'm trying to list files in one particular directory and with one particular ip. This htaccess file is located in that directory. So far, it seems that the hosting does not allow me to list directories. On localhost i can list everything in that directory, except the IndexIgnore ones, of course. The htaccess file content is:
Options +Indexes

<Limit GET POST>
order deny,allow
deny from all
allow from 22.214.171.124
</Limit>

IndexIgnore tabele_remote.php
IndexIgnore demo.txt
IndexIgnore functions.php
IndexIgnore config.php

Answer: It seems that AllowOverride directive is set somewhere previously
Also check there is no IndexIgnore * set on the parent directories or server entirely
Comment: It tries to list the directory, but there are no files. imageshack.us/f/857/capture1qv.jpg
Answer: change order deny,allow to order allow,deny and give it a try.
Also set AllowOverride all
Comment: May be they are also added to IndexIgnore somewhere previously, i.e. something like this IndexIgnore *.php  ?
Comment: IMHO there is only one way to fix impact of the indexignore directive, i.e. not to use it in a way like IndexIgnore *. Instead it is properly to use Options -Indexes. So you must either to change that yourself or contact server admin, if you disclosed that this is exactly your case. But I can not be sure 100%, that is not my realm
Comment: It tries to list the directory, but there are no files. http://imageshack.us/f/857/capture1qv.jpg/
Comment: You have files in that directory?
Comment: How do i remove the previously declared IndexIgnore *.php?
Comment: i have deleted the directive from the main .htaccess. Thanks!

htaccess directory listing


Compiling the compiler - how many times?

Question: If you compile a new version of compiler, how many times should you recompile it iteratively?
First: compile the new version of compiler[1] using the old version[0].
Second: compile the new version[2] using the newly compiled one[1], to apply new optimizations and fix bugs to the binary, not present in old[0] compiler.
Now third? Compile again, using [2] to remove any potential bugs that could have resulted from bugs in [1] as result of faulty compilation by buggy [0]...?
...but if you're paranoid, maybe the bugs introduced by [0] into [1] caused [2] to be somewhat buggy too...?
Does going beyond [2] make sense at all?
Answer: I'd stop when the result of compilation n is identical to the result of compilation n - 1; at that point you've reached steady state.
Comment: If this doesn't happen on the third version, there's probably a bug. The new compiler should produce the same output on own sources regardless of the version it was compiled with.
Comment: @Rafal: Agreed. @SF: Yes, comparisons would need to handle that sort of thing; not an uncommon requirement.
Answer: The instructions for bootstrapping OCaml invite you to continue until you have reached a fixpoint, if you wish. Assuming the new compiler only fixes bugs and does not introduce new ones, you may need to bootstrap several times to make self-inducing compiler bugs disappear.
You may also reach a fixpoint without the bug you were trying to fix being fixed, because the presence of the bug in the bootstrap compiler perpetuates it in the bootstrapped version (a sort of involuntary Ken Thompson). This happened at least once in the history of OCaml. When they noticed this, the developers fixed the assembly code by hand in order to obtain a correct compiler that translated correct source into a correct compiler.
Answer: Typically you should compile once withouth the standard library and get a partially working version of the compiler. Subsequently you need to recompile with the standard library support: this enables you to get further functionality (like printf checking and libgcc stuff).
I didn't know about subsequent recompilations, but thanks for the info :)


how to erase impossible variant from enum?

Question: The setting: In a web server, the business code needs to access the request payload, which is located in either query or body, but not both, the deserialization of query is handled by a trait Q, and the deserialization of the body is handled by the trait B != Q, a middleware, f, (a piece of code that sitting between the web framework and business code) is responsible for the invocation of Q and B according to the request method, if it is a GET, then invoke Q, if it is a POST then invoke B, thus the signature of f must be like f<Query: Q, Body: B>(...) -> Payload<Query, Body>, "must be" because somewhere in the implementation of f:
let payload = if request_method == "GET" {
    let query: Query = ...::deserialize(request_query);
    Payload::Query(query)
} else if request_method == "POST" {
    let body: Body = ...::deserialize(request_body);
    Payload::Body(body)
} else {
    // error
}

...

payload

(sadly, I didn't find a way to tell the framework to call f<Q> or f, nor a way to unify Q and B into a single trait)
In the business code, the handler for a GET would have the signature handler(Payload<Query, ()>) ... and a POST would have handler(Payload<(), Body>)
The question: is there some technique to erase the unit type from the payload without turning it into a trait (trait is difficult to work with)? (The real rationale for erasing the unit type is actually something else, but let's just say I want the unit type erased)
Edit: the meaning of "erasing" is to turn Payload<Query, Body> to Query or Body, i.e. handler(Payoad<(), Body>) would become handler(Body) - the "useless" unit variant of Payload<_, _> erased, resulting a enum with only one variant, essentially the "inner" itself.
Comment: Knowing more concretely what web server you're using and the exact types involved would be helpful. It sounds to me like there's better patterns available (at least in the web server frameworks I'm familiar with).
Comment: When you say "erase", what exactly do you mean? To me, we speak of "erasing" a type _parameter_ to make a single concrete type out of a generic one (usually via `dyn`), but `()` is a concrete type, not a type parameter, so I'm not sure what it would mean to erase it. Do you mean you want to end up with signatures in terms of `Payload` and `Payload` — one type parameter instead of two? Or something else? In particular, do you mean that you want the _variant_ effectively removed from the enum, like your question's title suggests? (That's doable)
Comment: @KevinReid Thanks for the comment, I've clarified the meaning of erasing in a edit, it's "end up with signatures in terms of Payload and Payload"
Comment: Perhaps this is personal opinion, but pointing the finger at how the "business logic" wants the parameter seems misguided. A function like `query_for_fish(query: FishType)` is a business logic function whereas the handling for `GET /fish?type=tuna` via some `handler(Payload)` is an *adapter* function. The adapter should be concerned with taking the `Query` and deserializing it into a `FishType` to hand off to the business logic. And at no point do you have to worry about unifying `Payload<(), Body>` and `Payload` types. But perhaps I'm still missing context.
Answer: Yes, there is a way to encode in Rust's type system that a variant of an enum can never be user. You have to use empty types (also called void types). One such type (two actually, but whatever) is already present in the prelude, it's the never type !. Since it's not completely clear about where you want to use it, I'll explain with the Result type.
Assume you have a trait which requires returning a Result<T, U> where the implementer of the trait can choose which T and U. For example, TryFrom:
struct A;
struct B;

impl TryFrom for B {
    type Error = ...;
    fn try_from(a: A) -> Result {
        Ok(B)
    }
}

In this example, it's clear that this conversion cannot fail. So what should I put in place of the dots? Often people put the unit type () there, thinking that is carries no information (because there is a single value possible of that type) so it's perfect for the job. However, this is not exactly what we wanted, right? There is actually a value of the type (), so this doesn't mean it's impossible to return Err(()). What we want instead is a type of which there are no values, because in that case we are sure it's impossible to return a value of that type. So the correct implementation would be
impl TryFrom for B {
    type Error = !;
    ...
}

In this case, there is even a RFC that proposes the following code to Just Work:
let Ok(b) = B::try_from(A);

This would be accepted, because the compiler knows it cannot be an Err(something), because then something: ! which is impossible.


Printing Issue: Google Maps w/ Directions

Question: I've embedded Google Maps API (with directions) onto a site I'm updating.  It works perfectly...until I try to print.  If I print to a PDF it's fine, but sending it to a printer generates nothing but 3 blank pages.  Here is my print.css:
<code>    #bg, #footer, #header, #enter-info, #driveit, #find, #leftcolumn, #print-button { visibility:hidden; }

#map_area{
    position:absolute;
    top:25px;
    left:120px;
    width:8.5in;
    margin:0 auto;
    clear:both;}

#directions{
    position:relative;
    left:25px;
    width:3.75in;}

#map_canvas{
    position:relative;
    float:right;
    right:25px;
    width:4in;
    min-height:500px;}
</code>
I thought this would be simple, but it's driving me crazy!
Any thoughts would be greatly appreciated.
EDIT: This question can be closed, as I've finally got it working.  The solution turned out to be adding "display:inline" to the wrapper div, and "display:block" to the directions and map divs.
Answer: The solution turned out to be adding "display:inline" to the wrapper div, and "display:block" to the directions and map divs.
Comment: That's not how you do it... you should add the solution *here* as an answer!
Comment: don't post an answer that's not an answer. Post an actual answer. -1.
Comment: I moved my solution down.  Hopefully, this now meets the requirements for posting.


What does the Reset Hub button on an Azure Virtual Hub do?

Question: Azure's Virtual Hub has a couple of buttons at the top: Reset Router and Reset Hub.
I've found some documentation on Reset Router here but so far cannot find anything on Reset Hub.

I'm trying to ascertain if Reset just means power-cycle/reboot; or if it clears all configuration / something like that.
I'm also trying to find out what the impact is on end users; i.e. do we lose all network connectivity whilst the reset is taking place (and if so, how long does a typical reset take), or is a new node brought up before the old one's taken down so that the reset is invisible to end users?

Additional Context
Note: Looking into this because all the route tables in our hub are no longer displaying in the portal & many commands which touch route tables fail / the cause seems to be that when anything touchs the defaultRouteTable (e.g. Get-AzResource -ResourceId 'id-of-the-default-root-table') we get a 503 Bad Gateway error; querying other route tables all works; but if we try to list them rather than querying specificly named route tables, we again get a 503... So we're wondering if the issue is something in the Azure Management Layer / if that may be resolved by a "reset".
The resources themselves are working correctly - so whilst there's an issue managing our Azure resources, users are currently unimpacted by any network issues.
We have an MS incident open for the above... so the question  abour Reset Hub is as much about curiousity as resolving the issue... We've asked MS the same, but our ticket's still in its first few hours, so it will likely be a few days (given the weekend) before it gets to someone who can answer this.
Comment: if solved, add your own comment as an answer and accept it 24h later on please
Comment: Update: MS have now shared this documentation: https://learn.microsoft.com/en-us/azure/virtual-wan/about-virtual-hub-routing#reset - which says that it brings the hub back to the correct provisioning state... Not yet clear whether this has any impact of this on existing connections / potential downtime...
Comment: Thanks @djdomi... so far I've got that link; but it doesn't say much on what to expect (i.e. it says that it brings the hub back to the correct provisoined state, but doesn't mention what impact this has on services relying on the hub (i.e. downtime)... When we try this for real, if there's been no better answers, I'll create an answer with feedback based on our real-world experience.
Answer: I found this in the docs what reset does
Hub reset
Virtual hub Reset is available only in the Azure portal. Resetting provides you with a way to bring any failed resources such as route tables, hub router, or the virtual hub resource itself back to its rightful provisioning state. Consider resetting the hub prior to contacting Microsoft for support. This operation doesn't reset any of the gateways in a virtual hub.
https://learn.microsoft.com/en-us/azure/virtual-wan/about-virtual-hub-routing#reset


How do I authenticate when calling an abp.io application REST Endpoint?

Question: I have a .Net Core application built with ABP.IO using the basic CLI. It exposes a swagger interface for basic user management and login etc. I can call any of the [Authorize]'d these end points from javascript once logged in or via Swagger OK. However this must be using some sort of authentication technique.
If I want to call the endpoints from  curl or from another application how do I authenticate and get an access_token etc.?
I can call the login methods but they just return success on successful login. Is there a way to get an auth token or something to be able to then make calls to end points that require authentication.
This seems like a very natural thing to do
Answer: If your application is built with angular version. Angular Home compenent have already imported OAuthService. You can call OAuthService.getAccessToken(), and may copy to clipboard etc.
<code>// this is already in template
get hasLoggedIn(): boolean {
    return this.oAuthService.hasValidAccessToken();
}

// you can add this to read bearer access token
get token(): string {
    return this.oAuthService.getAccessToken();
}
</code>
Answer: If it helps anyone else, I couldn't get the token via OAuthService, but I did get it via TokenService.
I injected it into the constructor and then called getToken()
<code>this.tokenService.getToken()
</code>


(C++) Como fazer um programa escrever em 2 arquivos diferentes?

Question: Fiz 2 tentativas, a primeira dá erro, e a segunda não escreve. poderiam me ajudar?
<code>#include<iostream>
#include<fstream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<cstdlib>
using namespace std;
int main()
{
    string linha;
    fstream fin ("ex2.txt");
    ofstream fout("ex2par.txt");
    ofstream fout("ex2impar.txt");
    if(fin.is_open())
    {
        while(getline(fin,linha))
        {
            int num = atoi(linha.c_str());
            if (num%2 == 0)
            {
                cout << "par " << num << endl;
                fout.open("ex2par.txt",ios::app);
            }
            else
            {
                cout << "impar " << num << endl;
                fout.open("ex2impar.txt",ios::app);
            }

        }
    }
}
/*int main()
{
    string linha;
    fstream fin("ex2.txt");
    ofstream par("ex2par.txt");
    ofstream impar("ex2impar.txt");
    if(fin.is_open())
    {
        while(getline(fin,linha))
        {
            int num = atoi(linha.c_str());
            if (num%2 == 0)
            {

                cout << "par " << num << endl;
                par.open("ex2par.txt");
            }
            else
            {

               cout << "impar " << num << endl;
                impar.open("ex2par.txt");
            }
        }

    }
}*/
</code>
Comment: Mas as mensagens você está enviando todas para o `cout`. Em que momento você realmente tentou escrever os textos nós arquivos?
Comment: Não entendi muito bem, no caso não seria na declarada do  ofstream par("ex2par.txt");
    e do ofstream impar("ex2impar.txt");, pois tentei os dois com FOUT mas deu erro, como na parte comentada
Answer: Boa noite.
Sobre a parte não comentada:
você criou 2 variáveis com o mesmo nome fout. Se vc. chamar a segunda de fout2 por exemplo não vai dar erro.
Quando vc. inicializa os streams com os nomes dos arquivos eles já vão se abrir. Pode tirar os comandos open.
Para escrever para os arquivos utilize as variáveis dos streams correspondentes e não cout. Por exemplo: fout << "par" << endl;
Veja se o código a seguir te ajuda:
<code>int main()

{

    string linha;

    fstream fin ("ex2.txt");

    ofstream fout("ex2par.txt");

    ofstream fout2("ex2impar.txt");

    if(fin.is_open())

    {
        while(getline(fin,linha))

        {

            int num = atoi(linha.c_str());

            if (num%2 == 0)

            {

                fout << "par " << num << endl;

            }

            else

            {

                fout2 << "impar " << num << endl;

            }

        }

    }

}
</code>


Bug em programação JQuery

Question: Boa noite! Estou com um problema na programação de um exercício, preciso remover estes "spans" dos campos que faltam no input, deixando apenas um que troca de acordo com a necessidade.

$(document).ready(function() {
    $("#validar").click(function() {
        $("input").each(function(index, element) {
            if ($(element).val() == '') {
                $("#validacao").append(element.id + "
");
            }
        });
    });
});
div {
    width: 40px;
    height: 40px;
    margin: 5px;
    float: left;
    border: 2px blue solid;
    text-align: center;
}

span {
    color: red;
}

<form>
    Nome
    <input type="text" id="nome">

    CPF
    <input type="text" id="cpf">

    RG
    <input type="text" id="rg">

    <input style="color: #0026ff" type="button" id="validar" value="Validar !" />

    Campos Inválidos

</form>
Answer: Tens de limpar o html desse campo antes de colocar de novo o que ainda está em falta. Usando $("#validacao").html('') apagas o conteúdo antigo.
Podes fazer isso assim:
$(document).ready(function() {
    var $validacao = $("#validacao");
    $("#validar").click(function() {
        $validacao.html('');
        $("input").each(function(index, element) {
            if (!element.value.trim()) {
                $validacao.append(element.id + "
");
            }
        });
    });
});

jsFiddle: https://jsfiddle.net/hmd7s2bw/

$(document).ready(function() {
    var $validacao = $("#validacao");
    $("#validar").click(function() {
        $validacao.html('');
        $("input").each(function(index, element) {
            if (!element.value.trim()) {
                $validacao.append(element.id + "
");
            }
        });
    });
});
div {
    width: 40px;
    height: 40px;
    margin: 5px;
    float: left;
    border: 2px blue solid;
    text-align: center;
}

span {
    color: red;
}

<form>
    Nome
    <input type="text" id="nome">

    CPF
    <input type="text" id="cpf">

    RG
    <input type="text" id="rg">

    <input style="color: #0026ff" type="button" id="validar" value="Validar !" />

    Campos Inválidos

</form>

Bug em programação JQuery


Is there a memory limit for a single .NET process

Question: We are currently thinking of building a cache-system to hold data pulled out of an SQL database and make it available to a couple of other applications (website, webservice, etc). We imagine the cache to be running as a windows service and basically consist of a smart dictionary which holds the cache entries. My question is, is there a limit to the working set of the application (it will be running under windows server 2003)? Or is the amount of physical memory the limit?
Comment: Consider your cache expiration policy before you write the first line of code. This is hard to bake in later.
I presume you have good reason to want to do this e.g. offline access. Performance is not a good enough reason, you may make perf worse through the memory overhead on the local machine.
Comment: actually, performance is one reason. the second one is that we want to centralize the cache to make it accessble by various on and offline applications. do you have experiences in building cache systems? can you recommend further reading?
Comment: The ASP.NET cache system may be a good place to get some ideas from, or maybe the caching application block: http://msdn.microsoft.com/en-us/library/cc309502.aspx
Answer: 32bit or 64bit? 32bit is 2gb (for a process), 64 bit is 1TB (enterprise edition 2003 server).
However, the maximum size of a CLR Object is 2gb even on 64bit.
Update: the information above was correct in 2008. See Ohad's answer for more recent information. Windows 2016 server can have a maximum of 24TB.
Comment: In my experience, even though the cap is theoretically 2 GB, the system will become unstable once you reach about 1.2 GB.
Comment: Actually, a 32bit process can have up to 3GB under an x86 OS and up to 4GB under an x64 OS. See my answer below or http://msdn.microsoft.com/en-us/library/aa366778%28VS.85%29.aspx#memory_limits
Comment: The large object limit happens quite frequently in numerical applications since data is often backed by arrays and arrays are a CLR object in .NET. The limit has been lifted in .NET 4.5. Finally!  http://www.centerspace.net/blog/large-matrices-and-vectors/
Comment: It's relevant for version 2.0 of the runtime, but I don't think that it has changed in 3.5. Having a single object of 2gb (unless it's a byte array) is fairly unusual anyway - in your case it would be a list of objects N size so you'd be ok.
Comment: The restrictions are the same in .NET 4 as well.
Comment: thanks for the read. it seems, that this post has been written prior to release of .net 2.0. i wonder, if there have been any changes in later versions.
Comment: @ChrisS please consider updating the answer about .Net memory limits with correct information - it is unlikely that correct post will rise from 10 points no to the top (and misleading numbers are not really nice for this quite popular Q&A).
Comment: @AlexeiLevenkov The information for the answer was right in 2008 - it's not incorrect just out-dated. I've added a link though
Comment: I think that Windows server limit of Physical ram has nothing to do with CLR limitations
Comment: I've found that I can use up to 62 Gb on Win 10 64 bit.
I've create 31 2Gb arrays. And them haven't consumed any actual RAM, on;y virtual space. but then app crashed.
Answer: I have recently been doing extensive profiling around memory limits in .NET on a 32bit process. We all get bombarded by the idea that we can allocate up to 2.4GB (2^31) in a .NET application but unfortunately this is not true :(. The application process has that much space to use and the operating system does a great job managing it for us, however, .NET itself seems to have its own overhead which accounts for approximately 600-800MB for typical real world applications that push the memory limit. This means that as soon as you allocate an array of integers that takes about 1.4GB, you should expect to see an OutOfMemoryException().
Obviously in 64bit, this limit occurs way later (let's chat in 5 years :)), but the general size of everything in memory also grows (I am finding it's ~1.7 to ~2 times) because of the increased word size.
What I know for sure is that the Virtual Memory idea from the operating system definitely does NOT give you virtually endless allocation space within one process. It is only there so that the full 2.4GB is addressable to all the (many) applications running at one time.
Comment: I can't confirm but according to my tests if really seems to be true.
Comment: In our case we are using .NET dll as a plugin to IE. We are also seeing IE throwing OOM exception at around 1.2 GB (when we use the plugin). @Luke Machowski, can you tell me which memory profiling tool are you using for .NET or IE?
Comment: @SandeepKhantwal It was a while ago but I was using the Ants Profiler at the time.
Answer: The following table from MSDN is the most precise answer to your query. Note that the IMAGE_FILE_LARGE_ADDRESS_AWARE flag cannot be set directly from the managed compiler, though fortunately it can be set post build via the editbin utility. 4GT refers to the /3gb flag.
Answer: On 32bit Windows you can get a bit more memory by booting Windows with the /3gb flag and flagging your app as "large address aware"
Comment: It's not that you get more memory in XP (i.e., more of that 4GB of RAM) it's that you can run a process up to 3GB of RAM http://msdn.microsoft.com/en-us/library/ms791558.aspx
Comment: Also don't use it with Virtual PC or Virtual Server http://blogs.msdn.com/virtual_pc_guy/archive/2004/12/23/331100.aspx
Comment: Anyone know how this works in 2008 server? i am assuming its still the same for the 32bit version.
Comment: @Matthias This technet blog: [Pushing the Limits of Windows: Virtual Memory by Mark Russinovich](https://blogs.technet.microsoft.com/markrussinovich/2008/11/17/pushing-the-limits-of-windows-virtual-memory/) has more information on this topic.
Answer: Matthias,
Not actually an answer to the direct question, but another way of approaching this problem which will get around some of the big pitfalls, which can be a major headache with caching solutions. (Sorry I don't have any recommended reading on the matter.)
We implemented this in a previous project, and it did create other problems.
For offline access, can you use sql express on the desktops to create a mirror of your database (or just the bit you need to cache)? Then all you need to do is switch which database your application is pointing to. You can even use it store diffs and replay these to the server - although this has other problems. You can alter the permissions on the local copy to make this one read-only if that's how it should be.
The dictionaries you are thinking of creating sound remarkably like Sql indexes. I would rely on sql to do the job for you if you can architect it that way. Why reinvent that wheel? If you do, you will have to think carefully about cache expiration and memory management - particularly if this is a windows service.
Good luck,
Sam
Answer: As with any other Windows program, you're limited by address space. That is: on 32-bit, you can have 2GB of address space. On x64, you can have 8TB.
If you don't have 8TB of physical memory, it will start to page.
Comment: And if you don't have 8TB of hard drive space available (I wish) then you'll start to get OutOfMemoryException's. Too bad. It'll be a while before many of us have that size HDD's in our development machines though. :(


Find Cartesian equation from Parametric Equations Including Sec and Tan

Question: Need to find the cartesian equation from:
$$ x = sec^2t - 1 , y = tan t, -\frac\pi2 \lt t \lt \frac \pi2 $$
With sin and cosine I use the unit circle, but I don't know what to do with sec and tangent. Any help would be greatly appreciated.
Answer: Hint :
$$\tan^2 t + 1 = \sec^2 t$$
Comment: I totally forgot about that identity... that gives me $ y = +- \sqrt x $ ... which is $ x = y^2   $ which is what is in the back of the book, many thanks
Answer: HINT:
$$\sec(x) = \frac{1}{\cos(x)}$$
$$\tan(x) = \frac{\sin(x)}{\cos(x)}$$
Comment: That's what I tried, and I ended up with $  y = xsint $  when it should be $ y = x^2 $ if I am not mistaken from looking at the back of my book
Comment: How did you solve for cos and sin, could you show me what you did?
Comment: Woops, the answer is $x = y^2$, I forgot about the tangent identity in the other answer