Joomla! displays the code of the template in a weird way

Question: So, I'm using latest Joomla 3.2 and template I created. This is the code from index.php:

            <div id="w_content_wrapper" class="<?php echo $active->alias; ?> ">

<jdoc:include type="modules" name="logo" style="xhtml" />

                        <jdoc:include type="message" />
                        <jdoc:include type="component" />
                        <jdoc:include type="modules" name="content" style="xhtml" />

<jdoc:include type="modules" name="sidebar" style="xhtml" />

<jdoc:include type="modules" name="quote" style="xhtml" />

<jdoc:include type="modules" name="user1" style="xhtml" />

<jdoc:include type="modules" name="user2" style="xhtml" />

<jdoc:include type="modules" name="user3" style="xhtml" />

<jdoc:include type="modules" name="user4" style="xhtml" />

<jdoc:include type="modules" name="copyright" style="xhtml" />

<jdoc:include type="modules" name="cookie" style="xhtml" />

<jdoc:include type="modules" name="additional" style="xhtml" />

The problem is, I created many category blogs and until yesterday they were all displaying correctly. But then I noticed than only one category blog is displaying totally incorrectly. What happenes is that

<jdoc:include type="modules" name="sidebar" style="xhtml" />

displays INSIDE

    <jdoc:include type="message" />
    <jdoc:include type="component" />
    <jdoc:include type="modules" name="content" style="xhtml" />

so I get something like this:

    <jdoc:include type="message" />
    <jdoc:include type="component" />

<jdoc:include type="modules" name="sidebar" style="xhtml" />

    <jdoc:include type="modules" name="content" style="xhtml" />

This is part of the code from Chrome browser:
https://drive.google.com/file/d/0BwXNqctc_x5dVUVwNXJ1NUlyNkU/edit?usp=sharing
I'm completely out of ideas here. I tried reuploading template, I created new menu items linked to this specific category blog. Problem doesn't go away. There is no problem with other blogs or if I just change the category of the blog inside same menu item. What am I doing wrong here?
Answer: Joomla blogs take the first part of the article up until the "readmore" separator.
Sometimes the readmore separator is placed in the editor inside a div, thus the intro Joomla extracts contains an unbalanced open <div which destroys your layout.   The browser does the rest of the issue trying to balance the open <div with the first corrensponding </div and ignoring the extra open div in the text.
Find the first item in the blog that displays wrong, open in the editor and place the readmore in the right place. You might have to clean the cache before you see the results.
Comment: There definitely is a problem with Readmore. However, I couldn't find the opened <div . I have found the Readmore causing the truble and I removed the article and created new one. Seems like it's working now! Thanks!
Comment: What may have happened is that somehow you split a div so that the open was before the readmore and the close was after it (and thus not displaying).


why do nginx process run with user nobody

Question: I was trying to setup nginx to run with one of my rails apps, when having a look at output for ps -e | grep nginx , I realised nginx worker processes run with user nobody.
Is there a reason why they are not running as www-data ?
Comment: Seems a reasonable question which led to an informative answer - why was the questioner dinged a point?
Answer:
Is there a reason why they are not running as www-data ?

Yes. You most likely haven't specified the user in your nginx config.
User Directive: http://nginx.org/en/docs/ngx_core_module.html#user
syntax: user user [group];
default:
user nobody nobody;
context:    main

How to run nginx as a particular user?
You can specify the user/group that nginx runs as, in the nginx config.
This is an example of what an nginx config might look like (notice the user directive):
pid                 /path/to/nginx.pid;
user                www-data www-data;
worker_processes    1;

events {
   worker_connections  1024; # usually 1024 is a good default
}

http {
   # more code goes here
}

Simply update your config and then reload or restart nginx and you should be good to go.
Of course you should choose the user that works best for your system, in Debian/Ubuntu there's a www-data by default, so that's a sensible choice.
Comment: www-data is to my understanding rather the owner/group of /var/www and it's not a good idea to use the same user for the nginx process (http://stackoverflow.com/questions/22336186/correct-apache-var-www-permissions)

A fresh installation of nginx via apt on debian uses the user nginx.

Maybe you'd want to change the example to using the nginx user.
Answer: The master process is run as root, then nginx will setuid()/setgid() to USER/GROUP. If GROUP is not specified, then nginx uses the same name as USER.
By default it's nobody user and nobody or nogroup group or the --user=USER and --group=GROUP from the ./configure script.
You can edit nginx.conf and set user to www www;


Relationship expressed by exponentiation

Question: I have a basic question, but, i don't really remember how to solve this kind of problem. I know the result must be $a = b$, but I don't know how to get there.

"Determine the relationship between a and b where a and b are natural
numbers that express the digit numbers of $x = 4 ^ {12} * 5 ^ {20}$ and $y =
 4 ^ {14} * 5 ^ {18}$ respectively."
Comment: Hint: $10=2 \times 5$
Answer: Note $4=2^2 \Rightarrow 4^n=2^{2n}$ and $2^m \cdot 5^m = (2\cdot 5)^m=10^m$
So
$$x=4^{12}\cdot 5^{20}=2^{24} \cdot 5^{20}$$
$$ =2^{4+20}\cdot 5^{20}=2^{4} \cdot 2^{20}\cdot 5^{20}$$
$$ =2^{4} \cdot 10^{20}=16\cdot 10^{20}$$
Thus $x$ has $2+20=22$ digits.
Similarly show $$y=2^{10}\cdot10^{18}=1024\cdot10^{18}$$
Then $y$ has $4+18=22$ digits.


Where and how can I find the layout files used by Android classes?

Question: Problem
The Android SDK classes refer to pre-defined layouts using resource IDs.
In my example, I am creating a custom Preference class and want to create a custom layout (including custom widgets) for that preference type. This all works fine, for example I can have a TextView displaying the preference title specified with android:title in XML (which is no custom attribute).
The problem is that I want the style of my custom layout to conform with the style used by the standard Android Preference classes. This includes for example the text size and style. I could simply try it out to find the matching style but I suspect that the style Android uses is general so that it would adapt with the general style of the app.
Approaches
I looked into the Preference class in the SDK and found that for the title it does the following:
TextView titleView = (TextView) view.findViewById(com.android.internal.R.id.title)

This hints that all the style is defined in a layout file. Now my question is: how to find this layout file? I wonder whether the resource id used here is enough, it looks so general that it might be even used for multiple purposes (that is, titles in other places than the Preference class). Is that the case?
To find the layout file, I looked for example in <android-sdk>/platforms/android-24/data/res/layout and it indeed contains some resources with names including "preference".
For example, the file preference_category.xml looks as follows:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    style="?android:attr/listSeparatorTextViewStyle"
    android:id="@+android:id/title"
/>

Here a title id is defined. Is that an id the above com.android.internal.R.id.title would refer to?
I can find further relevant layout files, where preference_child.xml looks quite promising:
<TextView android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

But still I would have to guess whether it is the file I am looking for. Thus the question is: How do I find the right layout file? There is not much documentation in the XML files. How does one in general find the layout files used at different places in the Android framework?
A related question (Where can I find default AlertDialog layout xml file? ) has an answer indicating that I looked at the right directory in the SDK. However, the answer does not tell how in general one proceeds to find the layout one is looking for.
The concrete case with a custom Preference
Relevant post: Android: Creating custom preference
In the linked answer the author suggests (by the given code) to create an own title TextView. I am wondering whether one can instead reuse the layout given by Android, keeping the TextViews for title and summary and just adding the own widget at the place noted in the XML, with id @android:id/widget_frame. Would that be possible without copying it and adapting it in a new layout file? The full file preference_child.xml from the Android SDK looks as follows:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingStart="16dip"
    android:paddingEnd="?android:attr/scrollbarSize">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="@dimen/preference_widget_width"
        android:gravity="center"
        android:orientation="horizontal">
        <ImageView
            android:id="@+android:id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="6dip"
        android:layout_marginTop="6dip"
        android:layout_marginBottom="6dip"
        android:layout_weight="1">

        <TextView android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

        <TextView android:id="@+android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignStart="@android:id/title"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="4" />

    </RelativeLayout>

    <LinearLayout android:id="@+android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="@dimen/preference_widget_width"
        android:gravity="center"
        android:orientation="vertical" />

</LinearLayout>

Answer: You can do it programmatically. First you need to get rootView of Activity, see here https://stackoverflow.com/a/4488149/2895571. Then you can try to findViewById() on that rootView.
Comment: @user905686 as far as I know it's not possible to override xml layout, so if one wants to modify it, it should be done programmatically. Just need to reference it and change it's properties
Comment: I don't see how this answers the questions. If you mean one could use a dummy widget to get the values from: This might be an approach but when working on the XML-level it would be better to use the actual SDK XML files.


If $\sin\alpha+\sin\gamma=2\sin\beta$, prove $\tan\frac{\alpha+\beta}{2}+\tan\frac{\beta+\gamma}{2}=2\tan\frac{\gamma+\alpha}{2}$

Question:
If
$$
\sin\alpha+ \sin\gamma = 2\sin\beta
$$
Prove that
$$
\tan\frac{\alpha+ \beta}{2}+ \tan\frac{\beta+ \gamma}{2} = 2 \tan\frac{\gamma+ \alpha}{2}
$$

Me and my teacher already tried so many times, but just got stuck every time no matter using sum to product or trying to change all the tangent into sin/cos.

My work:
I tried
$$
\sin\alpha -\: sin\:\beta+ \sin\gamma - sin\:\beta= 0 \\
\\
\cos\frac{\alpha+ \beta}{2} \sin\frac{\alpha- \beta}{2} + \cos\frac{\gamma+ \beta}{2} \sin\frac{\gamma- \beta}{2}= 0
$$
but it seems useless for proving the identities
and then I try to change the prove  into
$$
\frac{\sin\frac{\alpha+ \beta}{2}}{\cos\frac{\alpha+ \beta}{2}}+ \frac{\sin\frac{\beta+ \gamma}{2}}{\cos\frac{\beta+ \gamma}{2}}  = \frac{2\sin\frac{\gamma+ \alpha}{2}}{\cos\frac{\gamma+ \alpha}{2}}
$$
and it still have no clues to do.
Comment: @narip may not have noticed the factor of $2$ on the first equation's RHS.
Comment: @narip how  For $alpha=gamma=π/6  $         and $beta=pi/2 $   LHS= 1 but RHS =2
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Hint: Write the first equation as
$$\sin\alpha-\sin\beta=\sin\beta-\sin\gamma$$
and apply the difference-to-product identity. (What you've tried is essentially this, but I find that having the terms on opposite sides of the equation is helpful.) Rewrite the second equation similarly and see if you can manipulate it into a form that follows from the first equation.
Answer: Set $a = (\alpha + \beta)/2$, $b = (\beta + \gamma)/2$ and $c = (\alpha + \gamma)/2$. Then $\alpha = a - b + c$, $\beta = a + b - c$ and $\gamma = -a + b + c$.
With this substitution and applying the sum and difference identities, the first equation becomes
$$
2\cos(a) \cos(b) \sin(c) + 2\sin(a)\sin(b)\sin(c) = -2\cos(a)\cos(b)\sin(c) + 2\cos(a)\sin(b)\cos(c) + 2\sin(a)\cos(b)\cos(c) + 2\sin(a)\sin(b)\sin(c).
$$
Dividing both sides by 2 and grouping like terms, we have
$$
2\cos(a) \cos(b) \sin(c) = \cos(a)\sin(b)\cos(c) + \sin(a)\cos(b)\cos(c).
$$
Finally, dividing both sides of the equation by $\cos(a)\cos(b)\cos(c)$, we get $2\tan(c) = \tan(b) + \tan(a)$, which is the desired equation.


onRendered triggers Exception from Tracker afterFlush - function ReferenceError: dragula is not defined

Question: I am having trouble importing dragula correctly, using the ahref:dragula package. It works just fine, until I manually refresh the browser page. When I do, I get the following error :
debug.js:41 Exception from Tracker afterFlush function:
debug.js:41 ReferenceError: dragula is not defined
    at .<anonymous> (tasks.js:52)
    at blaze.js:3302
    at Function.Template._withTemplateInstanceFunc (blaze.js:3643)
    at fireCallbacks (blaze.js:3298)
    at .<anonymous> (blaze.js:3391)
    at blaze.js:1752
    at Object.Blaze._withCurrentView (blaze.js:2183)
    at blaze.js:1751
    at Object.Tracker._runFlush (tracker.js:505)
    at onGlobalMessage (setimmediate.js:102)

Reading around, I stumbled upon this question/answer, which makes me think the route might need a waitOn of some sort, I just don't get what exactly I should be waiting on. Following are a few pieces of my code I have cleaned up for readability, hopefully I didn't strip out any essential information. So, here is what my route definition currently looks like.
Router.route('/', function () {
  this.render('Home');
});

And the templates...
<template name="home">
  {{ #if currentUser }}
    {{> tasks }}
  {{ /if }}
</template>

<template name="tasks">

</template>

Finally, the onRendered function itself.
Template.tasks.onRendered(function() {
  this.drake = dragula([this.find('#activeTasks')]);
});

Answer: Based on this discussion, I have found a workaround that consists in wrapping by dragula definition in a Meteor.setTimeout function.
The resulting onRendered function :
Template.tasks.onRendered(function() {
  var self = this;
  Meteor.setTimeout(function() {
    self.drake = dragula([self.find('#activeTasks')]);
  }, 250);
});


What is the distribution of time's to ruin in the gambler's ruin problem (random walk)?

Question: In a gambler's ruin problem, where the gambler starts with a fixed amount of wealth. What is the distribution of times to ruin. That is, if each bet has a fixed payout.
As I understand it, this is a one dimensional random walk which stops when it hits zero. What is the distribution of steps taken to get to zero?
Comment: Is this what you're looking for? https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution#Relationship_with_Brownian_motion (continuous case)
Comment: Could you explain more about your difficulties? As, e.g., why the solutions provided in textbooks are not sufficient?
Comment: Could you reference a textbook provided solution? I've mostly seen distributions of wealth, but I'm interested in the CDF of the time to ruin which I've not seen.
Answer: Time-to-ruin in the discrete-time random walk: From your question, I take it that you are referring to a discrete-time version of the gambler's ruin problem.  Without loss of generality we can consider the wealth of the gambler denominated in units equivalent to the betting amount.  We will assume that the wealth of the gambler is a positive whole number of such units, and we denote the starting wealth as $w_0 \in \mathbb{N}$.  Then the time-to-ruin is defined as:
$$T \equiv \min \{ t \in \mathbb{N} | w_t = 0 \},$$
where the wealth follows the unit random walk process:
$$w_t = w_0 + \sum_{i=1}^t \Delta_i
\quad \quad \quad \mathbb{P}(\Delta_i = -1) = \mathbb{P}(\Delta_i = 1) = \frac{1}{2}.$$
The time-to-ruin is the "hitting time" for the state $w=0$ in this stochastic process.  You can determine the distribution of the time-to-ruin by looking at the distributions of the hitting times.  Here it is useful to appeal to a special result for random walks called the "hitting time theorem" (see e.g., Van Der Hofstad and Keane 2008 and Kager 2017), which shows that:
$$\mathbb{P}(T=t) = \frac{w_0}{t} \cdot \mathbb{P}(w_t = 0).$$
Below we will use this result to derive a useful distribution that is closely related to the distribution of the time-to-ruin.  The result is a discrete phase-type distribution, which is a type of distribution used to model the hitting time to the absorbing state of a Markov chain.

Deriving the distribution of the time-to-ruin: Looking at the nature of the random walk, it is easy to see that the time-to-ruin must occur somewhere over the support $t = w_0, w_0 + 2, w_0 + 4, w_0 + 6, ...$.  This is quite an intuitive result --- we need to have at least $w_0$ bets to lose the starting wealth, and any additional bets leading to ruin must come in pairs, each with one win and one loss cancelling each other out.  Thus, to facilitate our analysis, it is useful to work with the total number of winning bets in the time-to-ruin:
$$R \equiv \frac{T - w_0}{2},$$
which has support $r = 0,1,2,3,...$.  Now, applying the hitting time theorem above, we get:
$$\begin{align}
\mathbb{P}(R=r)
= \mathbb{P} \Bigg( \frac{T - w_0}{2} = r \Bigg)
&= \mathbb{P} ( T = w_0 + 2r )  \\[6pt]
&= \frac{w_0}{w_0 + 2r} \cdot \mathbb{P} ( w_{w_0 + 2r} = 0 ) \\[6pt]
&= \frac{w_0}{w_0 + 2r} \cdot \mathbb{P} \Bigg( w_0 + \sum_{i=1}^{w_0 + 2r} \Delta_i = 0 \Bigg) \\[6pt]
&= \frac{w_0}{w_0 + 2r} \cdot \mathbb{P} \Bigg( \sum_{i=1}^{w_0 + 2r} \mathbb{I}(\Delta_i=1) = r \Bigg) \\[6pt]
&= \frac{w_0}{w_0 + 2r} \cdot \text{Bin} ( r | w_0 + 2r, \tfrac{1}{2} ) \\[6pt]
&= \frac{w_0}{w_0 + 2r} \cdot \frac{(w_0 + 2r)!}{(w_0+r)! r!} \cdot \frac{1}{2^{w_0 + 2r}} \\[6pt]
&= \frac{w_0}{2^{w_0}} \cdot \frac{(w_0 + 2r - 1)!}{(w_0+r)! r!} \cdot \frac{1}{4^r} \\[6pt]
\end{align}$$
It is simplest to frame the gambler's ruin problem in terms of this distribution.  However, we can convert back to the distribution for $T$.  For any value $t = w_0, w_0 + 2, w_0 + 4, w_0 + 6, ...$ in the support for the time-to-ruin, we have:
$$\mathbb{P}(T=t) = w_0 \cdot \frac{(t - 1)!}{(\tfrac{t+w_0}{2})! (\tfrac{t-w_0}{2})!} \cdot \frac{1}{2^t}.$$

Implementation in R: We can program this density function using standard syntax for probability distribution as follows.  In this function the input t is a vectorised input for the time-to-ruin.  The function produces density values by default, but you can use the log input to produce log-densities instead.
druintime <- function(t, w, log = FALSE) {

  #Check inputs
  if (!is.numeric(t))           { stop('Error: Input t should be numeric') }
  if (!is.numeric(w))           { stop('Error: Input w must be a positive integer') }
  if (length(wealth) != 1)      { stop('Error: Input w must be a single value') }
  if (as.integer(w) != w)       { stop('Error: Input w must be a positive integer') }
  if (min(wealth) < 1)          { stop('Error: Input w must be a positive integer') }
  if (!is.logical(log))         { stop('Error: Input log must be a logical value') }
  if (length(log) != 1)         { stop('Error: Input log must be a single value') }

  #Compute number of successes in each time-to-ruin
  #and set indicators for integer values
  n   <- length(t)
  r   <- (t - w)/2
  IND <- (as.integer(r) == r)&(r >= 0)

  #Compute log-density
  LOGDEN <- rep(-Inf, n)
  LOGDEN[IND] <- log(w) - log(w + 2*r[IND]) +
                 dbinom(r[IND], size = w + 2*r[IND], prob = 1/2, log = TRUE)

  #Give output
  if (log) { LOGDEN } else { exp(LOGDEN) } }

Implementing this with starting wealth $w_0 = 6$ gives the following probability mass function.
#Compute probability mass function over a set of input values
t    <- 0:200
w0   <- 6
DENS <- druintime(t, w = w0)

#Plot the mass function
t.names <- rep(NA, length(t))
for (i in 0:20) { t.names[1+10*i] <- t[1+10*i] }
barplot(DENS, names.arg = t.names,
        main = 'Probability Mass Function for Time-to-Ruin', col = 'red',
        xlab = 'Time-to-Ruin', ylab = 'Probability')

Comment: great analysis! just a question - how would someone simulate random numbers from a "discrete phase type distribution"?
Comment: @user123945: One method is just to simulate the relevant Markov chain and use a ```while``` loop to get the relevant hitting times.  In some cases it is possible to get the spectral decomposition of the transition probability matrix for the chain and use this to derive an explicit formula for the distribution of the hitting times.  You can find an example of deriving and computing a distribution coming from a Markov chain in [O'Neill (2022)](https://link.springer.com/article/10.1007/s11009-022-09966-x) and [O'Neill (2023)](https://link.springer.com/article/10.1007/s11009-023-10053-y).
Comment: can you use the uniform distribution via the probability integral transformation .... and then simulate from this discrete phase type distribution?
Comment: I just tried using acceptance-rejection sampling - is this correct? https://stats.stackexchange.com/questions/636706/how-to-simulate-random-times-from-gamblers-ruin
Comment: @user123945: There are lots of ways you can potentially undertake your sampling.  To test whether you have programmed it correctly, generate a large sample from your method and compare the empirical distribution of the sample to the probability distribution you are trying to sample from.  With a large sample, the LLN ensures that these two should be close to one another, so if you have made a mistake you will be able to see it.
Comment: I tried to take inspiration from your work and derive the probability distribution of absorption times in markov chains. did I do this correctly? https://stats.stackexchange.com/questions/637986/deriving-the-distribution-of-markov-chain-times
Answer: Say your starting wealth is $W(0) = 6$ and we take 20 steps of the random walk, where a gambler has fifty-fifty probability to loose or win 1, then probability distribution for wealth looks like a (scaled and shifted) binomial distribution.

Obviously the cases with $W(20) \leq 0$ have gone bankrupt. But the amount of bankrupt gambler's is larger. Due to the symmetry of the steps — after hitting zero one is as likely to reach a certain positive value as a certain negative value — for every case of a gambler that is at a value below zero, there is an equivalent case that is above zero. To get to know the amount of gamblers that have still positive wealth we need to subtract that part. This is also called the reflection principle.
So we can model the cumulative distribution function for bankruptcy after $n=w(0)+2x$ steps as
$$F_{bankrupt}(n) = F_\text{binom}\left(\frac{n-w(0)}{2},n,p=0.5\right) + F_\text{binom}\left(\frac{n-w(0)}{2}-1,n,p=0.5\right)$$

n = seq(6,100,2)
yF = pbinom((n-6)/2,n,0.5)+pbinom((n-6)/2-1,n,0.5)
yf = diff(c(0,yF))
plot(n,yf, type = "h", lwd = 3, main = "probability distribution for \n bankruptcy after n steps if w(0)=6", ylab = "probability")

Comment: I tried to take inspiration from your work and derive the probability distribution of absorption times in markov chains. did I do this correctly? https://stats.stackexchange.com/questions/637986/deriving-the-distribution-of-markov-chain-times


Integral of $\int\frac{1}{1+2e^x}dx$

Question: It seems there are two ways to find the integral of this function $f(x) = \frac{1}{1+2e^x}$. In both paths I only do operations that I know are true, but for some reason one of them gives me the right answer and the next gives me a wrong answer.
This is how I did it:
$u = 1+2e^x$
$u-1=2e^x$
$du = 2e^x dx \implies dx=\frac{du}{2e^x}$
so
$$\int \frac{1}{1+2e^x} dx$$
will become
$$\int \frac{1}{u(u-1)} du$$
Using partial fractions, I turned this to
$$\int \frac{-1}{u}+\frac{1}{u-1}du$$
This leads to
$-\ln(u)+\int1/(u-1)du$
and this is where i face that crossroad. This approach leads me to the wrong answer:
$\int1/(u-1)du = \ln(u-1)$
gives me a final answer of
$ln(2e^x)-ln(1+2e^x)$ which is not the right answer.
However if I take this approach: (I unpack $u$ and $du$)
$\int1/(u-1)du \implies \int2e^x/2e^xdx \implies \int 1dx \implies x$
I end with this answer
$x-\ln(1+2e^x)$ which is the right answer.
But i can't see a reason that makes my first approach yield the wrong answer. Can someone please tell me why is this happening? Thanks
P.S sorry about the bad formatting i'm not that savvy with MathJax
Comment: The first answer you give differs from the second by a constant. They are the same.
Comment: Even the second answer is wrong. Any indefinite integral written without a constant of integration is wrong. If you append constants of integration (label them differently as they can -and do- take on different values), then both answers become right and equally valid.
Answer: Both answers are kind  of right, but a little wrong. Note that $\ln(2e^x)=\ln 2+x$, so the two answers differ by a constant. Thus their derivatives are the same, they are both antiderivatives of $\frac{1}{1+2e^x}$.
Both answers should have an arbitrary constant of integration.
Answer: Hint :
Put $2u+3=1+2e^x$. Then you will not make mistakes !
Answer: An easier solution:
$\int \frac{1}{1+2e^x}-1+1dx=\int \frac{-2e^x}{1+2e^x}+1dx=x-\int \frac{1}{1+2e^x} d(1+2e^x)=x-\ln|1+2e^x|=x-\ln(1+2e^x)$.

Integral of $\int\frac{1}{1+2e^x}dx$


node.js + json formatting

Question: In my node app i have an object array, i have to construct another array based on this object array.
Consider my object array as:
{ Maximum:
   [ { xxxx: 1,
       yyyy: 6.52,
       zzzz: 1154982,
       aaaa: 1,
       bbbb: 13.55,
       cccc: 4646732,
       dddd: 3776276 } ],
  Minimum:
   [ { xxxx: 0,
       yyyy: -6.65,
       zzzz: 1,
       aaaa: 0,
       bbbb: -15.01,
       cccc: 1,
       dddd: 0 } ] }

My result should be like this:
level2:{
   keys:{
     xxxx:{max:1,
           min:0},
     yyyy:{max:6.62,
           min:-6.65},
     .....
  }
}

OR THIS FORMAT:
level2:{
       keys:{
         {     key:xxxx,
               max:1,
               min:0},
         {     key:yyyy
               max:6.62,
               min:-6.65},
         .....
      }
}

EDIT:
{
    "keys": {
        "xxx": {
            "max": 1,
            "min": 0
        },
        "yyyy": {
            "max": 6.52,
            "min": -6.65
        },
        "zzzz": {
            "max": 1154982,
            "min": 1
        },
        "aaaa": {
            "max": 1,
            "min": 0
        },
        "bbbb": {
            "max": 13.55,
            "min": -15.01
        },
        "cccc": {
            "max": 4646732,
            "min": 1
        },
        "dddd": {
            "max": 3776276,
            "min": 0
        }
    }
}

but i need:
    "356"{
    "level2":{
        "keys": {
            "xxx": {
                "max": 1,
                "min": 0
            },
            "yyyy": {
                "max": 6.52,
                "min": -6.65
            },
            "zzzz": {
                "max": 1154982,
                "min": 1
            },
            "aaaa": {
                "max": 1,
                "min": 0
            },
            "bbbb": {
                "max": 13.55,
                "min": -15.01
            },
            "cccc": {
                "max": 4646732,
                "min": 1
            },
            "dddd": {
                "max": 3776276,
                "min": 0
            }
        }
    }
}

My ultimate aim to combine max and min value.Help to solve this.Thanks in advance...
Answer: var json = { Maximum:
   [ { xxxx: 1,
       yyyy: 6.52,
       zzzz: 1154982,
       aaaa: 1,
       bbbb: 13.55,
       cccc: 4646732,
       dddd: 3776276 } ],
  Minimum:
   [ { xxxx: 0,
       yyyy: -6.65,
       zzzz: 1,
       aaaa: 0,
       bbbb: -15.01,
       cccc: 1,
       dddd: 0 } ] }
;
level2 = {keys:{}};

for (i in json.Maximum[0]) {
    console.log(json.Maximum[0][i], i);
    level2.keys[i] = {
        max: json.Maximum[0][i],
        min: json.Minimum[0][i]
    };
}

Comment: +1 for your valuable time..
Comment: I'm sorry, I can not understand what is wrong with the answer I posted.
Comment: just nest it inside another object console.log({"356":level2,})
Comment: that 356 is dynamic...How can i assign it dynamically.. i tried it..i can't acheive it..can u please modify the code..
Comment: r u there??????????????
Comment: var someobject = {};
someobject[my_dynamic_number] = level2;
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/50668/discussion-between-thorsummoner-and-subburaj)

node.js + json formatting


Golden functions?

Question: If one seeks the functional solutions of $f^2(x)=f(x)+1=f(f(x))$
Are they called 'golden functions' ?
Are they always of the form of rational functions ?
Comment: Just curious: wouldn't it be more logical to call something like $f^{\circ2}(x)=f^{\circ1}(x)+f^{\circ0}(x)$ a "golden function"? *(Which would then be $f^{\circ2}(x)=f(x)+x$ )*
Answer: At least on the (unbounded and infinite!) set $\operatorname{im}(f)$, we see that $f(t)=t+1$. Hence the only rational function solution is just $f(x)=x+1$.

In fact, the following will describe all solutions $f\colon \Bbb R\to\Bbb R$ of the functional equation
$$ \forall x\in \Bbb R\colon f(f(x))=f(x)+1$$
Pick a non-empty set $A\subseteq \Bbb R$ that is closed under "$+1$". In other words, we have $A+1\subseteq A$, or  $A$ can be written as $A=\bigcup_{a\in A_0}(\Bbb N+a)$.
Let $g\colon \Bbb R\setminus A\to A$ be arbitrary and define
$$ f(x)=\begin{cases}x+1&x\in A\\g(x)&x\notin A\end{cases}$$
Indeed, with such $f$, we have $f(x)\in A$ for all $x$ and hence $f(f(x))=f(x)+1$.
Here's a non-trivial example of a smooth such function:
$$ f(x)=\begin{cases}x+1&x\ge 0\\x^2+x+1+e^{1/x}&x<0\end{cases}$$
Comment: I see what went wrong; I wrote a Moebius transformation $\frac{ax+b}{x + d},$   identities showed $b=ad$ so it is actually constant. But your linear map would  appear as denominator constant in a Moebius function
Comment: I tried rational functions but got stuck on a cubic

Golden functions?


Simultaneonus NX client connections

Question: I would like to have two separate NX connections for the same username going from one dual-monitor client to NX server. The idea is to get two separate same username KDE sessions. When I try to do it the most obvious way (by starting one NX client on each separate monitor), second connection just over takes the first one. Any idea on how to do this?
Answer: Create an alias username in /etc/passwd and /etc/shadow (using the same $HOME and $SHELL and password).
But be aware that 2 parallel KDE sessions may still be creating conflicting settings in $HOME/.kde* files -- so this may not work well (but that wouldn't be an NX/FreeNX problem per se...).

Simultaneonus NX client connections


O que é o conceito de inteiros assinados em uma linguagem de programação?

Question: Gostaria de esclarecer o significado do termo "inteiro assinado".
Estou  pesquisando sobre protocolos,  para construir um em Java, e vez por outra encontro o termo. Não sei do que se trata.
Sempre ouvi falar em tipos primitivos , por exemplo em Java: int, float, double, ...
Mas pra mim o termo é novo!
Por que se diz que Java "não tem" os tais inteiros não assinados?
E qual a diferença entre um "inteiro assinado " e  um "inteiro não assinado"?
Comment: Acredito que java tenha sim os inteiros assinados, o que não tem são os inteiros não assinados.
Comment: Precisa que melhore algo? Acha que pode aceitar agora?
Answer: Se por inteiro assinado está querendo dizer inteiro assinalado, é o tipo normalmente usado no Java. O número possui um bit para indicar se ele é positivo ou negativo.
Muitas linguagens possuem tipos sem sinal onde este bit não é considerado, por isso só guarda números positivos, mas pode ir até o dobro do mesmo tipo com sinal. Java não é uma dessas linguagens. Eles consideraram que isso é uma simplificação na linguagem.
Até faz algum sentido porque é comum as pessoas usarem ele errado e em poucas situações eles são necessários em aplicações de alto nível. Porém onde é preciso não pode usar, se precisar interoperar com código externo terá dificuldades.
Em C#, por exemplo existe o ushort (vai até 65535), uint (até 4294836225) ulong (até 18445618199572250625), sendo que o byte (até 255) já é não sinalizado, e o sbyte é que usa um sinal.
Então o sinal descrito aí é o + ou -.
Coloquei no GitHub para referência futura.


How to add text to html files generated by Python Bokeh

Question: How do I add text to the HTML files for plots that are generated by bokeh.  I don't see any API for specifically writing text on the files.  All you can do is make plots.
Answer: There are alot of ways to embed Bokeh plots in other documents. For static documents, you can have Bokeh create its standard default document, or you can have it use a template you provide. You can also generate just the div and script tags and then embed those in your own static pages or web-apps however you like. Any of the above can also either have the data in the document, in a sidecar .js file, or loaded from a Bokeh server. All these options are described in the user guide section on embedding:
http://docs.bokeh.org/en/latest/docs/user_guide/embed.html
and in the reference guide:
https://docs.bokeh.org/en/latest/docs/reference/resources.html
Please let us know if there is more or better information we could add there.
Comment: More/better information would be  a minimal working example of a useful template that can be used with bokeh.
Comment: A [GitHub issue](https://github.com/bokeh/bokeh/issues) is the best place to make sure a suggestion is not lost. There are examples of all the different embed function under the `examples` directory in repo, FWIW.
Answer: I wanted to add some description to my graphs so people could understand some complex and domain specific terms and embedding plots/data into HTML documents seemed complex.
If all you want to add to graph is a simple text go ahead with this.
Documentation states that

Warning
The explicit purpose of these Bokeh Models is to embed raw HTML text for a browser to execute. If any portion of the text is derived from untrusted user inputs, then you must take appropriate care to sanitize the user input prior to passing to Bokeh.

Copying examples from above link for quick reference and in case link gets broken.

    from bokeh.io import output_file, show
    from bokeh.layouts import widgetbox
    from bokeh.models.widgets import Div
    from bokeh.models.widgets import Paragraph
    from bokeh.models.widgets import PreText

    output_file("div.html")

    pre = PreText(text="""Your text is initialized with the 'text' argument. The remaining Paragraph arguments are 'width' and 'height'.""",width=500, height=100)

    p = Paragraph(text="""Your text is initialized with the 'text' argument. The remaining Paragraph arguments are 'width' and 'height'""", width=200, height=100)

    div = Div(text="""Your HTML-supported text is initialized with the text argument.  The remaining div arguments are width and height. For this example, those values are 200 and 100 respectively.""", width=200, height=100)

    show(widgetbox(pre, p, div))

Comment: I believe this should be marked as the answer of this question.
Answer: Here is an example for generating a single HTML file with both panads DataFrame and a Bokeh Plot.
(Inspired from https://github.com/bokeh/bokeh/blob/master/examples/embed/embed_multiple.py)
import io
import pandas as pd
from bokeh.embed import components
from bokeh.models import HoverTool
from bokeh.models import LinearAxis, Range1d
from bokeh.plotting import figure
from bokeh.resources import CDN
from jinja2 import Template

template = Template(
    '''<!DOCTYPE html>

                <meta charset="utf-8">
                <title>Overview</title>
                {{ resources }}
                {{ script }}

                    {{ table }}

                    {{ div }}

        ''')

df: pd.DataFrame = get_data_frame()
table_html = df.to_html()

plot = figure(x_axis_label='time', y_axis_label='value', x_axis_type='datetime',
                plot_width=1600, plot_height=800,
                tools='pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,save,hover,tap')
plot.sizing_mode = 'scale_width'
# now continue setup your plot
# ...
#

# get bokeh parts
script_bokeh, div_bokeh = components(plot)
resources_bokeh = CDN.render()

# render everything together
html = template.render(resources=resources_bokeh,
                       script=script_bokeh,
                       table=table_html,
                       div=div_bokeh)

# save to file
out_file_path = "test.html"
with io.open(out_file_path, mode='w') as f:
    f.write(html)


Can't create a list of elements linked by a "Parent"

Question: I'm trying to create a method (using the *A** algorithm) that solves a puzzle and returns the steps to that solution. The solution it's easy.. but I can't return the path to that.
I used a list of Nodes and then every time a push back a new Node I set the parent pointing to the Node which new came;
list<Node> opened;
list<Node> closed;

Node current;

opened.push_back(start);

while( opened.size() !=0 )
{
   current = getLowestCostPath(opened);

   if(IsSolution(current) == true)
       return opened;

   opened.remove(current);

   if( !Has(closed, current))
          closed.push_back(current);

   for( int i = 0; i < static_cast<int>(current.GetBoard().capacity()); i++ )
   {
   xx = current.GetBoard()[i].X();
   yy = current.GetBoard()[i].Y();

       for(int j = 0; j < static_cast<int>(current.GetBoard().capacity()); j++)
       {
            if( isMovable(current))
            {
                //if found a new node
                Node newNode = Node(newBoard);
                Node *t = &current;

                if(!Has(opened, newNode ) && !Has(closed, newNode ) )
                {
                   newNode.SetParent(t);
                   opened.push_back(newPath);
                }
            }
        }
    }
}

(..)

the class Node it's just this
class Node{

public:
   std::vector<Point> board;
   Path *parent;

   Node();
   Node(std::vector<Point> board)

   virtual std::vector<Point> GetBoard() const;
   virtual Path* GetParent() const;
   virtual void SetParent(Node *p);

Node::Node(): board(),parent(NULL)
{
}

std::vector<Point> Node::GetBoard() const
{
return board;
}

void Path::SetParent(Node *p)
{
    this->parent = p;
}

Path* Path::GetParent() const
{
    return parent;
}

But then I realized that I can't BUILD the path to solve the puzzle...
I can't even see a single Parent board...
for( list<Node>::iterator it = goal.begin(); it != goal.end(); it++)
{
    if( (*it).GetParent() != NULL ){
        cout << "writing a board" << endl;
        mas::WriteLine( (*it).GetParent()->GetBoard() , "\n");
    }
}

I've searched all over the internet and I can't realize what am I doing wrong :(

I also tried this but it makes VS2005 Crash.
//goal it's the opened list that the method Solve returned....
for(std::list<Node>::iterator it = goal.end(); it->GetParent() != NULL; t->GetParent())
{

    std::cout << "step" << std::endl;
    mas::WriteLine((*it).GetBoard(), "\n");
}

I'm trying to be more clear and objective. So... see this parts
current = getLowestCostPath(opened);

The value returned by the method getLowestCostPath came from:
Node Solution::getLowestCostPath( std::list<Node> l)
{
    std::list<Node>::reverse_iterator min = l.rbegin();
    int value = 0;
    for(std::list<Node>::reverse_iterator it = l.rbegin(); it != l.rend(); it++)
    {
        if( value < (*it).GetStep())
        {
            min = it;
            value = (*it).GetStep();
        }
    }
    return *min;
}

after that... on the method Solve.. there is this part of the code
//if found a new node
Node newNode = Node(newBoard);
Node *t = &current;

newPath.SetParent(t);

I think that the ERROR it's on this part, newPath it's pointing to t when it should be pointing to node on the list opened
Is it true? If it is.. how can I fix this?
Answer: your volume of code require deeper investigation, but basically what i see that you trace back your way incorrectly. assume n is your final node. then return back like this
for (; n->GetParent() != NULL; n = n->GetParent())
  //do something on each node

after this executes n will be the initial node
Comment: i tried this... but it makes the VS2005 crash.

for(std::list::iterator it = goal.end(); it->GetParent() != NULL; it->GetParent())
{

 std::cout << "step" << std::endl;
 mas::WriteLine((*it).GetBoard(), "\n");

}
Comment: @DanceDisaster: list::end() points one behind the last element of the list. Dereferencing it is undefined behaviour.
Comment: @DanceDisaster: just use the code i wrote and copy-paste errors.
Comment: std::list::iterator it = --goal.end();
mas::WriteLine( it->GetBoard(), "\n");

Using this code I can print the last Node, but I says tha it->GetParent() it's NULL... so the set of the Parent it's wrong!
Comment: I think that t it's pointing to current... when it should be pointing to the element on the list (which current it's assigned to)... Is this true? I need a little help, please!
Comment: i don't understand your comments, sorry. please try to explain them
Comment: My error it's probably on setting the parent. On this particular part of the code:  Node newNode = Node(newBoard); Node *t = &current     I think I'm pointing to an temporary variable when it should be pointing to a value on the list open. Is it more clear now? sorry!
Comment: I am going to write an answer... I'm sure it will be more clear.


Transformar um conteúdo em uma imagem

Question: Estou criando um projeto em Windows Forms para ajudar a minha empresa à gerar assinaturas de email automatizado para nossos colaboradores.
Eu tenho no caso um windows forms único que contém um Tab Control, com Dados e Preview. Na tab preview existe um PictureBox com algumas Labels por cima dela que é onde será inserido os dados do colaborador.
Minha pergunta é, como eu posso fazer com que seja salvo o conteúdo inteiro dessa tab Preview em uma imagem? (.jpg, .png, etc)
Segue imagens de exemplo abaixo:
Comment: Caso o cliente de e-mail seja o outlook: Já pensou em desenvolver um plugin para o outlook? Ao fazer isso é possível alterar a assinatura do remetente (em texto).
Comment: Não é para outlook.. E sim, já havia pensado dessa maneira se fosse o caso. :(
Comment: Aqui na empresa tem um sistema semelhante, onde a assinatura é gerada em HTML. Ao gerar a assinatura abre o navegador e o usuário usa o CTRL + A e o CTRL + C para copiar e colar na assinatura do e-mail.
Answer: Uma maneira seria usar os classes Bitmap e Graphics para fazer um screenshot. Não testei e nem sei se vai funcionar, mas segue um código que mostra um exemplo de como fazer screenshot de todo o seu desktop - talvez possa adaptá-la a tirar só da sua programa:
//Criar um novo bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

// Criar um objecto de graphics do bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

// Tira a screenshot do canto superior esquero até o canto inferior direito
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                            Screen.PrimaryScreen.Bounds.Y,
                            0,
                            0,
                            Screen.PrimaryScreen.Bounds.Size,
                            CopyPixelOperation.SourceCopy);

// Salvar o screenshot na pasta desejada
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);

Inspirado por essa resposta do SOen.

Transformar um conteúdo em uma imagem


Firebase OTP verification without signin in android

Question: How to send an OTP through firebase and verify it without signing in?
Like normally, the firebase receives the otp and calls the signInWithPhoneNumber and sign's in to firebase.
I don't want to sign in with that method.
I just want to get the otp from firebase and verify if It is correct or not and perform my custom operation if it is correct.
Thanks in advance.
Alternatively, I need to use otp for my custom verification. Suggest me any other methods to verify if the otp is correct or not(SMS).
Comment: have a look [at this](https://firebase.google.com/docs/auth/android/phone-auth)
Comment: as per documentation it seems like we cannot verify number without signing in. one thing you can do sign out user from firebase auth just after signing in
Answer: After receiving OTP call verifyPhoneNumberWithCode(String mverificationId, (Received OTP))
<code>private void verifyPhoneNumberWithCode(String verificationId, String code) {
                if(code.equals(mResendToken)&&verificationId.equals(mVerificationId)){
            ............
            ............
            //do your work
            ............
            ............
        }
        else
            Toast.makeText(this,"Please provide correct OTP",Toast.LENGTH_SHORT).show();
}
</code>
Comment: While this code snippet may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) helps to improve the quality of your response. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.


Find all pairs of primes $p,q$ such that $pq \mid 2^p +2^q$

Question: Find all pairs of primes $p,q$ such that $pq \mid 2^p +2^q$.
My attempt  : When either one of them is $2$ then easy case checking gives me set of solutions. But what happens when neither of them is $2$?
Answer: A slight tune up to the argument presented in Prometheus' answer (currently deleted, but hopefully soon fixed and undeleted) proves that there are no solutions such that $p$ and $q$ are both odd primes.
Lemma. Assume that $p$ is a prime factor of $2^{2^ts}+1$ where $t,s$ are positive integers, $s$ odd. Then
$$
p\equiv1\pmod{2^{t+1}}.
$$
Proof. Let $m$ be the order of the residue class of $2$ in $\Bbb{Z}_p^*$.
Because $p\mid 2^{2^ts}+1$, we have $2^{2^ts}\equiv-1\pmod p$, and consequently $2^{2^{t+1}s}\equiv1\pmod p$. This means that $m\mid 2^{t+1}s$ but $m\nmid 2^ts$. Therefore we can conclude that $2^{t+1}\mid m$. But by Lagrange's theorem $m\mid p-1$, so the claim follows.
The rest is easy. Without loss of generality we can assume that $2<p<q$ (the case $p=q$ is obviously impossible). Write $q-p=2^ts$, $s$ odd. The assumption is that
$$
pq\mid 2^p+2^q=2^p(2^{q-p}+1).
$$
This implies that both $p$ and $q$ should be factors of $2^{q-p}+1$. But the Lemma then implies that
$$
p\equiv q\equiv 1\pmod{2^{t+1}}.
$$
This means that $q-p$ is divisible by $2^{t+1}$ contradicting the fact that $s$ is an odd integer by design.
Comment: I didn't understand when you said that $2^{t+1}\mid m$ and $q−p=2^ts$. Could you explain me please?
Comment: @Vmimi $q$ and $p$ are both odd, so there exists a positive integer $t$ and an odd integer $s$ such that $q-p=2^ts$. If $p$ is a factor of $2^p+2^q$ it must also be a factor of $2^{q-p}+1$. The Lemma then says that $p\equiv1\pmod{2^{t+1}}$. Similarly, the Lemma implies that also $q\equiv1\pmod{2^{t+1}}$. But then $q-p$ is divisible by $2^{t+1}$. A contradiction.
Comment: I got that part but what about when you say that $2^{t+1}\mid m$?
Comment: @Vmimi 1) $m$ is a factor of $2^{t+1}s$. 2) $m$ is not a factor of $2^ts$. Therefore $2^{t+1}$ must be a factor of $m$?
Answer: A little late, but here's an alternative solution.
We claim that the only solutions are $(2, 2)$, $(2, 3)$, and $(3, 2)$. Checking, these indeed work.
Suppose at least one of the two primes is $2$---let it be $p$. Then, $2q \mid (2^q + 4)$. So, $2^q \equiv -4 \pmod{q}$. By Fermat's Little Theorem, $2^q \equiv 2 \pmod{q}$, so $q \mid 6$. Thus, $q = 2$ or $q = 3$, both of which work.
Now, suppose both primes are odd. By Fermat's Little Theorem, $2^p \equiv 2 \pmod{p}$, so since $2^p + 2^q \equiv 0 \pmod{p}$, then $2^{q - 1} \equiv -1 \pmod{p}$. Let $r = \operatorname{ord}_p(2)$. Since $2^{2(q - 1)} \equiv 1 \pmod{p}$, then $r \mid 2(q - 1)$, but $r \nmid (q - 1)$. Since $q - 1$ is even, this implies that $r = 2k$ where $k$ is some factor of $q - 1$ such that $\nu_2(k) = \nu_2(q - 1)$. By Fermat's Little Theorem, $2^{p - 1} \equiv 1 \pmod{p}$, so $\operatorname{ord}_p(2) = 2k \mid (p - 1)$. Since $\nu_2(2k) > \nu_2(q - 1)$, this implies that $\nu_2(p - 1) > \nu_2(q - 1)$. Similarly, we can show that $\nu_2(q - 1) > \nu_2(p - 1)$, contradiction.


VBa to clear all activex checkboxes in Word document

Question: I'm trying to create a button to clear all the activex check-boxes in a .docm file, but nothing seems to work. I saw many posts in the fórum, but none seems to work. Can anyone help me? Obs.: the original file have at least 30 check boxes and I don't want to type all the check-boxes names.
See the code below and the example file attached
Ps.: I tried ThisDocument.Fields; Me.Control and many others.
See attached image as example: ActiveX CheckBox
Private Sub CommandButton1_Click()
Dim Ctl As MSForms.Control

    For Each Ctl In ThisDocument.FormFields
        If Ctl.Name = "CheckBox" Then Ctl.Value = False
    Next Ctl
End Sub

Comment: I found this: https://www.extendoffice.com/documents/excel/4302-excel-uncheck-all-checkboxes.html
Comment: Thanks for the reply, but that code is for Excel, and I'm working with Word.
Comment: You need to specificy what kind of checkboxes are used in the document. Word has at least four different possibilities. What commands were used to create these checkboxes?
Comment: I only know 2 forms of check-boxes (sorry for my lack of knowledge), but is an ActiveX Check-box (see image attached). I'm sorry but didn't find a way to attached the file.
Answer: After many tests, the code below solved my problem:
Private Sub Limpar_Click()
Dim iShp As InlineShape
For Each iShp In ActiveDocument.InlineShapes
  If iShp.OLEFormat.ClassType = "Forms.CheckBox.1" Then
                iShp.OLEFormat.Object.Value = False
            End If
    Next
End Sub


QTP doesnot run in another screen resolution, any suggestions?

Question: QTP which access an application object in test PC screen resolution doesnt access the application window object in laptop? any suggestions to resolve this?
Answer: I also do not understand the question, but it may well be a resolution problem: Try looking at the answer to Mercury Quick Test Pro and Virtual machines: Works from one client machine but not another.
Comment: this is the same issue which i am facing
Answer: Do you have your code have many statements which involve coordinates?
If they involve coordinates then it is most likely that code will fail. If not post a code snippet here such that we can analyze it.
Comment: Hi, Welcome to stackoverflow.
Just to let you know this should really be posted as a comment, not an answer.
Answer: Don't really understand what you mean.
Just know at work we are using QTP and we don't really like it for many reasons...
You'd better give a try to Selenium it's a powerful tool :)
Answer: hey if u are automating web application then change ur resolution to 100%. If its more or less than 100% then qtp scripts will fail.
<code>                                   OR
</code>
An alternative solution, we can go for third party tool like Qres and MultiRes. These tools can be operated using QTP at runtime.
 So far I have not found a code for changing screen resolution at runtime using vb script. If anyone finds that, please post it.


When $a^2x^2+2bx+c$ is a perfect square?

Question: Is there any fast and easy method to find out $a^2x^2+2bx+c$ is a perfect square for some $x\in\mathbb{Z}$, i.e, when there is a $x,y\in\mathbb{Z}$ such that
$$
a^2x^2+2bx+c=y^2
$$
where $a,b,c$ are given integers?
P.S.:
My question has two parts:
First decide if it is perfect square or not
Second fast and easy method to find $x,y$.
Thanks!
Comment: Wops nevermind sorry.
Comment: @stenvikteam Did you read the question?
Comment: @Arthur, Sure, as it is the discriminant of the usual method in solving quadratic equation, and in this question it is a necessary but not (unfortunately) a sufficient condition.
Comment: you want x which makes this term a perfect square for all $a$, $b$, $c$?
Comment: @Sil You're right. I really meant $4b^2-4a^2(c-y^2)$ needs to be a perfect square (i.e. there needs to exist a $y$ so that it becomes a perfect square), because that's the actual discriminant. In your example, $y = 1$ gives $16$.
Answer: I can't answer you full question but I may give you a way.
Were can write $a^2x^2+2bx+c$=$$(ax)^2+2ax(\frac {b}{a})+(\frac {b}{a})^2+[c-(\frac {b}{a})^2]$$=$$(ax+\frac {b}{a})^2+[c-(\frac {b}{a})^2]$$
Thus if the second part i.e. $[c-(\frac {b}{a})^2]$ is equal to 0 then it is a perfect square.
Then $ax+(\frac ba)^2$=$y$. So you can find the value of $x,y$. I am now still finding a good way. Thank you.
Answer: Given $a,b,c$ with $a\neq 0$, rewrite the equation in factored form
$$\left(a y-a^2x-b\right)\left(a y+a^2x+b\right)=a^2c-b^2$$
This leads to two linear equations
$$a y-a^2x-b=d_1$$
and
$$a y+a^2x+b=d_2$$
where $d_1, d_2$ are divisors of $a^2c-b^2$ such that $d_1 d_2=a^2c-b^2$
Comment: Nice but it does not assure that $x$ and $y$ will be integers, consider $a=1$, $b=0$, $c=2$. Then those equations do not have integer solution.
Comment: @Sil That is correct. If the system of two linear equations has no solutions with $x$ and $y$ integers, then the given expression is not a perfect square.
Comment: Exactly, and that is the same you could say about the original equation. In other words, this does not give any new information about the solution, or how to find it.
Comment: @Sil By writing a system of linear diophantine equations we have shown that the number of solutions of the original equation is finite. Furthermore there are necessary and sufficient conditions for the existence of a solution of such a system.


How to hack my own server?

Question: Hello Im using Windows Server 2008 R2, yesterday I notice that my AD was not working propertly cause I cant manage users and mmc console dont allow me to work with any ad, dns relative consoles.
So I found unknows IPs on DNS Propertyes (in the tab where are two radio buttons : all ips and select ips)
so I notice that my Domain Administrator has become a "GUEST" and I lost my Local Administrator (was removed or maybe renamed).
Today I remove the AD with dcpromo /forceremoval , and now I cant enter with any administrator account on my server.
Login screen appears without the computername.
I want to enter with some trick or hack it for recover my information is an Windows Server 2008 R2 Enterprise RC1 Build 7100
Help me please, thanks to anyone
Answer: You might have to restore from backup.
Even that would be tricky because of active directory not liking the previous database appearing on the network, though.
Is this the only AD server you had? Are there backup servers? If this was JUST an AD server you might get away with rebuilding the box and re-joining it to the domain as an AD server.
You also need to investigate how you lost those privileges in the first place! Hack? Missing updates? Admin user gone rogue? If someone IS in your system with admin privileges there's a good chance you have other problems with trojans, corruption, stolen data...you really need to stop and audit everything in your network to find out what happened or this issue you're troubleshooting is akin to fixing a hangnail on a guy that just had his foot severed.
Comment: Problem is that doing a recovery on an AD system can cause issues with other AD servers as that causes temporal issues with their syncing. They don't like seeing a member server appear with updates that are tagged from back when you did your last backup. Another reason AD servers should just be used for AD...fail, build a new one and re-join as an AD server so it resyncs properly. It's quite a procedure to recover from a backup with other AD servers.
Comment: @Bart Thanks for comments, but I can't enter to the server to perform a BackUp :S
Comment: Server was updated ever
Comment: I meant you'd have to restore from a previous backup, maybe from bare metal recovery. Wipe and restore, as if the hard disk(s) had failed.
Comment: Bart is right.  Been there done that, won't do it again.  DC's are DC's not file servers.
Answer: I might be wrong but I remember that 2008 R2 RC1 was having a curious bug that was causing the symptoms you are experiencing right now... If you rebuild you server at the end, go for the RTM version, anyway RC1 will be dropped soon or later by Microsoft...
Answer: With the server no longer a DC then you can enable and reset the local Administrator account password by booting from a live rescue CD.  There are many live CD's that have these tools: UBCD4Win (requires an XP CD to create the ISO but has other Windows tools), Trinity Rescue Kit, Offline NT Password and Registry Editor, etc.
Since the server was compromised you'll have to format and reinstall once you get what you need off of it or you'll never be sure the system is clean and undamaged.

How to hack my own server?


A farmer is growing a magical tree

Question: This is not homework. It's a story I came up with to explain a statistical distribution I became interested in. If this is a known distribution, I'd love to be pointed in that direction.

A farmer has planted a crop of magical trees. Each tree has one long root that runs near the surface of the soil.
This species of magical tree sprouts one flower each day from its surface root. That sprouting flower is randomly placed along the root.
However, if the sprouting flower is further from the trunk than another flower, it does not grow. Perhaps this is because the flowers closer to the trunk soak up all the nutrients that would have allowed a new flower to sprout.
Here's an example of what a magical root could experience. _ is the root, f is a flower, n is a new flower that's trying to sprout, || is the trunk
Day 0. ||____________________
Day 1. ||___________n________ new flower attempts to sprout
Day 2. ||_____n_____f________ flower from yesterday grew up, new flower attempts to sprout
Day 3. ||_____f__n__f________ flower from yesterday grew up, new flower attempts to sprout
Day 4. ||_____f_____f____n___ flower from yesterday did not grow, new flower attempts to sprout
Day 5. ||__n__f_____f________ flower from yesterday did not grow, new flower attempts to sprout
Day 6. ||__f__f_____f___n____ flower from yesterday grew up, new flower attempts to sprout

Assume that the root is infinitely long (i.e. the root is best described by the reals, where the location of each flower is between $(0, 1)$).
Questions I have:

How many flowers can a farmer expect to harvest from the average magical tree after 100 days of growth (including the newly sprouted flowers on the 100th day)? After n days?
What's the average location of a flower (given as a real number $x$ between 0 and 1) after 100 days? After n days?

I know the answer to these questions by writing a program for it, but I'd love to better understand how to calculate this theoretically.
If this doesn't belong here, I'm happy to move it to a different stack exchange.
Comment: It belongs here. It has some similarities to a coupon collector problem in that you're summing geometric variates where $p$ decreases with each success.  [Notice that the location of each new "$f$" is smaller than every $f$ observed so far. So given $f$s at $x_1,..., x_k$, $P(n \to f) = x_{(1)}$, where $x_{(1)}$ is the smallest of the observed $x$'s. Aside from the day to go from $n$ to $f$, the process can be reduced to "wait a geometric number of days then place a new flower uniformly in $(0,x_{(1)})$, then recalculate that right bound.]
Comment: @whuber good point, that was confusing language. They are the same, I removed all mentions of sprouts dying and replaced them with 'did not grow'. Does that clear it up?
Comment: Historically, this process was described in terms of a game of rolling billiard balls one at a time on a table.  The "flowers" are the positions where a ball stops.  The ball nearest the players' side is always left in place; otherwise, it is removed.  Thomas Bayes used this to motivate a Binomial experiment with a Beta prior distribution.
Comment: What is the relationship between "does not grow" and "dies"??
Comment: "Did not grow" seems also to imply "disappears one generation later." This affects the status of subsequent flowers, so please clarify exactly what the rules are.
Comment: If the sprout did not grow, then it's as though it was never there. Another sprout can attempt to grow in the exact same location later on. Does that answer the ambiguity?
Answer: My attempt.
For a flower to sprout it needs to be closer to the trunk than all other current flowers. We define $X_i \sim Unif[0, 1]$ as then location of seed at day $i$.
For a flower to grow it needs to be smaller than all seeds until then current point. That is, define $Y_i = 1$ if the flower sprouted and $0$ else.
Therefore, the probability for a flower to sprout is
$$P(Y_i = 1) = P(X_i < min_{i < j}(X_j))$$
The minimum of uniform distribution is quite simple to find (assuming independence), define $M_i = min_{j < i}(X_j) $.
$$P(M < m) = 1 - P(M > m) = 1 - P(X_1 > t, \ldots, X_{i-1} > t) = 1 - (1 - m)^{i-1}$$.
The density is,
$$f_M(m) = (i-1)(1-m)^{i-2}$$
Therefore, the expected value is,
$$E(M) = \int_0^1 (i-1)(1-m)^{i-2} m dm = (i-1) \int_0^1 (1-t)t^{i-2}dt  $$
Finally, we obtain
$$ E(M_i) =  \frac{1}{i}. $$
Note that this answer your question 2, the average location of a flower in day $n$, will be $\frac{1}{n+1}$ (since we are looking at the extra day).
Now, to question 1, the expected number of flowers will be (note we add 1 to deal with the first seed),
$$ E(\sum_{i=2}^n 1 + (Y_i)) = \sum_{i=2}^n E(Y_i) = \sum_{i=1}^n E(E(Y_i)|M_{i}) = 1 + \sum_{i=2}^n E(M_{i}) = \sum_{i=1}^n \frac{1}{i}.$$
Verifying the results using simulation, (using R):
    runDays <- function(days) {
      flowers <- Inf
      for (i in 1:days) {
        possible <- runif(1)
        if (possible < min(flowers)) {
          flowers <- c(flowers, possible)
        }
      }
      return(flowers[-1])
    }

Question 1,
    x <- replicate(100000, length(runDays(50)))
    mean(x)
    [1] 4.49174
    sum(1 / 1:50)
    [1] 4.499205
    x <- replicate(100000, length(runDays(100)))
    mean(x)
    [1] 5.17413
    sum(1 / 1:100)
    [1] 5.187378

Question 2,
    x <- replicate(100000, rev(runDays(50))[1])
    mean(x)
    [1] 0.0195804
    1 / 51
    [1] 0.01960784
    x <- replicate(100000, rev(runDays(100))[1])
    mean(x)
    [1] 0.009909106
    1 / 101
    [1] 0.00990099

Looks ok.
Comment: I notice your experimental value for Q1 is much closer to `sum(1/1:99)` (`5.177378`). But for `runDays(50)`  `sum(1/1:49)` and `sum(1/1:50)` seem to be either side of the experimental value (4.479205 and  4.499205).  (I cannot explain why, so will have to stick to heckling from the sidelines.)
Comment: Thank you so much! I'll need to study this a bit, my attempts were stymied, so I'm excited to learn something. What's the programming language you use here?
Comment: Its called R, widely used for statistical computations. Here's the link: https://www.r-project.org/
Answer: Kozolovska gives a good answer.  This one outlines a different solution method.
Let $X_n$ be the location of the leftmost flower after $n$ days.  The problem states $X_0=1$ and the distribution of $X_{n+1}$ conditional on $X_n$ is a mixture of $X_n,$ with probability $1-X_n,$ and a uniform distribution on $[0,X_n),$ with probability $X_n.$  The moment generating function of the latter is
$$\phi_{X_n}(t) = E\left[e^{tX_n}\right] = \int_0^{X_n} \frac{e^{t x}}{X_n}\,\mathrm{d}x =\frac{e^{tX_n}-1}{tX_n}.$$
Let's compute the moment generating function of $X_{n+1}.$  It is immediate that the conditional expectation of $\exp(tX_n)$ is the same linear combination of expectations of the mixture components,
$$E\left[e^{tX_{n+1}}\mid X_n\right] = (1-X_n)e^{tX_n} + X_n\phi_{X_n}(t).$$
Taking expectations (w.r.t. $X_n$) yields
$$\begin{aligned}
\phi_{n+1}(t)  &= E[e^{tX_{n+1}}]= E\left[E\left[e^{tX_{n+1}}\mid X_n\right] \right] \\
&= \phi_n(t) - \phi_n^\prime(t) + \frac{\phi_n(t) - 1}{t}
\end{aligned}\tag{*}$$
Clearly $\phi_0(t) = \exp(t(1)) = \exp(t).$  The general solution (which you can check by plugging it into the recursion $(*)$) is
$$\phi_n(t) = \frac{n!}{t^n}\left(e^t - 1 - t - \frac{t^2}{2} - \cdots - \frac{t^{n-1}}{(n-1)!}\right).$$
This is the moment generating function of a Beta$(1,n)$ variable.  Since $X_n$ is bounded its m.g.f. determines its distribution, so we conclude $X_n$ has a Beta$(1,n)$ distribution.
(This is more readily derived using uniform order statistics -- but it might be of interest to see it emerge using the m.g.f. method.)

Here is a simulation using R.
n <- 50
n.sim <- 1e5
X <- rbind(1, apply(matrix(runif(n * n.sim), n), 2, cummin))

The n rows of $X$ record values of $X_0=1, X_1, \ldots, X_{n}$ in n.sim independent simulations of this process.  The histogram of the last one indeed matches the theoretical Beta density:
hist(X[n, ], freq=FALSE, breaks=100, ylim=c(0, 1/beta(1,n)), col=gray(.95),
     main=bquote(paste("Histogram of ", X[.(n)])),
     xlab="Value")
curve(dbeta(x,1,n), lwd=2, col="Red", add=TRUE, xlim=c(1e-6,1), n=1001)

The expected numbers of remaining values ("flowers") match the theory, too, as in this scatterplot of all n simulated random variables:
i <- apply(X, 2, function(x) cumsum(diff(x) < 0))
plot((cumsum(1/seq_len(n))), rowMeans(i),
     main="Expected Count",
     xlab="Theory", ylab="Simulation")
abline(0:1, col="Red")

Comment: Wow! So cool. This will take even more digesting.

A farmer is growing a magical tree


Problema com zoom na tela usando fabricjs

Question: Problema com zoom de tela, ao usar o fabricjs.
Quando tenho um canvas com muitos elementos, o zoom demora muito, fazendo um delay muito lento, está quebrando o desenho, e o canvas não finaliza a renderização corretamente, o lápis passa a riscar no lugar errado, é uma série de problemas...
Javascript:
window.onload = function() {

   var area = document.getElementById('my_area_canvas');
   var size = 0.1;

   function zoomIn() {

      var scale = Math.min(
        (window.innerWidth - 170) / window.innerWidth,
        (window.innerHeight - 170) / window.innerHeight
      );
     scale=+size;
     area.style.transform = 'scale('+scale+')';
   }

   function zoomOut() {

      var scale = Math.min(
        (window.innerWidth - 170) / window.innerWidth,
        (window.innerHeight - 170) / window.innerHeight
      );
      scale=-size;
      area.style.transform = 'scale('+scale+')';
   }

}

HTML:
<button onclick="zoomIn()">+</button>
<button onclick="zoomOut()">-</button>

    <canvas id="shapes" width="1108" height="598" class="shapes lower-canvas" style="position: absolute; width: 1108px; height: 598px; left: 0px; top: 0px; touch-action: none; user-select: none;">
    </canvas>

Existe alguma maneira de adaptar esse zoom conforme o modelo que ele apresenta aqui?
http://fabricjs.com/fabric-intro-part-5
Comment: O elemento "my_area_canvas" está definido com uma classe em vez de um id.
Comment: ok, corrigi, mas esse não era o problema. Mas já corrigi o problema, e vou publicar uma resposta.
Comment: bom dia colega, consegue ajudar com isso https://pt.stackoverflow.com/questions/534532/atribuir-um-valor-whidth-para-getactiveobject-em-fabric-js
Answer: Só precisei acrescentar isso dentro das funções e resolveu o problema:
 var originalWidth = canvas.getWidth();
 var originalHeight = canvas.getHeight();
 var ratio = 1;

 canvas.setDimensions({ width: originalWidth * ratio, height: originalHeight * ratio });
 canvas.setZoom(ratio);


Add a limitations to anonymous user for node view

Question: I have to put a limitations on the number of nodes an anonymous user can view. So I have to set a limitations of 5 after that the anonymous user is made to login by redirecting to the login page.
So I have used hook_nodeapi and under view operation i maintains a counter in cookie for the no of times the user visits the node.So if exceeds the counts it redirects to login page. But some how it doent work and gets redirected randomly..i mean not after 5 but after 7,8,,or some number.Some times it doesnt even increments the counter.
So is it because the cache is enabled or is there some other reason to it.
below is my code used under hook_nodeapi:-
if($user->uid==0){
  if(isset($_COOKIE['anonymousquizview'])){
    $m = $_COOKIE['anonymousquizview'];
    $m++;
    setcookie("anonymousquizview", $m, 0,"/", "www.example.com");
  }
  else {
    setcookie("anonymousquizview", 1, 0,"/", "www.example.com");}
    if ($_COOKIE['anonymousquizview'] >=5) {
      drupal_set_message("To attend more challenges, kindly login.");
      drupal_goto('user/login');
    }
  }
}

Answer: If cache is enabled hook_nodeapi() is not always executed. The first time a node is viewed Drupal renders the page and save it in the cache. During this process, hook_nodeapi() will be fired. Next time the same page is viewed, Drupal will find the rendered copy in the cache,  serve this copy, and no hook_nodeapi() will be fire fired.
You have to do it in hook_boot. This hook is fired even for cached pages. You must first check if current path is a node path (you may use arg() function). Try to add lightweight code as it will be executed in every page petition.
Remember that this protection is easily bypassed clearing the cookies for your domain.
References

hook_boot()
arg()


How to delete all Drupal content owned by a particular user?

Question: It seems like there should be a drush command to achieve this, but I cannot find one. I am not clever enough to fashion an SQL query that will delete all nodes owned by a user as well as clean up all the field and revision data.
Please let me know if anyone has any solutions (other than deleting the user's account).
Drupal 7
Answer: A possible alternative to achieve what you're trying to do, is to use a combination of modules Views and Views Bulk Operations (VBO). With these modules in place, you could simply create a view of all the nodes "owned" by a user, and simply use the out-of-the-box VBO action to "delete an item" (after adding a VBO field like "Bulk operations: Content"). And by creating a similar VBO view, using the VBO field "Bulk operations: Content revision", you can probably also cleanup up the revision data.
If you need more sophisticated business logic to decide about the criteria related to "owned by a user", you could add Rules to such solution also and implement a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

Create a Rules Component with a Rules Condition to checks if the node matches the criteria you're interested in.
Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Done ...


Multiple JNI Layer in the same SO File.

Question: I am trying to add jni layer to an old library.
There is already a jni layer in that library. But I do not wish to add my code to that file.
For better management I want to create seperate java and c files.
Is it possible have "multiple" JNI Layers in the same .so file?
If so how do I go about doing it?
Answer: I am not sure exactly what you mean by multiple JNI layers.  It sounds like you are asking if you can run javah against two distinct java files and create a single JNI library based on native methods contained in those two files?  Absolutely.  Simply compile and link each file together.

Multiple JNI Layer in the same SO File.


Finding E(X). from the basic

Question: The diameters of the marbles manufactured follow a N-distribution with $μ = 9$mm  and $σ = 0.125$mm. A marble is classified as oversize if its diameter is more than $9.16$mm.
The diameters of the marbles are measured one by one. Let $X$ be the random variable representing the no. of measurements when the first oversized marble is found. Find $E(X) .$
I found $\text{pr(a randomly selected marble is oversized)} = 0.1003$ via $N\sim(9, 0.125)$.
All I know is $E(X) = \sum [x \times P(X= x)]$, but how to go from that to the answer of $E(X) = 1/0.1003$.
Answer: Found the probability of one marble to be oversize than X is a geometric rv with $E[X]=\frac{1}{p}$
You can easy prove this calculating $\Sigma_x x p(x)$ where
$$P(X=x)=q^{x-1}p$$
$x=1,2,3,...$ and $q=(1-p)$
Proof:
$$\mathbb{E}[X]=p\sum_{x=1}^{\infty}x q^{x-1}=p\sum_{x=1}^{\infty}\frac{d}{d q}q^x=p\frac{d}{d q}\underbrace{\sum_{x=1}^{\infty}q^x}_{=\frac{q}{1-q}}=$$
$$=p\frac{d}{d q}\frac{q}{1-q}=p\frac{1}{(1-q)^2}=\frac{p}{p^2}=\frac{1}{p}$$
Proof through "the basic"
$$\mathbb{E}[X]=p+2pq+3pq^2+4pq^3+...=p(1+2q+3q^2+4q^3+...)=pS$$
Thus
$$S=1+2q+3q^2+4q^3+...$$
$$Sq=q+2q^2+3q^3+...$$
Let's subtract member to member:
$$S(1-q)=1+q+q^2+q^3+q^4+...=\frac{1}{1-q}$$
(geometric series)
$$S=\frac{1}{(1-q)^2}=\frac{1}{p^2}$$
Thus
$$\mathbb{E}[X]=\frac{p}{p^2}=\frac{1}{p}$$
but I prefer the first proof...
Comment: Thanks for the explanation. I go through the basics and get a result similar to your last statement.  Let the probability of getting an oversized = p and $p^c = q$
$E(X) = [1P(X = 1)] + [2P(X = 2)] + [3P(X = 3)] + [4P(X = 4)] + …
= 1p + 2(q)p + 3(q^2)p + 4q^3p + …
= p[1 + 2q + 3q^2 + 4q^3 + ….]$
Comment: @Mick : I added the proof in my answer

Finding E(X). from the basic


Picking from Logistic vs Survival Model

Question: I have a health data set for measuring the effectiveness of a drug. (Age, Gender(0,1), Morbidity(1,2,3), Dosage(0,1), Group (a,b), Effect (Not effective =0, effective = 1), and Time (days needed for drug to work if Effect = 1, Days observed until subject left the study if Effect =0), and I'm being asked to predict Effect.
Obviously, Time is better if it's lower. My general recollection with survival models using right censored data is that "longer" or "bigger" Time is better. (I'm remembering my GLM class from 2005 in undergrad.)
Should I be using Logistic Regression or a Survival Model? Are there other types I should consider?
If I were to be predicting Time, would a linear regression model or a Tobit model be appropriate?
Thank you in advance for any help. I've hosted my data here if anyone wants to poke at it.
Comment: Survival analysis is your choice given "subject left study" has no relation with "drug to work".
Answer: First, whether longer is better or worse does not depend on your choice of model but on what is being measured. One common use of survival analysis (and the reason for its name) is time to death. Obviously, longer is better! But if your effect is good (e.g. relapse from a disease) then longer is worse. That's not a problem. Survival analysis can be used in both cases.
Second, logistic and survival analysis ask different questions. Logistic, in your case, would answer "Was the probability of an effect related to age, gender etc.?" while survival would answer "Was the time to the effect (technically, the instantaneous hazard) related to age, gender etc.?"
Does time to effect matter a lot in your study?
Third, if you are predicting time then you want survival analysis, not linear or tobit. The great strength of survival analysis is that it deals well with censoring - those people who left the study for whom you have only the information that the effect did not occur before they left.
Comment: Hi Peter, this is very helpful. I need to do two sets of analysis, one to predict effect, and another to predict time to effectiveness. The former will be logistic and the latter survival, based on what you've said. QUESTION: Is using right censored data as a predictor problematic? I've found some papers online suggesting that it causes parameter inflation in *linear* regression models, but haven't found anything relating to logistic regression.
Comment: Ummm.... None of your predictors will be right censored.
Comment: Peter, isn't my Time variable right censored? restated: Time (days needed for drug to work if Effect = 1, Days observed until subject left the study if Effect =0)
Comment: Yes, but it should not be a predictor in the logistic regression.
Comment: Interesting...! It's actually one of the most powerful predictors in the dataset. Why should it not be used is a predictor?
Comment: If you want to poke at my data it's hosted here: https://nofile.io/f/nMao7hxwtBz/ares_data_set.xlsx
Comment: For one thing, you don't know it when you start.

Of course it's highly related to the event, but it's not a predictor because it doesn't come first.
Comment: Peter, very good point and fascinating. And of as you mentioned previously, survival analysis will evaluate what predicts the time to effectiveness. What the data shows is that IF the drug is effective, the average Time is very short. If the drug is inneffective,the time is very long.

Picking from Logistic vs Survival Model


Uncaught ReferenceError: vira1 is not defined

Question: Estou criando uma função mas quando é chamada diz que não foi definido ainda, qual seria o motivo ?

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-jogomemoria',
  templateUrl: 'jogomemoria.html',
})
export class JogomemoriaPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

}
function vira1(){
 document.getElementById("vira0").style.zIndex = "999";
}
<ion-header>
</ion-header>

<ion-content padding class="bgcMemoria">

</ion-content>
Comment: Em vez de `onclick=` utilize `(click)=`
Answer: A partir do Angular 2 para fazer binding de eventos usa-se parênteses, toda vez que quiser chamar um evento faça (evento)="exeFuncao()"
Alguns eventos:
(focus)="exeFuncao()"
(blur)="exeFuncao()"

(submit)="exeFuncao()"

(scroll)="exeFuncao()"

(cut)="exeFuncao()"
(copy)="exeFuncao()"
(paste)="exeFuncao()"

(keydown)="exeFuncao()"
(keypress)="exeFuncao()"
(keyup)="exeFuncao()"

(mouseenter)="exeFuncao()"
(mousedown)="exeFuncao()"
(mouseup)="exeFuncao()"

(click)="exeFuncao()"
(dblclick)="exeFuncao()"

(drag)="exeFuncao()"
(dragover)="exeFuncao()"
(drop)="exeFuncao()"

Você pode ver a lista completa nesse artigo no sitio da Mozilla.
Outro erro, é que seu método vira1 está fora da classe JogomemoriaPage então não ira funcionar.
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
    selector: 'page-jogomemoria',
    templateUrl: 'jogomemoria.html',
})
export class JogomemoriaPage {
    constructor(public navCtrl: NavController, public navParams: NavParams) {
    }
    vira1(){
        document.getElementById("vira0").style.zIndex = "999";
    }
}

Comment: E para declarar uma variável ai dentro ? Estou tentando mas fica dando erro não seria assim ? "let variavel: any = 0;" fica mostrando erro no let
Comment: Que variável? Porque na pergunta não tem, ai já é outro problema, que recomendo abrir outra pergunta, pois vou ter que sinalizar como ampla. Quando criar uma pergunta certifique de ter colocado todos os detalhes.
Comment: Abri outra pergunta com mais detalhes
Comment: Mas tenta colocar a variável no método `constructor` sem o `let`.
Comment: Certo, agora se a resposta solucionou esse problema considere marcar como aceita.


Is there an "Idiot proof" way to re-enable all fields (regardless of there state) on a form?

Question: My problem is that I have javascript that enables/disables some form fields that I have disabled by default that the user doesn't need to send to my business, but can enable them if they need to with a checkbox. However, I obviously have a form provider that is quite finnicky about disabled fields. Basically, the visitor will select checkboxes that will enable certain fields that they need to enter, or choose to.
What I'm curious about, can I create a checkbox that will undo all the fields enabled or disabled state to just enabled, regardless of it's current state, so that all fields get submitted?
Another reason I need this kind of function is because the client receives an autoresponce e-mail, and when the fields are disabled they see %FeildName% if the field was disabled before submitting the form. simply because the field never existed when the data was submitted on the form, obviously because of it's disabled state.
If something can be done, can it be entered in my existing javascript code? I already have a Form Validation script, that I used with javascript.
I'm not exactly great at javascript, and never really even played with jQuery before, nor do I have the intellect to follow jQuery, so any help would be appreciated.
My code can be seen on this page, just view the source.
http://www.gbjimaging.net/order/form/complete/audio.htm
The checkbox at the very bottom of the form, before the submit and reset buttons I'd like to perform this function, so that all information is garenteed to be submitted. Again, thanks for your anticipated help, and it really will be appreciated.
Comment: If you don't have the intellect to follow jQuery, you're in the wrong line of work. Are you planning to come running to SO for every script you need to write?
Comment: @OneOfOne Those are his words, not mine.
Comment: @Geno J, Try reading my answer! It has an example you need and basic info for newbies in order to start using jQuery!
Comment: @Barmar, "the intellect to follow jQuery", seriously? the fact that you think that there's only one way to do anything saddens me deeply...
Comment: Hey, I also did say that I am open minded. If there's a Dummies book on it, it's a best seller to me. lol
Answer: There is a very easy way to do this.  All you have to do is put all the field items in an Array, then when the user checks the checkbox, you can make an Array loop and for every item in the Array (for(var i = 0; i < array.length; i++) if(checkBox.checked == true) {array[i].disabled = false;} else {array[i].disabled = true;}).  This will disable all items if checkbox on uncheck, and enable on check.
Here is a small diagram:
Comment: There is no `enabled` property, it should be `.disabled = false`.
Comment: @Barmar Thank you, I was using my knowledge of actionscript, I should've checked.  Anyways, it was fixed.
Answer: In jQuery:
$(":input").prop('disabled', false);

:input is a jQuery pseudo-selector that matches all types of form input fields. The .prop method gets or sets properties, so this sets all the disabled properties to false.
Answer: The following example is the way to make sure that all fields of your current form were re-enabled. All of the elements with input, select, textarea and checkbox tags will become enabled as you click a button:
$(document).ready(function() {
  $('#switcher').click(function() {
    $('input, select').each(function() {
        if ($(this).attr('disabled')) {
            $(this).removeAttr('disabled');
        }
    });
  });
});

Online example
You need to use jQuery and add it to your page by pasting the following to your page's head:

In this example Google CDN is being used.
Please read more about jQuery Install and jQuery Usage.
Comment: Where does both of the above codes you provided go? I mean, I'm familiar with Javascript, and I know that the Form Validation that I use went in the head. I mean I don't want to sound like I'm completely clueless, but I did a lot of my form generating using form providers that did it all for me. To me, I've been always interested in web design, and have learned a lot on my own. I just know there's a lot more to learn. So, I'm sorry if I sound like I have no idea what I'm doing, but at least I'm willing to learn.
Comment: After going to that online example, I found that there would be a huge problem there. If I entered that using a checkbox, the checkbox would become disabled. On top of that, all existing fields that were disabled, would become enabled, and the enabled fields would become disabled. So, that code is a bit counterproductive, because it still presents the same problem, but now all the disabled fields are enabled, and enabled fields before are disabled.
Comment: What I'm trying to do is enable ONLY the current fields that were disabled should be re-enabled. For example, the extra phone number fields should be re-enabled, or the extra Item numbers. When I played with that code it disabled all enabled fields like FirstName, LastName and so on, and re-enabled all the disabled fields like the spair phone numbers, and the checkboxes, and item number details. ~ http://www.gbjimaging.net/order/form/complete/audio.htm
Comment: I made an example based on your form that after you click enable button, it will enable all `input, select, textarea` and `checkbox` fields, take a look at the updated example: http://jsfiddle.net/XVq6a/2/
Comment: In that case, where does the two examples of this code go? Judging by the first code, it looks like it may go in the head, but I'm not 100% sure. I'm not even sure if it can be added to an existing code. Because from the looks of it, it is what most people do on here, and specifically look at the function of javascript, and start there, when they don't add .
Comment: Secondly, does the other code for jQuery looks like it can be added anywhere. So, any help is appreciated. I don't mean to be blunt, nor sound rude. I just am trying to get a grasp of this stuff. I'm willing to try anything, and I'm trying not to be judgemental in regards to any of the answers I've received. I'm just kinda over my head is all. ;)
Comment: Do you want to add it to your page?
Comment: Well... looking at the demonstration, and seeing it in action, yes. The only thing I'd do, is change the switcher to a checkbox.
Comment: The code works great. Curious though... instead of an Enable link, can it be a checkbox? I'd like the client to be able to check that box at the end of the form to enable all fields, and then hit Submit. The checkbox will mainly work for that purpose, but it will confirm the client has entered all information, to the best of their ability. My last comment... I promise. If you've got a responce, could you send it via comment or chat? Thanks.
Comment: Nevermind, just found the id tag! thanks! Very much appreciated. Thanks everyone for your help and insight!
Answer: Something along the lines of :
function validate(OrderAudio) {
    if(valid) {
        var e = document.getElementsByTagName('input'), i;
        for(i = 0; i < e.length; ++i) {
            e[i].disabled = false;
        }
        e = document.getElementsByTagName('textarea');
        for(i = 0; i < e.length; ++i) {
            e[i].disabled = false;
        }
    }
}

Comment: I'll try this out. This looks the easiest route, without having to seriously remodify my whole form. Although, I may look into jQuery anyway, as it is becoming more and more evident that it's going to be unavoidable at some point.


Java invoking method requiring vararg

Question: So I have method more or less like this:
foo(Boolean a, Boolean b, Integer... excess)

and I want to invoke it with array of arguments that contains at least first 2 booleans and not always rest of integers. I've tried creating array of objects and put it on the end but then it throws Exception cuz it cant cast array of object to integer, dont know why so I ask, is there any easy way of doing this?
Comment: Show us what you've tried. *'it throws Exception'* -- what exception?
Comment: you might have used `int[]` instead of `Integer[]`
Comment: damn, too early posted, I wanted to include that I do it in reflection and it goes like this
method.invoke(cl, list.toArray())
this list had plain list of arguments, 2 logic and Integer[], 2 login and Object[] but nothing worked in case where list contains excess integers and where it does not
Comment: You can always *edit* the question, its not too late.
Answer: Your method declaration for the mandatory and optional parameters are correct but in fact if you want to use an object array for the optional parameter part then you should be using definin Object... args as your final parameter to the method.
In your question you said you tried to create array of objects and passed this to the method as the final parameter but your declaration is Integer... args which is equivalent to Integer[] args so you have to declare and pass an Integer[] to the method.
Comment: finally, thank you!
Answer: In your case, you defined foo method like below.
void foo(Boolean a, Boolean b, Integer... excess) {

}

Since varargs can take zero or more arguments, you can call that either passing integer array or not.
Example 1:
Integer[] arr = { 2, 3, 5 };
foo(true, false, arr);

Example 2
foo(true, false);

Find below sample app.
public class App {

    private static void foo(Boolean a, Boolean b, Integer... excess) {

    }

    public static void main(String args[]) {
        Integer[] arr = { 2, 3, 5 };

        foo(true, false, arr);
        foo(true, false);
    }
}

I would recommend you to read varargs here.

Java invoking method requiring vararg


Translation invariance of Lebesgue integral

Question: I am looking at the following statement: Let $u:\mathbb{R^3} \rightarrow \mathbb{S}^1$ and $z\in \mathbb{R}^3$ and $h>0$ small. Then the integral $\int_{\mathbb{T}^3} dx$ is translation invariant and therefore
$\int_{\mathbb{T}^3} u(x)-u(x-\sqrt{h}z) dx = \int_{\mathbb{T}^3} u(x-\sqrt{h}z)-u(x-2\sqrt{h}z) dx$.
I understand that the Lebesgue-measure is invariant under translation and this implies that the Lebesgue Integral is translation invariant as well, in the sense that for a measurable set $D \subset \mathbb{R}^3$ we have
$\int_D u(x) dx = \int_{D-z} u(x+z) dx$.
The torus is defined as the quotient of the cartesian plane with the identifications $(x,y,z)\text{~}(x+1,y,z)\text{~}(x,y+1,z)\text{~}(x,y,z+1)$. The thing I don't understand in the first statement is that we have both times the integral over $\mathbb{T}^3$. I thought that on the righthand side it should be $\mathbb{T}^3+\sqrt{h}z$ for $\sqrt{h}z \notin \mathbb{Z}^3$ after our definition of $\mathbb{T}^3$. Am I not understanding the notion of the three-torus correctly or where is my mistake?
Answer: The torus $\mathbb{T}^n$ is mapped to itself upon a translation of it's native periodic coordinates. Think about the circle (less commonly noted as $\mathbb{T}^1$) for example- if you shift the angle coordinate by any amount, you will still traverse the whole circle on the interval $[0,2\pi)$.
Of course, when a function is defined on the torus, in order for this to still hold true under integration, we need to equip the function with the same symmetry as the torus, in other words we must make it periodic in all directions with the same period as the torus. This makes sense if you want your function to be single-valued on the manifold.
Proof for the Riemann integral, with some simplifying assumptions
Here's a proof for the Riemann integral on $\mathbb{T}_1$ that generalizes well to higher dimensions:
Assume $f(x+1)=f(x)~\forall x$. Then we define the following Riemann integral
$$I(a)=\int_{0}^{1}f(x-a)dx=\int_{a}^{a+1}f(x)dx$$
We compute it's derivative and we find that:
$$\frac{dI(a)}{da}=f(a+1)-f(a)=0\iff I(a)=I(0)$$
and thus we proved
$$\int_{\mathbb{T^1}}f(x)dx=\int_{\mathbb{T^1}}f(x-a)dx~ \forall a\in\mathbb{R}$$
Generalizing in higher dimensions is easy. Denoting $\mathbf{a}=(a_1,a_2,...a_n)$ and generalizing the periodicity property on $f$ accordingly, we define
$$I(\mathbf{a})=\int_{(0,1)^n} dx_1...dx_n~f(\mathbf{x+a})$$
Taking the gradient, we note that
$$\begin{align}\frac{\partial}{\partial a_i}I(\mathbf{a})&=\int_{(0,1)^n} dx_1...dx_n~\frac{\partial}{\partial a_i}f(\mathbf{x+a})\\&=\int_{(0,1)^n} dx_1...dx_n~\frac{\partial}{\partial x_i}f(\mathbf{x+a})\\&=F_i(a_i+1)-F_i(a_i)\end{align}$$
where we defined
$$F_i(t)=\int_{(0,1)^{n-1}}dx_1...dx_{i-1}dx_{i+1}...dx_nf(x_1+a_1,...,x_{i-1}+a_{i-1}, t,...,x_n+a_n)$$
Due to the periodicity condition in all coordinates, it is clear that
$$F_i(t+1)=F_i(t)~,~\forall i,t$$
and hence all first-order partial derivatives of $I$ identically vanish and the integral is shown to be a constant with respect to shift parameters. By setting $\mathbf{a}=0$ we conclude that
$$\int_\mathbb{T^n}d\mathbf{x}f(\mathbf{x+a})=\int_\mathbb{T^n}d\mathbf{x}f(\mathbf{x})$$
as desired. These ideas should have an analogue on the Lebesgue integral that I haven't been able to exactly pinpoint, but I hope they provide with a good starting point.
EDIT: Proof for Lebesgue integral, only assumes positivity and measurability
I came up with a Lebesgue-measure style outline of a proof for $\mathbb{T}^1$:
Consider the measure of the following set $\mu(x\in (0,T)|f(x)>t)$. If f is positive definite and measurable, the Lebesgue integral exists and is equal to $\int_{0}^{\infty}\mu(x\in (0,T)|f(x)>t)dt$.
However we note that if we shift the argument by an amount $a=mT+r, 0<r<T$ and assume $f$ is $T$-periodic,
$$\begin{align}\mu(x\in (0,T)|f(x+a)>t)&=\mu(x\in (0,T)|f(x+r)>t)\\&=\mu(x\in (r,T)\cup(T,T+r)|f(x)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(x\in (T,T+r)|f(x)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(y\in (0,r)|f(y+T)>t)\\&=\mu(x\in (r,T)|f(x)>t)+\mu(x\in (0,r)|f(x)>t)\\&=\mu(x\in (0,T)|f(x)>t)\end{align}$$
and we are done. This can be readily generalized to higher dimensional analogues of the statement, since all we need to show is that what shifts do is to merely  rearrange the interval of integration (in your case the whole higher dimensional torus). In fact the previous proof goes through completely by just adding indices where appropriate, $a_i=m_iT+r_i$ and applying the one-dimensional procedure repeatedly!
Here's the outline of the proof for $\mathbb{T}^n$:
$$\begin{align}\mu((x_1,...,x_n)\in (0,T)^n|f(x_1+a_1, ...x_n+a_n)>t)&=\mu((x_1,...,x_n)\in (0,T)|f(x_1+r_1, ..., x_n+r_n)>t)\\&=\mu(x_1\in (0,T),(x_2,...x_n)\in(0,T)^{n-1}|f(x_1,x_2+r_2,...,x_n+r_n)>t)\\&=\mu((x_1,x_2)\in (0,T)^2,(x_3,...x_n)\in(0,T)^{n-2}|f(x_1,x_2+r_2,...,x_n+r_n)>t)=...\\...&=\mu((x_1,...,x_n)\in (0,T)^n|f(x_1, ...x_n)>t)\end{align}$$
Comment: Thanks for the detailed answer! Your proof is clear to me, but I still don't really get the argument with the torus. You say: The torus Tn is mapped to itself upon a translation of it's native periodic coordinates. Think about the circle (less commonly noted as T1) for example- if you shift the angle coordinate by any amount, you will still traverse the whole circle on the interval [0,2π). And there exactly is my problem: Why is $x \in \mathbb{T}^3$ linked to the angle coordinate and not only to the radial coordinate? Why is this clear?
Comment: Maybe a little more precise: why does the translation $x+a$ with $x \in \mathbb{T}^3$ have to affect the angle coordinate?
Comment: The radial coordinate is a property of the embedding space. For example, the radius of the unit sphere $S^2$ when embedded in $\mathbb{R}^3$ is irrelevant to it's topological properties, the radial direction is not part of the space $S^2$. Here you need to imagine that you are an ant living on $\mathbf{T}^3$ that is measuring some function on it and is trying to find it's average value. The ant can move in 3 directions that are separately periodic, so it will use 3 angles to describe them. It doesn't know anything about the radial coordinates you use to describe it as an external observer.
Comment: When the ant goes around $\mathbb{T}^1$, and it finally returns to the original point, it says "aha! now I traversed 1 unit of length= length of my world", not "aha! I traversed $2\pi R$", the ant doesn't know nor does it have access to the external radius $R$.
Comment: That helped a lot to visualize the problem, thanks!