Can't login: user/login redirects to index page

Question: My Drupal 7 user, user login and admin pages all redirect to the index page. I am unable to login at all. This problem came up recently after the site had been unchanged for months.   I can't think of a single reason this started happening all of a sudden.

http://sohp.us/?q=user
... ?q=user/login
... ?q=admin

Nothing looks funny when I debug in my browser. I have the following details based on my research:

No errors are appearing.
There were no updates, automatic or manual, to the site or modules.
I'm not using Secure Pages, Ubercart SSL, or any other SSL modules that might interfere. The site is pretty basic, simple Zurb Foundation theme, Views, and a couple other small modules, nothing fancy.
$base_url = 'http://sohp.us'; // NO trailing slash!  Is specified in my settings.php file (located in root/public_html)
The Drupal instance was installed through cPanel's Softaculous
I downloaded the default .htaccess for Drupal 7 and replaced the existing one (no changes required).

It seems like the PHP for bringing up the login isn't working correctly, but I could definitely be missing something obvious or compeltely different from what I've been trying. If anyone has any suggestions on things to test out to get myself back in, it is much appreciated.
Thank you.
Comment: A few years late for this comment, but one thing that can happen to cause this is if mod_rewrite somehow gets disabled on Apache. If anyone comes across this in the future, you can check that.
Comment: How exactly your headers looks like?
Comment: When was the last time you updated the site? What version of Drupal?
Answer: Do you have drush installed? I would try clearing cache as a first step, probably won't fix it but worth a shot. After that try renaming the theme that you are using to force Drupal to use a different theme, or change the theme manually in the database. Try disabling modules one by one to see if any of them might be interfering. Start with any module that changes paths (like PathAuto...). I also noticed that no matter what your site will not throw a 404 page not found error. If that was intended, then whichever process you used to redirect 404's to index.php could possibly be causing an issue.


If $f(x)=\frac{1}{n}$ and $x=\frac{1}{2^n}$, where $n$ is a positive integer, and $f(x)=0$ for all other values of $x$. Is $f$ continuous at $x=0$?

Question: Just started Taylors "Advanced Calculus", which seems moderately proof based. I can't figure this one out. The book is old, so some of the notation is a bit odd to my eyes.
Regardless, I start by rearranging $x=\frac{1}{2^n}$ into $\log_2(\frac{1}{x})=n$. From this it follows that $f(x)=\frac{1}{\log_2(\frac{1}{x})}$, which tends to $0$ as $x$ approaches $0$.
So, from this I would assume that it is in fact not continuous as it seems to not be defined at $0$. However, when I check the answer in the back of the book, it simply states that it is. For some problems the book will show a method, however, unfortunately that was not the case for this one.
Comment: I suggest you start by writing the definition for continuity at $x=0$ and then try and work from there.
Comment: "If $f(x)=\frac{1}{n}$ and $x=\frac{1}{2^n}$" That's not well written. I think you mean  "If $f(1/2^n)=1/n,$ ...
Answer: We want to estimate $|f(x)|$ in a neighbourhood of $0$. Let $\varepsilon>0$. Choose $\delta=\varepsilon$, then if $1/\delta<n$, then $1/\varepsilon=1/\delta<n\leq 2^n$. It now follows that if $1/n<\delta$, then $1/2^n<\varepsilon$. Now for $|x|<\delta$ we either have $x=1/n$ for some $n$ in which case $|f(x)|=1/2^n<\varepsilon$, if not then $|f(x)|=0<\varepsilon$.


Find the Taylor Series for $f(x)$ centered at a given value $a$

Question: $$f(x) = \frac{6}{x}\,\, \mathrm{at}\,\, a = -4 .$$
Assume that $f$ has a power series expansion. Do not show that $R_n(x) -> 0$
I took the derivatives of f(x):
$$f(x) = 6/x$$
$$f'(x) = -6/x^2$$
$$ f''(x) = 12/x^3 $$
$$ f^{(3)}(x) = -36/x^4 $$
but I am unable to write out the series, please help! Thank you
Comment: Does my answer help you, or do you still need assistance?
Comment: thanks for your comment, but i do need a little more assistance if you do not mind. The truth is that i do not quite understand how to apply the nth derivative into the series
Comment: No problem! I'll update my answer. :)
Comment: I accidentally forgot the factor of $6$. I've fixed the addendum. I hope this helps.
Answer: For a function $f$, the definition of the Taylor Series of $f$ is:
$$\text{Taylor}(f)=\sum_{n \ge 0}\frac{f^{(n)}(a)}{n!}(x-a)^n, $$
where $f^{(n)}$ indicates the $n$th derivative of $f$ with $f^{(0)}=f$.
The problem, then, reduces to the following: Is there an $n$th derivative of $f(x)=\frac{6}{x}$? (More aptly, since $6$ is a constant: Is there an $n$th derivative of $\frac{1}{x}$? If so, what is it?)
Let's do a table of values:
$$
\begin{align}
\frac{d}{dx}\frac{1}{x}&=-\frac{1}{x^2}\\
\frac{d^2}{dx^2}\frac{1}{x}&=2\frac{1}{x^3}\\
\frac{d^3}{dx^3}\frac{1}{x}&=-6\frac{1}{x^4}\\
&\ldots
\end{align}
$$
This pattern seems to suggest $$\frac{d^n}{dx^n}\frac{1}{x}=(-1)^{n}n!\frac{1}{x^{n+1}}.$$
Let's prove this via induction on $n$. The base case trivially true. Assume the induction hypothesis for $n=k$.
$$
\begin{align}
\frac{d^{k+1}}{dx^{k+1}}\frac{1}{x}&=\frac{d}{dx}\frac{d^k}{dx^k}\frac{1}{x}\\
&=\frac{d}{dx}(-1)^kk!\frac{1}{x^{k+1}}\\
&=(-1)^kk!(k+1)(-1)\frac{1}{x^{k+2}}\\
&=(-1)^{k+1}(k+1)!\frac{1}{x^{k+2}}.
\end{align}
$$
Thus, via induction, we see this is correct!
Can you take this from here? Apply the $n$th derivative and the definition of $\text{Taylor}(f)$.

Okay, so you have the following pieces of information: $a=-4$, $f^{(n)}(x)=(-1)^nn!\frac{1}{x^{n+1}}$, and the definition of the Taylor Series. You simply substitute these into the definition as follows:
$$
\text{Taylor}(f)=6\sum_{n \ge 0}\frac{(-1)^nn!\frac{1}{a^{n+1}}}{n!}(x-a)^n=6\sum_{n \ge 0}\frac{(-1)^nn!\frac{1}{(-4)^{n+1}}}{n!}(x-(-4))^n . . .
$$
Try to go from here and simplify this. :)
Comment: Thank you for the lovely question! :-)
Answer: Refer to the definition of Taylor Series. You will have to evaluate your derivatives at $a=-4$.


Set ordered in two different ways.

Question: First of all i must inform you that this is general question, so i would like to know only general information.
Let $A, B$ be some sets and let $C\subseteq A\times B$.
Let $(a,b) , (c,d) \in C$
There are two different orders:

$(a,b)\le_{1}(c,d) \iff a\subseteq c$
$(a,b) \le_{2}(c,d) \iff b\subseteq d$

Consider now the structure $P=(C, \le_{1}, \le_{2})$. It is different from ordinary partially ordered set, because of the one extra order

Is there any known theory that tells about the structure above?

I would like to know some PDF or books about this structure, its properties and known results.
Regards
Answer: Those relations $\leq_1$ and $\leq_2$ are not partial order relations;
for example, with $b\neq d$, we have
$$(a,b) \leq_1 (a,d) \quad\text{ and }\quad (a,d) \leq_1 (a,b).$$
These are quasi-orders (also pre-orders).
I don't know of any book discussing them, or freely available pdf, but here are two articles which include something about them, including that structure with two quasi-orders:

A. Urquart, A topological representation theory for lattices, Algebra Universalis, 8 (1978) 45-58,
G. Markowski, The factorization and representation of lattices, Trans. Amer. Math. Soc., 203 (1975) 185-200.

Set ordered in two different ways.


Difference between p-value of chi-squared calculation, and p-value in "critical value" lookup table

Question: I am learning about chi-squared. It has two steps; a) chi-squared calculation b)  critical value
When I calculate chi-squared, the output includes a) chi-squared statistic (220.5) and b) a p-value (1.315...e-48):
<code>chisquare_result = stats.chisquare(df['observed'], df['expected'])
chisquare_result
# Output : Power_divergenceResult(statistic=220.5, pvalue=1.3153258948574585e-48)
</code>
When I lookup the critical value, my course materials describe my inputs as a) degrees of freedom, and b) a concept described as a p-value (where we used typical threshold 0.05).
<code># Desired p-value is 0.05, and (1-0.05) = 0.95
p_value =  0.05
critical_value = stats.chi2.ppf(q=(1-p_value), df=2)
# Output: 5.991464547107979
</code>
My questions:

Are the bolded "p-values" I mention above; are they both truly p-values?
a) If they are both p-values, what's the difference between them, why don't they each have the same value?
b) If they are not both p-values; what's the difference between them?
If I can get a p-value as output when calculating chi-squared, why do I need to calculate a critical value?
a) In other words; why isn't the p-value from chi-squared sufficient to reject/fail-to-reject Null Hypothesis?
Comment: The second thing is not a p-value. It's a significance level. You choose it before you see data. A p-value is something you calculate from the data.
Comment: To be clearer, then: The thing where you say "p_value =  0.05" ... that thing is not a [p-value](https://en.wikipedia.org/wiki/Statistical_hypothesis_testing#Interpretation). It is a significance level.
Comment: @Glen_b ; the second thing is not a p-value; if we subtract it from 1, it produces a p-value, right? In fact, it produces a p-value *I could compare to my own "choose before you see the data" p-value*, to decide if my chi-squared test is reliable.
Comment: In other words, I could compare `critical value` for an acceptable p, to `chi-squared` statistic; (**black line** in attached image): `chi-squared` value is greater than `critical value` = can reject null hypothesis.

OR I could compare the `p-value` of a `chi-squared` calculation, to an acceptable `p`  (**purple line** in attached image) ; if `chi-squared p-value` is *less* than acceptable `p`, = can reject null hypothesis. These two approaches will always lead to same conclusion.https://i.postimg.cc/zvvnK69y/2019-04-09-11-54-39-Ins-Chi-square.png
Comment: OK, so it's a wording thing? The code should be written like this: `# Desired significance level is 0.05, and (1-0.05) = 0.95;

significance_level =  0.05;

critical_value = stats.chi2.ppf(q=(1-significance_level), df=2);`

And I can compare this `0.05` which is `significance level`, to the `chi-squared p-value` of `0.046` ; since the latter is smaller than the former; I can reject null hypothesis?
Comment: OK I think you're trying to impress what the Wikipedia article describes as "If the **p-value** is not less than the **chosen significance threshold** ...  then the evidence is insufficient to support a conclusion...."  so they're different concepts -- one is a calculation, the other is your choice -- but, you must compare the values together to reject/fail-to-reject null hypothesis. I confuse these ideas by calling the significance threshold "my choice of acceptable p-value". Let me know if this sounds wrong.
Comment: That's about the size of it, yes.
Answer: 5.99 is the critical value for 2 degrees of freedom and p = 0.05. So any value of $\chi^2$ greater than 5.99 is significant at the 0.05 level.
220.5 is the critical value for 2 degrees of freedom and p = $1.315 \times 10^{-48}$ so any value greater than 220.5 is significant at that level.
The difference is that in one case you are specifying the level first (0.05) and asking what value of $\chi^2$ is significant beyond that level and in the other case you are starting from your obtained value of $\chi^2$ and asking what the critical value would have been.
Comment: Infinity probably means it gave up or is a programming error and the other one is giving you the tail you did not expect. I do not use whatever software it is you are using so cannot help with how you reverse it.
Comment: So if I calculated the critical value for a p-value of $1.315 \times 10^{-48}$  , that is, same code as above, but a much smaller p-value: `stats.chi2.ppf(q = (1-1.3153258948574585e-48), df = 2)` - the result would be 220.5 ? In other words, I *can* skip the critical-value calculation, thanks to Python's *giving me the associated p-value for a chi-squared calculation, which allows me to decide if the p-value is sufficiently low*; doing the critical-value calculation for a higher p-value is redundant.
Comment: But this: `stats.chi2.ppf(q = (1-1.3153258948574585e-48), df = 2)` produces output of `inf` ( I was expecting output of `220.5`)

And this: `stats.chi2.cdf(220.5, 2)` produces output of `1.0` (I was expecting output of `1.315...e-48`

I'm not sure why scipy `pdf(...)` and `cdf(...)` *cannot* calculate the critical value / p-value for a very low p-value (do `inf`/`1` respectively), but the `chisquare(...)` *can* calculate it,
Comment: Either way I think I understand what @mdewey is saying re: my questions

1) these p-values *are* both p-values ,

1a) They don't have the same value because the `0.05` specifies the acceptable p-value first, whereas the `1.31e-48` produces the p-value, and then you decide if it's acceptable.

2) I *can* skip the critical value calculation, if I get the p-value of the chi-squared calculation


Adding elements in bulk on JointJS leads to performance issues

Question: We are trying to build a Visualization Framework using JointJS (we are not using Rappid). SVG is used to render graphical data on the browser.
We have a scenario where we have a model with approximately 4500 ports.
We have used ports as elements and NOT as attributes. Meaning to say that we have embedded ports as cells inside a model. There is a certain reason why need such a setup.
When such a model is added onto the graph, it takes roughly 8 to 9  seconds to render. Once the model is rendered, moving and repositioning the model works okay. However, when we try to add further models the browser tends to crash.
This is how we have created the Paper object
 function createPaper(options) {
     var paper = new joint.dia.Paper({
        el: options.el,
        width: options.width,
        height: options.height,
        model: options.graph,
        gridSize: 1,
        label:options.name,
        async : { batchSize: 250}
    });
    return paper;
 }

This is how we have created the model
function createModel(options) {
    var model = new joint.shapes.devs.Model({
        position:options.position,
        size:options.size,
        attrs:  options.attrs
    });
    return model;
}

This is how we have created the port as a custom model
    joint.shapes.custom = {};

    joint.shapes.custom.Port = joint.shapes.basic.Generic.extend(_.extend({},    joint.shapes.basic.PortsModelInterface, {

    markup: '<g class="rotatable"><g class="scalable"><path class="port-body" d = "M 0 0 L 0 0 L 15 5 L 0 10 L 0 10 z"></path></g><text class="port-label"/></g>',

    defaults: joint.util.deepSupplement({

    type: 'devs.Port',
    size: { width: 10, height: 10 },
    position : {x : 0, y : 0},
    attrs: {
        '.': { magnet: false },
        '.body': {
            width: 150, height: 250,
            stroke: '#000000'
        },
        '.port-body': {
            r: 5,
            magnet: true,
            stroke: '#000000',
            fill : 'yellow'
        },
        text: {
            'pointer-events': 'none'
        },
      }

   }, joint.shapes.basic.Generic.prototype.defaults),

}));

 joint.shapes.custom.PortView = joint.dia.ElementView.extend(joint.shapes.basic.PortsViewInterface);

 function createPort(options){
    var port=new joint.shapes.custom.Port({
        position:options.position,
        size:options.size,
        attrs:  options.attrs
    });

    return port;
}

Below is the way we are adding models and ports to the graph
                    var cells = [];
                    var model = createModel(options);
                    //Add the cell to the graph
                    cells.push(model);

                    var totalInports=options.inPorts.length;
                    var totalOutports=options.outPorts.length;

                    //Add the inports
                    for (var portIndex = 0; portIndex < totalInports; portIndex++) {
                        port = createPort(options.inPorts[portIndex]);
                        model.embed(port);
                        cells.push(port);
                    }

                    //Add the outports
                    for (var portIndex = 0; portIndex < totalOutports; portIndex++) {
                        port = createPort(options.outPorts[portIndex]);
                        model.embed(port);
                        cells.push(port);
                    }
                    graph.addCells(cells);

Could anybody kindly give some answers to the below questions -
Are we using the paper and models in the right way ?
Are there better ways of adding cells to the graph which could improve the
   performance ?
Thanks in Advance
Answer: I know that this is an old question that has been left unanswered for a long time. My take is to use:
graph.fromJSON or graph.addCells(/*Array of json cells*/)

Then, try to translate all the operations as a compound json that will be passed to graph.fromJSON or graph.addCells.


How to prove $\int_{0}^{\infty} \sqrt{x} J_{0}(x)dx = \sqrt{2} \frac{\Gamma(3/4)}{\Gamma(1/4)}$

Question: I was reading a paper in which they used the following relation and I am curious to know how it can be proved.
$$\int_{0}^{\infty} \sqrt{x} J_{0}(x)dx = \sqrt{2} \frac{\Gamma(3/4)}{\Gamma(1/4)}$$
where $J_{0}(x)$ is a Bessel function of the first kind and $\Gamma(x)$ is the gamma function.
I tired to prove it using the integral form of the Bessel function as: $J_{0}(r)=\int_{0}^{2\pi}e^{-ir \cos(\theta)}d\theta $ and the integral form of Gamma function as: $\Gamma(r)=\int_{0}^{\infty}x^{r-1}e^{-x}dx$ but I couldn't.
Then, I tried to prove it using the series representation of the Bessel function as $J_{0}(x)= \sum_{k=0}^{\infty} \frac{(-1)^k}{(\Gamma(k+1))^2} (\frac{x}{2})^{2k}$ in the integral but I couldn't still prove it.
I don't know if a complex contour integral formula for the Bessel function and Gamma function can be useful to prove this, but anyway I'm trying every thing.
Could you please help me to prove this relation?
Thank you
Comment: As already remarked, the integral in the LHS is not convergent, strictly speaking. The RHS is the regularized value $$\lim_{\lambda\to 0^+}\int_{0}^{+\infty}\sqrt{x}\,J_0(x)\,e^{-\lambda x}\,dx$$ which can be computed through the Laplace transform and Euler's Beta function.
Answer: Well, we have:
$$\mathcal{I}_{\space\frac{1}{2}}:=\int\limits_0^\infty x^\frac{1}{2}\cdot\mathscr{J}_0\left(x\right)\space\text{d}x\tag1$$
Using the 'evaluating integrals over the positive real axis' property of the Laplace transform, we can write:
$$\mathcal{I}_{\space\frac{1}{2}}=\int\limits_0^\infty\mathscr{L}_x\left[\mathscr{J}_0\left(x\right)\right]_{\left(\text{s}\right)}\cdot\mathscr{L}_x^{-1}\left[x^\frac{1}{2}\right]_{\left(\text{s}\right)}\space\text{d}\text{s}\tag2$$
Using table of selected Laplace transforms:
$$\mathcal{I}_{\space\frac{1}{2}}=\int\limits_0^\infty\frac{1}{\sqrt{1+\text{s}^2}}\cdot\frac{1}{\text{s}^{1+\frac{1}{2}}}\cdot\frac{1}{\Gamma\left(-\frac{1}{2}\right)}\space\text{d}\text{s}=-\frac{1}{2\sqrt{\pi}}\int\limits_0^\infty\frac{1}{\sqrt{1+\text{s}^2}}\cdot\frac{1}{\text{s}^\frac{3}{2}}\space\text{d}\text{s}\tag3$$

And now, we can use:
$$\int\limits_0^\infty\frac{1}{x^\text{n}}\cdot\frac{1}{\sqrt{1+x^2}}\space\text{d}x=\frac{\displaystyle\Gamma\left(\frac{1}{2}-\frac{\text{n}}{2}\right)\cdot\Gamma\left(\frac{\text{n}}{2}\right)}{\displaystyle2\sqrt{\pi}}\tag4$$
When $0<\Re\left(\text{n}\right)<1$.

So, we end up with:
$$\mathcal{I}_{\space\frac{1}{2}}=-\frac{\displaystyle1}{\displaystyle2\sqrt{\pi}}\cdot\frac{\displaystyle\Gamma\left(\frac{1}{2}-\frac{3}{2}\cdot\frac{1}{2}\right)\cdot\Gamma\left(\frac{3}{2}\cdot\frac{1}{2}\right)}{\displaystyle2\sqrt{\pi}}=\frac{\displaystyle\Gamma^2\left(\frac{3}{4}\right)}{\displaystyle\pi}\tag5$$
Answer: The Bessel function of the first kind has a series expansion,
$$J_0(x)=\sum_{k=0}^\infty\frac{(-1)^k}{(k!)^2}\left(\frac{x}{2}\right)^{2k}$$
hence by the slight extension of Ramanujan's master theorem,
$$\int_0^\infty x^{s-1}J_0(x)\ dx=2^{s-1}\frac{\Gamma\left(\dfrac{s}{2}\right)}{\Gamma\left(1-\dfrac{s}{2}\right)}$$
taking $s=3/2$,
$$\int_0^\infty x^{1/2}J_0(x)\ dx=2^{1/2}\frac{\Gamma\left(\dfrac{3}{4}\right)}{\Gamma\left(\dfrac{1}{4}\right)}.$$


Show that a random variable Y is infinite

Question: I have the following question where I am required to show that a random variable is almost surely infinite:
Let $Y$ be a non-negative random variable, given that
$$
E[e^{-Y}]=0,
$$
show that $Y$ is almost surely infinite.
I know that "$Y$ is almost surely infinite" is equivalent to showing that
$$
P[Y=\infty] = 1.
$$
I have attempted to use the Markov Inequality
$$
P[e^{-Y}\geq\epsilon] \leq \frac{E[|e^{-Y}|^r]}{\epsilon^r},
$$
we can pick $r=1$ and we know $e^{-Y}>0$ giving
$$
P[e^{-Y}\geq\epsilon] \leq \frac{E[e^{-Y}]}{\epsilon} = 0 \implies P[e^{-Y}\geq\epsilon] = 0.
$$
I think that the next step involves showing that
$$
P[Y>k] = 1,
$$
however I am unsure how to do so rigorously, and where I would go from here.
I would really appreciate any help steering me in the right direction. Thanks
Answer: Without using Markov's inequality, you can proceed by writing
$$\mathbb{P}[Y= \infty] = \mathbb{P}(\bigcap_{k=1}^\infty \{Y > k\}) = \lim_{k \to \infty} \mathbb{P}(Y > k)$$
This implies that if $\mathbb{P}(Y = \infty) < 1$ then there exists a $k$ such that $\mathbb{P}(Y>k) < 1$. Equivalently, for this $k$, $\mathbb{P}(Y \leq k) > 0$. But then, since $e^{-Y} \geq 0$ and $x \mapsto e^{-x}$ is decreasing, we can write
$$0 < e^{-k} \mathbb{P}(Y \leq k) \leq \mathbb{E}[e^{-Y}] = 0$$
which is a contradiction.
Comment: Thanks, guess I was barking up the wrong tree. Forgive me if this is a stupid question, can you explain why $e^{-k}P[Y\leq k] \leq E[e^{-Y}]$ ?
Comment: Sure! You can write $$E[e^{-Y}] = E[e^{-Y}1_{\{Y \leq k\}}] + E[e^{-Y}1_{\{Y > k\}}] $$ The second term is non-negative and the first term satisfies $$E[e^{-Y} 1_{\{Y \leq k\}}] \geq e^{-k} P[Y \leq k]$$ since if $Y \leq k$ then $e^{-Y} \geq e^{-k}$.


Writing a .NET console application with GUI wrapper

Question: I am writing a .NET console application to upload files. However, I might have to create a GUI front end for this application in the future. How can I best design my console application with this in mind? Passing arguments will be simple, but how can I show progress and errors in the GUI?
Answer: I would suggest that instead of trying to make your console application be the point of integration for a front-end, instead create a common shared library to host all the business logic, and instead integrate your UI at that level.
Answer: Keep your application presentation and logic decoupled.  You can design your application around interfaces.  For example, if you create and use an IProgress interface for reporting progress, your console application can use Console.Write to report progress, but your GUI application, later, can just use the same interface to update a progress bar.
Answer: Don't make the GUI interact with the console app. Separate the logic from interface and make each interface interact with the common logic library(ies)


java spring session how to custom cookie key

Question: I using spring session HttpSession, how can I custom cookie key, I tried this solution: Custom cookie name when using Spring Session. but it does not work, the name is SESSION still.
my config like below:
<context:annotation-config/>
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<context:property-placeholder location="classpath:/env/env_test.properties"/>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
     p:port="${spring.redis.port}" p:hostName="${spring.redis.host}"/>
<bean id="mapSessionRepository" class="org.springframework.session.MapSessionRepository" />
<bean id="sessionRepositoryFilter"
  class="org.springframework.session.web.http.SessionRepositoryFilter">
  <constructor-arg ref="sessionRepository"/>
  <property name="httpSessionStrategy">
    <bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
      <property name="cookieName" value="_session_id" />
    </bean>
  </property>
</bean>

Answer: You just need to add below bean to create custom cookie.
    <bean class ="org.springframework.session.web.http.DefaultCookieSerializer">
            <property name="cookieName" value="JSESIONID"></property>
    </bean>

JESSIONID - Custom Cookie Name

    Please remove below configuration fr`enter code here`om xml file.

    <bean id="sessionRepositoryFilter"
      class="org.springframework.session.web.http.SessionRepositoryFilter">
      <constructor-arg ref="sessionRepository"/>
      <property name="httpSessionStrategy">
        <bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
          <property name="cookieName" value="_session_id" />
        </bean>
      </property>
    </bean>

Answer: You have to create a bean with class
org.springframework.session.web.http.DefaultCookieSerializer

So inside of that bean, you define your custom properties, after you declare that bean as a property of the following:
org.springframework.session.web.http.CookieHttpSessionStrategy

By example:
<bean id="yourCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
        <property name="cookieName" value="yourCustomName"/>
        <property name="cookiePath" value="yourCustomPath"/>
        ...
</bean>
<bean id="cookieHttpSessionStrategy" class="org.springframework.session.web.http.CookieHttpSessionStrategy">
        <property name="cookieSerializer" ref="yourCookieSerializer"></property>
</bean>


What is the algorithmic complexity of knot equivalence?

Question: Question. Given two (tame) knots by their link diagrams, what is the algorithmic complexity (e.g. time in the size needed to store the link diagrams) to decide if the represented links are isotopic?
There are several results on related problems in computational knot theory, cf. wikipedia, which imply that knot equivalence is at least NP-hard and BQP-hard.
On the other hand it is known that deciding whether two closed, oriented 3-manifolds given by triangulations are homeomorphic is only known to be elementary recursive (ER), cf. Kuperberg's work.
It is known that equivalence (isotopy) of knots can be reduced to equivalence (homeomorphy) of their knot complement 3-manifolds, which suggests that knot equivalence should also be in ER. There are some obstacles to that which are not clear to me. First given a link diagram for a knot one would have to produce effectively a triangulation of the knot complement and the growth in memory size from link diagram to triangulation has to be controlled compatible with ER. Second the knot complement is oriented but not closed, its boundary being precisely a tubular neighborhood of the knot.
It seems to me reasonable to believe that the growth in size from link diagram to triangulation should be manageable (at most exponential or even polynomial, say) and that Kuperberg's result should be extendable to oriented manifolds with boundary. This answer to a mathoverflow question indeed claims that knot equivalence is in ER.
On the other hand, ER is quite a large class. Given that, e.g., recognizing the trivial knot is in $\text{NP}\cap\text{co-NP}$ it seems plausible that the actual complexity of knot equivalence is much lower.
ER consists of problems that admit algorithms of time complexity a tower of exponentials (of order $k$) in a polynomial in the input size.
Upper bounds. Are their any results on the size of $k$? Are there any algorithms to decide knot equivalence with better complexity and without detouring to equivalence of knot complements known?
Lower bounds. Are there better lower bounds known than NP-hardness or BQP-hardness? E.g. Gröbner bases are EXPSPACE-complete, is it known that such a problem is reducible to knot equivalence?
Comment: Take sa look at these slides: https://people.maths.ox.ac.uk/lackenby/quasipolynomial-talk.pdf. While they focus on the unknotting problem, Lackenby provides you with a very good survey of known results.
Answer: To your questions about upper bounds: turning a diagram into a triangulation can using linearly many tetrahedra, purely locally -- you explicitly construct a gadget to put in at each crossing, containing I think eight tetrahedra. It's not too hard to construct yourself.
(Going the other way -- from triangulation to diagram -- is where it can blow up exponentially; torus knots exhibit this.)
There aren't many complete knot invariants, so if you're determining if two knots are isotopic, you're probably either searching Reidemeister moves (in which case, how do you bound that search? we don't currently know) or, as you say, you're deciding homeomorphism of (oriented) knot complements. One way of extending the 3-manifold homeomorphism algorithm to oriented 3-manifold homeomorphism is to extend the algorithm to decide homeomorphism of 3-manifolds with boundary pattern. See Chapter 6 of Matveev's book Algorithmic Topology and Classification of 3-Manifolds for an explanation of this approach, which also allows you to decide link isotopy. (Roughly speaking, for knots, you decorate the boundary with a graph that is not symmetric under an orientation flip.) Although of course it doesn't cover progress since 2005, that is generally a very good book for learning about triangulation-focused approaches to 3-manifold algorithms.
In terms of results on the size of $k$, we can pull this back to giving bounds on the runtime of 3-manifold homeomorphism for manifolds with a single torus boundary component. Scull proved that the problem can be solved for closed hyperbolic manifolds in runtime at most $2^{2^{t^{O(t)}}}$, where $t$ is the number of tetrahedra in the two triangulations (arXiv:2108.00779).
I don't know of much work on the case with boundary, aside from my own work on Seifert fibered spaces (arXiv:2306.04612) where I prove that the homeomorphism question is in NP, so the runtime is at most $2^{poly(n)}$. It wouldn't be hard to make that polynomial explicit. This case covers isotopy between $K$ and $J$ where $J$ is a torus knot. You might also be interested in Haraway-Hoffman's work (arXiv:1907.01675
) that determining if a manifold (so hence a knot) is not hyperbolic is in NP, assuming $S^3$ recognition is in coNP (which is currently known to be true if GRH is true by work of Zentner).
I would guess that the problem should be in NP, so runtime at most $2^{poly(n)}$, but that is open. If you fix a link $L$, Lackenby has announced that the $L$-recognition problem is in NP (see Section 4.4 of "Elementary Knot Theory" in Lectures on Geometry (Clay Lecture Notes), Oxford University Press (2017) but I don't know of a published proof.


AndroidStudio - Trocar url por imagem em local path do projeto

Question: Boa tarde pessoal,
Tenho uma string que uso para setar a imagem de alguns botões:
 String imagem[] = {"https://cdn.pixabay.com/photo/2015/12121.jpg",
            "https://cdn.pixabay.com/photo/2016/0555555.jpg"};

Baixei as imagens e salvei no diretório src\main\imagens dentro do projeto.
Como posso substituir na string acima a url pelo path local?
Segue o código detalhado:
No meu onCreateView:
mAdapter = new ModuloAdapter(lista(), getActivity());

private List<ItemModulo> lista() {

    String titulo[] = {"A", "B", "C", "D"};

    String imagem[] = {"https://cdn.pixabay.com/photo/2015/10/19/20/01/5555.jpg",
              "https://cdn.pixabay.com/photo/2016/02/11/23/24/5554.jpg",
              "https://cdn.pixabay.com/photo/2016/11/08/05/29/44141.jpg",
              "https://cdn.pixabay.com/photo/2016/11/08/05/29/4412241.jpg"};

    for (int i = 0; i < titulo.length; i++){
            ItemModulo item = new ItemModulo();
            item.setLista(lista[i]);
            item.setImagem(imagem[i]);
            itemList.add(item);
    }

    return itemList;
}

Comment: Detalha mais como você está setando a imagem nos botões
Comment: editei com mais detalhes
Comment: Ainda to meio confuso, o que você quer é que em tempo de execução o aplicativo irá baixar as imagens pro aparelho, e essas imagens salvas será usada no botão?
Comment: não eu vou usar a imagem já baixada e colocada no drawable
porém não estou conseguindo usar a imagem direto somente com o link....gostaria de colocar o local path da imagem na string ao invés da url
Answer: Olá, o certo é deixar imagens do projeto na pasta drawable e alterar a nomenclatura dela pra não começar com número:
src/main/res/drawable
Você pode chamar as imagens da seguinte maneira:
        //adiciona suas imagens em um array de inteiros ao invés de String
        int[] imagem = new int[]{R.drawable.imagem1, R.drawable.imagem2, R.drawable.imagem3};

Logo, no seus getters and setters altera o setImagem e o getImagem para int
no seu for para enviar a lista mantém o mesmo
Agora aqui vai o truque, na hora de recuperar esse inteiro da imagem faça o seguinte:
Drawable drawable = getResources().getDrawable(item.getImagens());

Utiliza esse drawable pra setar a imagem no botão.
A classe R é responsável pela comunicação entre xml e java, e o diretório drawable onde fica armazenadas as imagens do projeto.
Comment: Espero que tenha o ajudado, qualquer dúvida só falar, e se a resposta foi útil pra vc, marque-a como útil ou como respondida. Abraço
Comment: Obrigado pela resposta amigo. mas não consegui fazer assim funcionar. traz a imagem em vazia. Eu utilizo a string da seguinte maneira tenho um array com os nomes e o array aí de cima com as imagens. A imagem está no drawable
for (int i = 0; i<tipo.length; i++){
            ItemModulo item = new ItemModulo();
            item.setRecipe(tipo[i]);
            item.setImg(img[i]);
            itemList.add(item);
        }
Comment: @user147627 eu editei minha resposta, se ainda não tiver conseguindo, edita sua pergunta e coloca como você tá recebendo essa imagem no getImagem e e enviando para o botão. Eu fiz um projeto simples com 3 exemplos diferentes com o mesmo resultado, caso queira comparar com seu código me avisa que coloco no github e mando aqui na minha resposta.


How to register type adapter for boolean.class/Boolean::class.javaPrimitiveType and Boolean.class/Boolean.class.java

Question: I am trying to convert this Java sample into Kotlin:
Gson gson = new GsonBuilder()
        .registerTypeAdapter(Boolean.class, new JsonStrictBooleanDeserializer())
        .registerTypeAdapter(boolean.class, new JsonStrictBooleanDeserializer())
        .create();

val gson = GsonBuilder()
        .registerTypeAdapter(Boolean::class.java, JsonStrictBooleanDeserializer())
        .registerTypeAdapter(Boolean::class.javaPrimitiveType, JsonStrictBooleanDeserializer())
        .create()

However, they do not appear to behave the same. I decompiled the Kotlin sample and it appears that only one type adapter is being registered:
(new GsonBuilder())
        .registerTypeAdapter((Type)Boolean.TYPE, new JsonStrictBooleanDeserializer())
        .registerTypeAdapter((Type)Boolean.TYPE, new JsonStrictBooleanDeserializer())
        .create();

What is the correct way of registering a type adapter for boxed and primitive booleans in Kotlin?
Comment: Are you aware of this https://meta.stackoverflow.com/questions/374546/can-i-somehow-see-what-i-commented-or-answered-to-a-question-deleted-by-author ?
Comment: @Yunnosch Thank you for notifying about ;)
Answer: Both uses of the Boolean class you have are being compiled to the primitive boolean type. You need to use javaObjectType in addition to javaPrimitiveType, like so:
val gson = GsonBuilder()
        .registerTypeAdapter(Boolean::class.javaObjectType, JsonStrictBooleanDeserializer())
        .registerTypeAdapter(Boolean::class.javaPrimitiveType, JsonStrictBooleanDeserializer())
        .create()

This will result in the first call using Boolean.class and the second using Boolean.TYPE (the Class for the primitive boolean).


How to add contacts from your application and save it in the addressbook?

Question:
Possible Duplicate:
How do you add contacts to the iPhone Address book with monotouch?

I have searched, and havnt find any tutorials about how to save contacts from your application  in your addressbook.
If you have some contacts in your application you may want to save them in your phones contact list so you have all the contacts at the same place.
Anything that can help is good, tutorials or whatever.
Comment: this has been discussed before - see above question
Answer: A useful starting point and reference is the Address Book Programming Guide.  In particular you'll want to invoke:

ABAddressBookAddRecord
  Adds a record to an address book.
<code>bool ABAddressBookAddRecord (
    ABAddressBookRef addressBook,
    ABRecordRef record,
    CFErrorRef *error
);
</code>
Parameters

addressBook
  The address book to which record is added.
record
  The record to add to addressBook.
error
  On error, contains error information. See "Address Book Errors."

Return Value
true when successful, false otherwise.
Availability
  Available in iOS 2.0 and later.
Declared In
  ABAddressBook.h


Does grails / hibernate store Dates with milliseconds in PostgreSQL?

Question: I'm currently using grails with classes storing java.util.Date fields als DATETIME. However I need the precision / milliseconds to be stored as well which I think is not possible with MySQL.
If I switch to PostgreSQL, will it store my Dates with millisecond precision (or is it easy to configure it this way)?
Answer: Yes, Hibernate / PostgreSQL can also store milisecond precision, no problem. Use the Hibernate timestamp datatype.
Answer: Yes, since MySql 5.6.4 you can use
   DATETIME(3) for milliseconds, or
   DATETIME(6) for microseconds
TIME and other types also now support precision.
http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html


Prevent assignment in conditional expression in visual studio 2010

Question: Given the following code:
    bool test = false;
    bool test2 = true;

    if (test = test2)
    {

    }

I want to get a warning when compiling this code as probably I wanted == instead.
I don't get a warning from compiler and can't find a code analysis rule anywhere for it (fxcop or stylecop).
The closest compiler warning I found was CS0665:
http://msdn.microsoft.com/en-us/library/c1sde1ax%28v=vs.90%29.aspx
But this only triggers if I do:
if (test = true)

Can anybody point me to an existing rule or tool I can integrate into my build process that will trigger on this?
Is there a good reason why we would want to allow this first construct?
Comment: If you have this problem a lot, then you've got bigger problems as well. You'd do well to address all the similar problems (low-experience developers, insufficient code review and insufficient QA).
Comment: FWIW, its not really VS that is allowing this as an assignment, but .NET.  Also, ReSharper catches this, but does not throw a warning by default.  It could be configured to do so however.
Comment: A reason you _could_ want to use this sort of construct is something like `string bar; if (foo == null || (bar = GetABar()) == null) return;`. This keeps you from either eagerly evaluating GetABar() or adding an assignment line and another if.
Answer: ReSharper will display a warning for this, saying:
Expression is always true

I would suggest using 'Configure inspection severity' and upgrading it to an Error
Comment: @DieterDHoker do you use ReSharper?


Is --overrides an accepted option in drush 8.x?

Question: I'm creating a build script and would like to include the --overrides flag as describe in the documentation. I'm using Drupal 8.0.0 and Drush 8.0.1 and I get the following:

drush make build.make.yml ~/Sites/built --prepare-install --overrides=dev.make --no-cache -y -vvv
Unknown option: --overrides.  See 'drush help make' for available options. To suppress this error, add the option --strict=0.

Am I missing something? Is this functionality not built yet?
Comment: Corrected an edit that removed tags from title. The tags are needed for the sentence to make sense.
Answer: It appears to be in the master branch, but not yet in 8.0.x.
Comment: The relevant commit: https://github.com/drush-ops/drush/commit/60ac0a23010a95cf684a3fee2c094557c0bd488b


How can I view Office files in Windows Phone app?

Question: I want to develop an Windows Phone 8.1 app which can view office files without launch the other apps.
But I can not find any free SDK or framework or component to do that.
So, doesn't Microsoft provide any way to developer just viewing Office document in Apps?
Answer: There is no standard tools for viewing Office documents in your application. You can only open the file in Office.
But you can use alternative library.
For example
C1Excel library or
Essential Studio for Windows Phone
Comment: Is there any library that is able to open and view powerpoint (.ppt) file?


How to change drupal commerce views like checkout,payment?

Question: i configured drupal commerce module all working fine.question is how to format or design the checkout page,billing page,review page,payment page. i can add more data but how change existing data..i make tpl file for related name but by this we can add more data but how to change existing data plz tell me ASAP.
in detail:actually drupal commerce provides four page for checkout (1)checkout(2)billing address(3)order review(4)payment all are working fine problem is: can i change the all four page's design and add more data to it.how can i find out the html of these four page. i can't figure out by making template file of those four page.
Comment: Please explain your question. Not able to get your requirement.
Answer: Have you learned Views?
you can try change default views shoppingcart,checkout page,billing page,review page etc.
Eg: to modify shopping cart block you can go to
http://your.site/admin/structure/views/view/commerce_cart_block/edit


Comparing percentages of time series with unequal lengths - Is that right?

Question: I am reviewing a work of a colleague of mine.
He graphed two different time series for the same product - the first one (historic figures) takes into account 4 years, while the second one (estimates) has 3 years.
He then added percentages comparisons for the growth rates - almost 15% for the 4-year time series and 16% for the 3-year.
Now I think that comparing 2 time series with unequal lengths might be misleading. For instance, if I use the same length, the new percentages become  10% and 16%, which I think gives a much clearer picture of how the situation will evolve.
So, 2 questions:
1) Am I correct in thinking that it is better to use the same time lengths between the two for visualization purposes?
2) Is there any statistical way to 'standardize' the results (in terms of calculating percentages) of time series with different lengths?
Thanks!
Answer: You're intuition is right in my opinion.
1: The same length on the graph should correspond to the same amount of time but this doesn't stop one line from being longer than another line.
2: As for the growth rates: I think you would do better to measure them on a yearly basis so you compare apples and apples.


Change and outliers detection by means ARIMA (Tsay procedure)

Question: I have a question about automatic on-line outliers and change point detection in time series data.
Now I read the paper:
"Outliers, Level Shifts, and Variance Changes in Time Series" Ruey S.Tsay
It's written in the abstract: "..The methods employed are extremely simple yet useful.."
But for me it's not very easy to understand these methods and especially to implement.
If someone can give me a hint how to do that in R/Matlab etc I will be highly appreciated.
Answer: Alexandr,
You need to consider different strategies when building the model and trying to identify outliers.  It is an iterative process.  Let me just put out some concepts that you need to consider.  Differencing, ARMA model structure, parameter changes in the model(ie CHOW test), changes in seasonality, changes in trend and TSAY's focus of outliers, level shifts and variance change.  Use WLS when you find a variance change.
We have programmed it.  It took us years to perfect as the TSAY work omitted other things as I have listed above.
You could use this free piece of software if you are looking just for level shifts.  It does a pretty good job. http://www.beringclimate.noaa.gov/regimes/


How to have optional split screen layout in HTML/CSS?

Question: I have a panel full of tiles that can be any length, including scrolling beyond the lower bounds of the viewport, so the vertical scroll is currently in use for this.
What I want to have, is an optional lower panel than can be shown or hidden at the users request, which will always take up the lower 25% of the screen. The tiles above should then shrink to a scrolling pane ABOVE this, so you can independently scroll the tiles, without changing the position of the lower panel.
So I need an outer container that is always 100% of the screen height, with no scrolling.
Within that, I want a panel of scrollable content. If this is the only panel visible, then it should take up 100% height of the outer container, giving the illusion that the main screen is scrolling.
When the lower panel is visible, the scrollable content should only take up the first 75% of the screen height and the scroll bar is only 75% of the height to reflect this. The lower 25% is the new panel which should be fixed. The lower panel should ALSO be independently scrollable. So you end up with two independently scrolling panels stacked on top of each other
I've tried to do this with flexbox but am not having any luck. Can anyone advise what I'm doing wrong?
Fiddle below
https://jsfiddle.net/cdg6815s/2/
.app-container {
  height: 100%;
  padding: 10px;
  background-color: blue;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.container {
  height: 80%;
  background-color: green;
  padding: 10px;
  flex: 0.8;
  overflow-y: scroll;
}

.logtailContainer {
  height: 20%;
  background-color: red;
  padding: 10px;
  flex: 0.2;
  overflow-y: scroll;
}

Comment: Just add `body, html {height: 100%; margin: 0;}` and probably `* {box-sizing: border-box;}` - check it [here](https://jsfiddle.net/skobaljic/m1rxL45v/1/)
Answer: If you use flex, you can use flex:1;or flex-grow:1 on the main container instead setting a fixed height and only set an height/min-height on the second container that can be hidden.
to fill the window, height:100vh and a margin reset for body is also efficient here.
if border and padding are involved, mind also the box-sizing model to include them in your sizing.
here is a demo with a checkbox to toggle hide/show for the second container and box-sizing to mind the padding of .app-container to calculate the 100vh height.

body {
  margin: 0;
}

.app-container {
  height: 100vh;
  padding: 10px;
  background-color: blue;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.contentpanel {
  background-color: green;
  padding: 10px;
  flex: 1;
  overflow-y: scroll;
}

.lowerpanel {
  height: 20%;
  background-color: red;
  padding: 10px;
  min-height: 4em;
  overflow-y: scroll;
}

/* demo purpose CSS to use input/label to toggle display of lowerpanel */
#hide {
  position: absolute;
  right: 100vw;
}

[for="hide"] {
  cursor: pointer;
  background: #bee;
  border: 1px solid;
  border-radius: 5px;
  padding: 0.25em;
  display: block;
  width: max-content;
  margin: auto;
}

#hide:checked~.lowerpanel {
  display: none;
}

  <input type="checkbox" id="hide">

    toggle red container

    App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

    Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

  </div
Answer: Edit: skobaljic's comment is a way simpler way to do this. I'm keeping this answer as it still works.
I'm assuming you want something like this:

* {
  box-sizing: border-box;
}

.b {
  height: 100vh;
  margin: 0;
  padding: 0;
}

.app-container {
  height: 100vh;
  padding: 10px;
  background-color: blue;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.contentpanel {
  max-height: 75vh;
  background-color: green;
  padding: 10px;
  flex: 0 1 75vh;
  overflow-y: scroll;
}

.lowerpanel {
  max-height: 25vh;
  background-color: red;
  padding: 10px;
  flex: 0 1 25vh;
  overflow-y: scroll;
}

      App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App tiles

 App
      tiles

 App tiles

 App tiles

 App tiles

      Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

 Logtail stuff

A few issues:

You are setting the .app-container to 100% height, but of what. You need to set a reference, so setting the height on the body/html is necessary.
flex property is shorthand - so you were setting the flex grow (as you may know), but that's the ratio to what it will grow. Setting the flex-basis property to the height might be the better way to go.
I changed the height values to vh units to use the viewport height as reference.
Setting max-height on your elements instead of height, allows for them to shrink/grow but stop at the specific height value.
Comment: Thanks for the advice. Just one last thing - the lower panel needs to be hidden or displayed on user preference. I was going to use display none/block - but currently with that CSS if the lower panel is hidden, the top panel only fills 75% of the height. I assume to get it to fill the whole screen if the lower panel isn't there, I change both 75vh to 100vh?
Comment: How are you toggling it? JS?


Como pegar nas cordenadas pegando a linha e alterando a colunda

Question: <code>   Set rgFound = Range("B1:B1000").Find(Sheets("FormAluguer").Range("E10"))
If rgFound Is Nothing Then
    resposta = MsgBox("Não encontrado.", vbYesNo + vbExclamation, "stock incorrecto")
Else
Dim mrange As String
Dim linha As Integer

mrange = rgFound.Address(RowAbsolute:=False, ColumnAbsolute:=False, External:=False)
 resposta = MsgBox("Foi encontrado em :" + rgFound.Row, vbYesNo + vbExclamation, "stock incorrecto")

End If
</code>

mrange retorna $b7 e eu queria pegar neste valor e reter o numero da
  linha neste caso 7 para depois fazer contas na coluna O linha 7 fazer
  contas

tentei rgFound.Address().row mas não funciona
Answer: O problema estava no operador de concatenar

resposta = MsgBox("Foi encontrado em :" + rgFound.Row, vbYesNo +
  vbExclamation, "stock incorrecto")

deve ser assim:

resposta = MsgBox("Foi encontrado em :" & rgFound.Row, vbYesNo +
  vbExclamation, "stock incorrecto")


Consistency and rates of convergence

Question: Suppose that I have two statistics that are known to be consistent , e.g :
$ S_{n} ^2 $ (biased sample variance about sample mean) and $ S_{n-1}^2$ (bessel-corrected sample variance, that is unbiased).
I know that bias and consistency are different things but my question is:

does the bias matter in how (slow or fast) the sequence converges?
Answer: To measure the speed of convergence of a consistent estimator to the parameter it estimates, you need to specify some measure that will quantify the closeness of the estimator and the parameter, so that you can measure the accuracy of the estimator at each $n$, and for a given parameter value.  An example of this would be to use the mean-square-error (MSE), given by:
$$\text{MSE}(\hat{\theta}_n) = \mathbb{E} \Big( (\hat{\theta}_n - \theta)^2 \Big| \theta \Big).$$
This gives you a measure of closeness of the estimator $\hat{\theta}_n$ to the parameter $\theta$.  For this particular measure, it can be shown that:
$$\text{MSE}(\hat{\theta}_n) = \mathbb{V}(\hat{\theta}_n | \theta) + \text{Bias}(\hat{\theta}_n, \theta)^2.$$
You can see from this expression that the mean-squared-error is affected both by the bias of the estimator and also its variance.  The overall MSE is an interaction of these two things.

Application to variance estimation: To preserve clarity of the value of $n$ used, I am going to vary your notation to denote the standard variance estimator (with Bessel's correction) as $S_n^2$ and the (uncorrected) sample variance estimator as $B_n^2$.  Now, using moment results from O'Neill (2014), and taking $\kappa$ as the kurtosis parameter in the underlying distribution, we have:
$$\begin{equation} \begin{aligned}
\text{MSE}(S_n^2)
&= \mathbb{V}(S_n^2 | \sigma) + \text{Bias}(S_n^2, \sigma^2)^2 \\[6pt]
&= \Bigg( \kappa - \frac{n-1}{n-3} \Bigg) \frac{\sigma^4}{n} + 0^2  \\[6pt]
&= \Bigg( \kappa - \frac{n-1}{n-3} \Bigg) \frac{\sigma^4}{n},  \\[10pt]
\text{MSE}(B_n^2)
&= \mathbb{V}(B_n^2 | \sigma) + \text{Bias}(B_n^2, \sigma^2)^2 \\[6pt]
&= \mathbb{V}\Big( \frac{n-1}{n} \cdot S_n^2 \Big| \sigma \Big) + \mathbb{E} \Big( \frac{n-1}{n} \cdot S_n^2 - \sigma^2 \Big| \sigma \Big)^2 \\[6pt]
&= \Big( \frac{n-1}{n} \Big)^2 \Bigg( \kappa - \frac{n-1}{n-3} \Bigg) \frac{\sigma^4}{n} + \Big( \frac{n-1}{n} - 1 \Big)^2 \sigma^4 \\[6pt]
&= \Big( \frac{n-1}{n} \Big)^2 \Bigg( \kappa - \frac{n-1}{n-3} \Bigg) \frac{\sigma^4}{n} + \frac{\sigma^4}{n^2} \\[6pt]
&= \Bigg[ \Big( \frac{n-1}{n} \Big)^2 \Big( \kappa - \frac{n-1}{n-3} \Big) + \frac{1}{n} \Bigg] \frac{\sigma^4}{n}. \\[6pt]
\end{aligned} \end{equation}$$
Hence, the difference of these error measures is:
$$\text{MSE}(S_n^2) - \text{MSE}(B_n^2) = \Bigg[ \Big( \kappa - \frac{n-1}{n-3} \Big) \cdot \frac{2n-1}{n^2} - \frac{1}{n} \Bigg] \frac{\sigma^2}{n}.$$
With a bit of algebra it can be shown that:
$$\text{MSE}(S_n^2) > \text{MSE}(B_n^2) \quad \quad \iff \quad \quad \kappa > \frac{n-3}{n-1} + \frac{n}{2n-1}.$$
The above formulae give you explicit expressions for the MSE of the two estimators for any value of $n$.  As $n \rightarrow \infty$ we have $\text{MSE}(S_n^2) > \text{MSE}(B_n^2)$ if and only if $\kappa > \tfrac{3}{2}$, which is the case for distributions other than highly platykurtic distributions.  So you can see that, other that in the case of highly platykurtic distributions, the biased sample variance estimator has lower MSE than the unbiased sample variance estimator.

Note: There are other measures you could potentially use to look at how close the estimator is to the parameter it is estimating.  More generally, these measures are usually expected values of some "loss" function that depends on the distance of the estimator from the parameter.  The MSE uses squared-error loss, which is a common loss function.

Correction: A previous version of this answer had an error in the MSE difference which flowed through to later results; this has now been corrected.

Consistency and rates of convergence


Como criar um input search html que é representado por apenas um icone

Question: Estou fazendo um projeto para aplicar uns conceitos de html/CSS que comecei a estudar há 1 mês, estou com um problema, na versão do site para mobile, não dá para colocar uma caixa de input muito grande no header, então.
Como faço com que o input type="search" seja apenas uma imagem, e que ao clicar apareça a BOX com o texto para o usuário digitar?
Comment: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_image
Comment: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image
Answer: no HTML você irá usar uma label com a imagem dentro e o input fora, desse modo:

<input type="search" name="imagem" id="imagem">

No CSS você irá utilizar o seguinte:
input[type="search"] {
    display: none;
}

e você precisará usar JavaScript:
function mostrarcampo() {
    var input = document.getElementById('imagem');
    var clique = document.getElementById('label');
    clique.onclick = function(){
       input.style.display = 'block';
    }
}

Answer: Aplicando somente o conceito de HTML/CSS conforme proposto na pergunta, acredito que seja isso que você quer:

<!DOCTYPE html>

Form com pesquisa animada:

<form>
  <input type="text" name="search" placeholder="Search..">

</form>

Referência: W3Schools
Answer: Usa media queries para esconder ou mostrar elementos conforme o dispositivo. Aqui um exemplo mostrando mudança de cor, mas pode alterar qualquer coisa:
/* Código geral, que será herdado por qualquer dispositivos.
   nesse caso, seria o código usado no desktop, na maioria das   vezes.
   Se você já conhecer a ideia do Mobile First, esse primeiro código será destinado para mobiles.
*/
a {color: blue;}

/*
 Pra dispositivos que tem uma largura mínima de 768 pixels. Tablets, por exemplo.
*/
@media screen and (min-width: 768px) {
  a {color: yellow;}
}

/*
 Com uma largura mínima de 992 pixels. Monitores por exemplo.
*/
@media screen and (min-width: 992px) {
  a {color: green;}
}

/*
 Dispositivos com largura mínima de 1200 pixels. Por exemplo TVs.
*/
@media screen and (min-width: 1200px) {
  a {color: black;}
}

Fonte do exemplo: Tableless


Can you change the view item output amount depending on user role?

Question: Is there a way to do this within one view/display or do I have to make two seperate displays, one showing field_images with unlimited item output and one display showing field_images but only showing max 2 images - depending on user role?!
Comment: I dont see an option to do that. I think either two views or go with two fields one for anonymous user and one for authenticated user.
Comment: do you wan all the images or only images uploaded by the user?
Comment: all the images. basically i want to limit the amount of visible images per node to two for anonymous users, and unlimited to other roles. i would create two displays with different role and item amount setup but i wondered whether there is an easy way from within views directly
Answer: I'd clone the view, the public one I'll name (temporarily) Public and change the access permission so anonymous users can view it.  The original one I'll name (again temporarily) Private and change the access to the authenticated user role.
Now you have two view displays, Public & Private.  Public display setting can be 2 and Private can be set to unlimited.
Comment: i know i could do it that way, my question was if there's another possibility doing it not like this :) but thank you anyways
Comment: View displays is the best way to make small changes to a view,it maintains the other views settings, so if you  change the view to display a teaser view mode, the change should trickle down to the other displays.
Comment: again, I know that :) thank you, that was not my question.


Using line breaks from VB.Net to XML

Question: I am writing data from a vb project to an XML document. When I recall the data, all the previous notes are coming back as one long line of text. How can I break the lines by submission to the XMl document?
Code:
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles     btnSave.Click

        Dim AcctNum = txtAcctNum.Text.ToString

        'Dim note1 As String = ""

        'Dim linebreak As String = "
"

        'Str & VBNewLine
        'Str & VBCrLf

        Dim note2 As String = TxtNotes.Text
        'note2(0) = vbNewLine
        'note2(1) = TxtNotes.Text()

        Dim note3 As String = txtPastNote.Text

        note2 = note3 + "\n" + note2

        Dim root As XElement = XElement.Load("CreditApp.xml")

        Dim customer = From el In root.<custData>
                       Where el.<AcctNum>.Value = AcctNum
                       Select el

        For Each element In customer
            element.SetElementValue("Note", note2)
        Next

        'Dim NewNote As String = note1 + note2

        'Dim doc As New XmlDocument
        'doc.Load("CreditApp.xml")

        'Dim custData As XmlElement = doc.CreateElement("custData")

        'Dim note As XmlElement = doc.CreateElement("Note")
        'note.InnerText = NewNote

        'custData.AppendChild(note)
        'doc.DocumentElement.AppendChild(custData)

        root.Save("CreditApp.xml")
        MessageBox.Show("NOTES SAVE")

    End Sub

Code that retrieves the elements from XML:
 For Each element In customer
            txtSSN.Text = element.ssn
            txtfName.Text = element.fname
            txtlName.Text = element.lname
            txtAcctNum.Text = element.acctnum
            txtVerfiWord.Text = element.passcode
            txtAcctAmt.Text = element.acctAval
            txtAcctBal.Text = element.acctbal
            txtLPmtAmt.Text = element.lpmtamt
            txtLPmtDate.Text = element.lpmtdate
            txtGender.Text = element.gender
            txtAddress.Text = element.address
            txtCity.Text = element.city
            txtState.Text = element.state
            txtZip.Text = element.zip
            txtPhone.Text = element.phone
            txtEmail.Text = element.email
            txtCreditLmt.Text = element.creditlim
            txtIntRate.Text = element.intrate
            txtMinPmtDue.Text = element.minpay
            txtPmtDueDate.Text = element.pmtduedate
            txtPastNote.Text = element.note

end sub

Comment: Can you add an example of how you are writing the data to the XML file?  Thanks.
Comment: What is the data source a file or a control?
Comment: @Wade73 - Its an XML file (document).
Comment: We tried adding a \n,  and a vbNewLine in between the notes but none of these were successful
Comment: See if this [MSDN Forum Link](http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/a9a48e2a-99f3-43f5-ae01-e907b2a7b878) is any help
Comment: @Mark Hall This did not help us. We have figured out that note2 & vbNewLine & note3 will store the note correctly in XML. What we need is when we pull the data out of the file, we need it to recognize new lines.
Comment: Can you show the code that you are using to import your data from the xml file?
Comment: @Mark Hall information has been added
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10298/discussion-between-kevin-schultz-and-mark-hall)
Answer: I am presumming that you are using a TextBox, its Multiline property is set to True and the character you are using for the NewLine is part of the string being input from the xml file, You can try using String.Replace or if you need to split into seperate Strings you can use String.Split
txtPastNote.Text = element.note.Replace("\n", vbCrLf)

Using line breaks from VB.Net to XML


Interaction terms in mixed effects model

Question: I have outcome variable Y with independent variables A, ...., J and variables to control for clustering 'area'. I'd like to assess whether B, ... J inflate or deflate the relationship between A and Y. I think to assess that, we can use interaction terms in a regression model as follows (computationally):
Y ~ AB + AC + ... A*J + (1|area).
Including interaction terms in a model would obviously change the interpretation of the coefficients of the model. My question is, whether this approach of using interaction terms appropriate within the context of mixed effects modeling (random intercept) and whether this implementation of interaction terms would be appropriate?
Answer: There is no specific reason you can't use interaction terms in mixed models. Of course, adding all those interactions means you will have more terms, so you need to be sure you have enough data, but you seem to understand those issues.
Comment: Related blog post: [You need 16 times the sample size to estimate an interaction than to estimate a main effect](https://statmodeling.stat.columbia.edu/2018/03/15/need16/).
Comment: Is this mathematically valid or would it introduce a problematic degree of multi-collinearity?


Weighted Marker Clusterer

Question: Google Maps has a nice feature called Marker Clusterer which lets you to apply grid-based clustering to a collection of markers.
Marker Clusterer counts every marker as one, it sums up the number of markers in the grid. Differently, I want to assign a weight to every marker and sum up these weights in the cluster. Is it possible with Google Maps API? Do you know any other javascript library which provides a similar feature?
Comment: You can modify Marker Clusterer library for that.
Comment: assinging the weight to every marker and summing them up should be easy, as each marker should be a `lat lng` pair you have stored on a database or something, so you just set the weight value along the coordinates, and as to fetch all those markers you will need a loop, you can just fetch the weight as well and sum them up in a temporal variable. The problem will be mainly to display that weight.
Answer: It's not as complicated as it seems.
The markerclusterer-library provides the option to override the calculator-function(this is the function that will build the cluster-icons).
Store the weight as a property of the markers, e.g.:
new google.maps.Marker({position:new google.maps.LatLng(1,2),weight:8});

The calculator-function may look like this:
   var calc=function(markers, numStyles) {
      var weight=0;

      for(var i=0;i<markers.length;++i){
        weight+=markers[i].weight;
      }
        return {
        text: weight,
        index: Math.min(String(weight).length, numStyles)
      };
    }

To apply this custom function:

initialize the clusterer without markers:
var markerCluster = new MarkerClusterer(map);

set the function
markerCluster.setCalculator(calc);

add the markers:
markerCluster.addMarkers(markers);

Demo: http://jsfiddle.net/doktormolle/H4EJu/
The pitfall: the calculator-function will have to iterate over all markers(by default it doesn't, it only calculates based on the length of the markers-array). This will affect the performance of the MarkerClusterer, especially when you have a lot of markers.

Weighted Marker Clusterer


C#, extension method RenderTransform not acccepting a first argument of type "System.Drawing.Rectangle"

Question: <code>private void RemoveUnfitChromosomes()
        {
            int[] buildingLW = new int[2 * buildingNo];     //2x for length & width

            for (int i = 0; i <= 2 * (buildingNo - 1);)        //working values to be changed for user input
            {
                buildingLW[i] = 30;     //l,x
                buildingLW[i + 1] = 10;     //w.y

                i = i + 2;
            }

            foreach (int[] chromosome in population)
            {
                int[] temp = new int[3 * buildingNo];
                List<Rectangle> building = new List<Rectangle>();

                Array.Copy(chromosome, temp, 3 * buildingNo);

                for (int j = 0; j < buildingNo; j++)
                {
                    building[j] = new Rectangle(temp[3 * j] - buildingLW[2 * j] / 2, temp[3 * j + 1] + buildingLW[2 * j + 1] / 2, buildingLW[2 * j + 1], buildingLW[2 * j]);

                    RotateTransform rotate = new RotateTransform();
                    rotate.Angle = temp[j+2];
                    rotate.CenterX = temp[j];
                    rotate.CenterY = temp[j+1];

                    building[j].RenderTransform= rotate;
                }
</code>
My problem is here building[j].RenderTransform= rotate;, which I will have this extension method RenderTransform not accepting a first argument of type "System.Drawing.Rectangle". I understand that the rectangle structure does not have a method for rotation. I am just confused by the information I am having.
The above is my code where I am trying import my data from another part of my code and then rotate my rectangle built from those data. FYI, I am trying to see if any of those rectangles intersection with one another. I am confused with the following code from http://msdn.microsoft.com/en-us/library/ms754009(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2. Their code was able to use polyline2.RenderTransform, so is there a way I can do it too?
I have tried searching online for hours, but I'm new to programming and cant understand what people are saying sometimes, so my apologies if the question is repeated. Thank you for your time.
Answer: RenderTransform is not an extension method, it's a property and Rectangle has it as well. System.Windows.Shapes.Rectangle not System.Drawing.Rectangle
Comment: Thanks. I managed to change my rect to a System.Windows.Shapes.Rectangle, but now I am unable to use the .IntersectsWith method. Any help? Thank you
Comment: I don't see any IntersectsWith() method . You're probably using Visual Studio so when the cursor is on top of the method press F1 to get the online help for that method


Mostrar 'confirm' somente após o carregamento da pagina

Question: Estou chamando a seguinte função dentro da pagina:
window.onload = function() {
    acess();
}

function acess() {

    decision = confirm("Deseja realmente excluir o servidor cadastrado abaixo?");

    if (decision) {
        window.location.replace("fin.del.cad.php");
    } else {
        history.back();
    }
}

Porem, o Confirm aparece e a pagina fica em branco carregando infinitamente até que eu clique no mesmo.
Gostaria que o Confirm e/ou alert após o carregamento da página e não antes.
Tentei algumas opções que vi em outros foruns e não deu muito certo.
Comment: Você pode deixar tb `window.onload = acess;` e inverter a ordem - deixar acess antes do onload.
Comment: Não funcionou :(
Answer: Você pode dar uma atrasada na caixa de confirmação colocando um setTimeout após o .onload. Um valor mínimo de 1 segundo pode ser suficiente (comentei os redirecionamentos para teste).

window.onload = function() {
   setTimeout("acess()",1000);
}

function acess() {

    decision = confirm("Deseja realmente excluir o servidor cadastrado abaixo?");

    if (decision) {
        // window.location.replace("fin.del.cad.php");
    } else {
        // history.back();
    }
}
Conteúdo da página

Usando readyState
O readyState retornará loading até que a página esteja totalmente carregada. Após retornar complete eu ainda dou mais 1 segundo para executar a confirmação:
var chkReadyState = setInterval(function() {
    if (document.readyState == "complete") {
        clearInterval(chkReadyState);
        setTimeout("acess()", 1000);
    }
}, 100);

Comment: @Shinchila_Matadora Valeu! Cloquei na resposta uma outra opção. Abs!
Comment: Cara, vc é muito topper, serviu direitinho, obrigado!
Answer: O ATRIBUTO DEFER
O atributo defer diz ao navegador para executar o script apenas quando a análise do HTML estiver finalizada.


How to create a custom layout with for a view, I have tried to print the fields but nothing works I created the template but cant display rows

Question: I have a view in drupal 7 but I cant show up the rows, I created a template for the row-style-output but nothing happen.
<?php

/**
 * @file
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */
?>

  <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

Comment: What is the name of the template file? Where is the template file located in the codebase?
Comment: is located in themes->templates I can put html and I can see it but not the rows to show up the rows and using for example bootstrap to create a layout or something like that I will add a image in the post.
Answer: According to your template name, it seems there is a mismatch between your template name and its content. You are using a template named views-view--blog-page.tpl.php but with the content of a views-view-fields.tpl.php file.
According to your Views template suggestions, here is how your templates shall be organised (from the most global one to the most accurate):

views-view--blog--page.tpl.php should override Views module views-view.tpl.php file. This is the global template of your View. In it, you can find $rows variable, which is the global result of your view. But you don't have access to each row details.
views-view-unformatted--blog--page.tpl.php should override views-view-unformatted.tpl.php. Here, you can alter your output at row level (e.g. Add a  element around each row). Still no access to the details of each row.
views-view-fields--blog--page.tpl.php should override views-view-fields.tpl.php. It is the template used to output a row content (fields-level). This is the one to use if you wish to alter the output of your rows content.
views-view-field--blog--page.tpl.php should override views-view-field.tpl.php. Most accurate level. It is the output of each field inside each row.

Now, you just need to pick the Views template suiting your needs, override it with the right name and you should be fine. :-)


Wrapping a TextField in my own reusable component

Question: So I have a component that adds a * at the beginning of typed in text that looks like this:
 export default class MyTextField extends Component {

      constructor() {
    super();
    this.state = {
      value: '',
    };
  }

  static propTypes = {
    onChange: PropTypes.func,
    value: PropTypes.string
  }

  addSymbol(newValue, symbol) {
    return newValue.indexOf(symbol) === -1 ? `${symbol}${newValue}` : newValue;
  }

  change(input, newValue) {
    console.log(`I am the parent wit newValue ${newValue}.`);
    this.setState({
      value: this.addSymbol(newValue, '*')
    });
  }

  render() {
    const {
      onChange, // eslint-disable-line no-unused-vars
      ...other
    } = this.props;

    return (
      <TextField
        value={this.state.value}
        onChange={this.change.bind(this)}
        {...other } >
      </TextField >
    );
  }
}

Now I use MyTextFieldin another component like this:
 <MyTextField
    style={styleTextFields}
    floatingLabelText='Add text'
    type='text'
  />

Now when I start typing everything works great.
If I change the code above and add value='test' prop on MyTextField everything breaks.  It appears its because I added a prop to TextField which can not be overwritten by MyTextField value={this.state.value}.
So how can I add prop value and still add a * at the beginning of the typed text?
The other part is if the user adds their own onChange, how can I get both MyTextField and the component using MyTextField onChange events to get called?
=======Beginning of Edit 1===============
@Patrick - I have made tweaks based on your comment and the first part is now working.  So I can type in <TextField /> and I see the changes.
The changes are below:
export default class MyTextField extends Component {
      constructor(props) {
    super();
    this.state = {
      value: props.value ? this.addSymbol(props.value.toString(), '*') : ''
    };
  }

  static propTypes = {
    onChange: PropTypes.func,
    value: PropTypes.string
  }

  addSymbol(newValue, symbol) {
    return newValue.indexOf(symbol) === -1 ? `${symbol}${newValue}` : newValue;
  }

  change(input, newValue) {
    console.log(`I am the parent wit newValue ${newValue}.`);
    this.setState({
      value: this.addSymbol(newValue, '*')
    });
  }

  render() {
    const {
      value, // eslint-disable-line no-unused-vars
      onChange, // eslint-disable-line no-unused-vars
      ...other
  } = this.props;

    return (
      <TextField
        value={this.state.value}
        onChange={this.change.bind(this)}
        {...other } >
      </TextField >
    );
  }
}

I am not sure how to make the onChange tweak because you are not supposed to modify component state?
I also did try this in the render() function which does not work:
  addSymbol(newValue, symbol) {
    return newValue.indexOf(symbol) === -1 ? `${symbol}${newValue}` : newValue;
  }

  change(input, newValue) {
    console.log(`I am the parent wit newValue ${newValue}.`);
    this.setState({
      value: this.addSymbol(newValue, '*')
    });
  }

  render() {
    const {
      value, // eslint-disable-line no-unused-vars
      onChange, // eslint-disable-line no-unused-vars
      ...other
  } = this.props;

    return (
      <TextField
        value={this.addSymbol(this.state.value, '*')}
        {...other } >
      </TextField >
    );
  }

Anyway, thank you for your help.
=======Ending of Edit 1===============
=======Beginning of Edit 2===============
I fixed the onChange event problem by adding my own event called onNewValueChange and calling it in the onChange.  Here is the final code:
export default class MyTextField extends Component {

      constructor() {
    super();
    this.state = {
      value: props.value ? this.addSymbol(props.value.toString(), '*') : ''
    };
  }

  static propTypes = {
    onNewValueChange: PropTypes.func,
    value: PropTypes.string
  }

  addSymbol(newValue, symbol) {
    return newValue.indexOf(symbol) === -1 ? `${symbol}${newValue}` : newValue;
  }

  change(input, newValue) {
    const value = value: props.value ? this.addSymbol(props.value.toString(), '*') : '';
    this.setState({
      value: value
    });

    if(this.props.onNewValueChange) {
        this.props.onNewValueChange(value);
    }
  }

  render() {
    const {
      onNewValueChange, // eslint-disable-line no-unused-vars
      ...other
    } = this.props;

    return (
      <TextField
        value={this.state.value}
        onChange={this.change.bind(this)}
        {...other } >
      </TextField >
    );
  }
}

Now I use MyTextField in another component like this:
<MyTextField
    style={styleTextFields}
    floatingLabelText='Add text'
    type='text'
    onNewValueChange={(newValue) => console.log(newValue) }
  />

@Patrick thank you for your help getting me in the right direction.
=======Ending of Edit 2===============
Comment: you're trying to pass the same prop twice to the component, why not add a logical check to see if the prop was provided? and if it was, set it as the state in the constructor ? also instead of running your logic "onChange" to add a symbol, why not simply run this logic on each render?
Comment: @Patrick I edited my post based on your comment.
Answer: In general, I think this pattern of omitting props before passing everything else inside a component is confusing, at least for me. Being explicit as possible should always be a priority.
If I understood you correctly, the expected behavior is as follows:

You can pass a default text, this text should be prefixed with a * by your component.
You can modify the text, but no matter how you modify it, it should always be prefixed with a * - so an empty string should just be *.

I've created this fiddle which hopefully does what you meant : https://jsfiddle.net/69z2wepo/78041/
The key concept is to separate between props and state, a prop is passed only once, and should really be responsible for the initial state of your
Here's the two classes I created :
class Input extends React.Component{
  render(){
   return (<input onChange={this.props.onChange} value={this.props.value}/>)
  }
}

class WrappedInput extends React.Component{

  constructor(props){
      super();

    let val = props.value || '';
    this.state = {
        value : this.addSymbol(val,'*')
    }
  }

  handleChange(e){
    let newVal = e.target.value;
    this.setState({value:this.addSymbol(newVal,'*')});
  }

  addSymbol(newValue, symbol) {
    return newValue.indexOf(symbol) === -1 ? `${symbol}${newValue}` : newValue;
  }

  render(){
   return (<Input onChange={this.handleChange.bind(this)} value={this.state.value}/>)
  }
}

Comment: I want the `Input` object to wrap the string logic so anyone using `input` can have the same functionality.  I also want anyone using `input` to able to subscribe to `onChange` event so they are be alerted about changes.  In m real app(this is a small example of what i'm doing), I have 10 different text boxes needing the same functionality so I want a reusable component in one place instead of copying code.
Comment: I saw you accepted my answer, I hope it pointed you in the right direction


How to setup Switcher in Intellij IDEA 10

Question: I'm using the Switcher in Intellij IDEA to switch between editor tabs a lot. After I upgraded to version 10 the Switcher will only show 10 editor tabs, which is of course far too little. Does anybody know where I can increase this? I have scoured the IDE Settings but I can't find it.
Answer: 10 files is the hardcoded limit for Switcher, you can't change it. Use Recent Files if you want to see more.
Comment: Thanks for a prompt answer. Not the one I was hoping for though. I have started using Recent files but it's not quite the same.
Comment: you can change the default. please see https://stackoverflow.com/a/2065756/4251722


SQL Chinese formatting year part of a date

Question: I am using MS SQL Server 2016, I would like to retrieve only the year part of a given date and formatted using the Chinese culture code zh. This is simple to do with all other culture codes expect for Chinese culture codes. For example, to format a date to only show a year in the English (Ireland) culture I could do this:
select format(try_cast('2017-12-29' as date), 'yyy', 'en-IE')

The above will produce the desired output 2017. However, this is not the case with the Chinese culture codes. For example,
select format(try_cast('2017-12-29' as date), 'yyy', 'zh')

The above produces 2017. But the desired output is 2017年. So, my question is how do I get this in the correct way? Below is how I am getting the desired output, but I am not sure if this is the correct way. Please assist.
select substring(format(try_cast('2017-12-29' as date), 'D', 'zh'), 0, 6)

Comment: Is the character at the end always `年` regardless of the year?
Comment: I would say yes @Larnu, the character `年` will always be at the end regardless of the year.
Answer: If the character is always going to be 年 at the end, just concatenate it on:
SELECT CONCAT(DATEPART(YEAR, CONVERT(date,'20171229')),N'年');

Comment: `FORMAT` is a pretty slow function, @HakunaN . For a scalar value, it's "fine", but start applying it to large datasets, and you often start to experience performance loses.
Comment: Thanks @Larnu, I was wondering why would I choose your solution over my solution I have outlined. Or why is your code better to use compared to my code? Thanks once again.
Comment: Thank you @Larnu for answering my question. Very helpful.


send value to controller using html.actionlink

Question: I am passing value from Html.ActionLink to the controller. But the problem is in controller, value is not being fetched. I don't know what is the problem.
Here is my code :
View :
    @Html.ActionLink("Copy", "Copy", "Item", new { id = item.Item_code}, null)

Contoller :
       public ActionResult Copy(int id)
       {
                 // Logic here
                 return View();
       }

Comment: This is really strange! Look at [this](https://dotnetfiddle.net/A9VEmd) fiddle it worked for me correctly. It might give you some tip to the resolution.
Answer: You HTMLhelper looks OK, so that's strange. Please check a route for this link. Also type in the expected URL in browser address bar and see if you can get to controller. Also check URL when your mouse over the link. Does it show correct link?
You could try to use Url.Action instead of Html.ActionLink helper like below:
 Copy

Update
Since you have ID like 001020002, try to change int type to string to see if it works that way:
   public ActionResult Copy(string id)
   {
             // Logic here
             return View();
   }

in View:
@Html.ActionLink("Copy", "Copy", "Item", new { id = item.Item_code.ToString()}, null)

Comment: Hi..thanx for the answer. Url.Action did not work. :(
Comment: When I typed url in address bar, i get to controller. and link shows correct address when I move mouse over that link...
Comment: It returns 'The resource can not be found' Requested URL: /Item/Copy/001020002
Comment: @Gokhale That's strange. What is the name of your controller where Copy action located?
Comment: @Gokhale Post the URL along with your route configurations.
Comment: @Gokhale check updated answer, if it won't work please post your code from RouteConfig.cs to your question. And also embrace you Copy action with the controller class name in your question, please.


Which samples are used in random forests for calculating variable importance?

Question: Each tree of a random forest is learned on a random bootstrapped sample.
Consequently, given that the number of trees is large, it is probable that every observation of a data set is used to form at least one tree of a forest and hence there exists no "independent" sample which can be used for evaluating the performance of the random forest.
Which samples are used by random forest to calculate variable importance then?
In my understanding there is no guarantee that there exists a sample which is independent from forming the trees.
Comment: @Julian If you feel my post below answered your question, please mark it as 'accepted' by clicking the green check mark. If not, please add a comment to clarify. Thanks in advance.
Comment: There are several methods that can be used to calculate the variable importance. For example one can calculate "total decrease in node impurities from splitting on the variable, averaged over all trees", in which case the answer to you question would be "all the samples". Do you have a specific method in mind?
Answer: After each tree is grown, the values of a given predictor are randomly permuted in the out-of-bag sample (the one third of unique observations that are not part of the bootstrap sample) and the prediction error of the tree on the modified OOB sample is compared with the prediction error of the tree on the untouched OOB sample.
This process is repeated for all input variables, and averaged over all trees. Finally, variables are given scores proportional to the overall decrease in accuracy that their permutation induced.
The most important variables are the ones leading to the greatest losses in accuracy when "noised-up" (see Breiman 2001).
In short, you do have independent samples at the tree level. The importance of a given variable is first computed at the tree level, and the scores are aggregated over all trees to obtain the final, global importance score for the variable.
Comment: Thank you for your answer, what is the advantage of randomly permuted variable importance over calculating the decrease in accuracy by completely removing that variable from the equation?  E.g. let's say I have an ordinal variable called age_group. I can recalculate my model's accuracy by permuting the values of age_group across different observations, or seven simpler I can calculate the accuracy for the model by completely removing age_group as an independent variable. How and why is the former better?


Switch homepage

Question: What's the best way to deliver a different homepage per user role?
Currently I have an EventSubscriber that redirects the request, but would like to deliver the page at / rather than doing a 302 to /the-other-homepage
Comment: https://www.drupal.org/project/page_manager you can add page, set it as homepage and add variants based on conditions(user role). If you want to keep your code, you can hook into \Symfony\Component\HttpKernel\KernelEvents::CONTROLLER event and change the controller...or better, use RouteEnancer. I use it for TFA when user want's to access admin pages to display form for TFA code.
Comment: Many thanks Ivan I marked Key's answer as the answer as you're both right and page manager is probably what we should be using.  However, as the client wants to manage the pages separately I'll look into the events you listed.
Answer: Your best option is to use Panels/Page Manager module. Override the default homepage and this will give you a lot of different control options.
What you'd want to do from there is to setup different variants based on the different homepage you want to deliver. Use selection rules to select which role gets access to which version of the homepage.

Switch homepage


Duplo evento no click jQuery

Question: Estou a tempo tendo problemas nos eventos do jQuery. Já utilizei de todas as práticas recomendadas para barrar o duplo evento de click. Segue exemplos:
.off()
e.preventDefault();
e.stopPropagation();
unbid('click');

Sempre quando tem um click eu efetuo essa função
function LoadingTela(botao,tipo) {
     if (tipo == true) {
       $(botao).prop("disabled", true);
       $('.mask-loading').show();
     }else {
       $(botao).prop("disabled", false);
       $('.mask-loading').hide();
     }
 }

Alguém chegou a alguma solução ou novo controle de evento?
Comment: Parece que seu evento está sendo chamado duas vezes, o **.off** vc disse que usou, foi na hora de criar o evento? Por exemplo, tente fazer **$("#botao").off("click").on("click",function(){ /*suas coisas aqui*/ });** para evitar que ele seja criado duas ou mais vezes. Caso isso não funcione você pode tentar algo mais complexo, algo como salvar no seu botão quando ele for clicado e só permitir clicks novamente depois de, digamos, 1 segundo. Se precisar posso te montar um exemplo.
Comment: `function LoadingTela(botao,tipo) {
    if (tipo == true) {
        $(botao).prop("disabled", true);
        $('.mask-loading').show();
    } else {
        $(botao).prop("disabled", false);
        $('.mask-loading').hide();
    }
}`
Answer: Você pode tentar com a função one do jQuery. Ela é semelhante à função on, com a diferença que o evento é removido do elemento apenas sua primeira execução, ou seja, para o exemplo abaixo a função no evento click será executada apenas uma vez.

$('#btn').one('click', event => {
  console.log('Botão pressionado');
});

<button id="btn">Pressione-me!</button>

Se for possível que o evento seja disparado múltiplas vezes na mesma página e a intenção seja somente proteger de múltiplos cliques simultâneos, você pode desabilitar o botão (ou elemento que dispara o evento) enquanto estiver processando a aplicação:

$('#btn').on('click', function(event) {
  $(this).prop('disabled', true);
  console.log('Botão pressionado');

  // processando o evento click...

  $(this).prop('disabled', false);
});

<button id="btn">Pressione-me!</button>
Comment: Porem este botão sera executado novamente na mesma tela, pela aplicação  estar baseada em ajax, tem como renovar este btn sem atualizar a pagina ?
Comment: Utilizei esse controle de desabilitar o botão mais sempre no segundo click a minha function que esta sendo chamada duas vezes, pode ter ficado algum resquício do evento na pagina para ele ser disparado duas vezes ?
Comment: @Guilhermezio consegue fazer um [mcve]?
Comment: Utilizo sempre quando clico essa função
  `function LoadingTela(botao,tipo) {
    if (tipo == true) {
        $(botao).prop("disabled", true);
        $('.mask-loading').show();
    } else {
        $(botao).prop("disabled", false);
        $('.mask-loading').hide();
    }
}`
Comment: editado a pergunta com o exemplo

Duplo evento no click jQuery


Is there a way to make this curve fit my data better?

Question: I'm working off Safe Leads and Lead Changes in Competitive Team
Sports and trying to apply the same
techniques to baseball scores, using number of outs remaining instead
of the number of seconds. I'm pretty far out of my depth reading the
paper so I'm just cherry-picking the algorithms that look right and
trying to use them with baseball data. I get a pretty reasonable curve
(similar to Figure 16 in the paper), but as the game gets more safe,
the erf(v) curve overestimates the probability the lead is safe by a
few percentage points (I wouldn't mind if it underestimated a
little). Here's a picture: the red triangles are the observed values,
and the black line is the erf(z) curve; the hand-drawn blue line is roughly what I wish the erf(z) curve looked like.

Is there a way to make my curve fit the data better, either by applying some
additional transformation to the result of erf(z) or using something
other than erf in the first place? Preferably also something easy to
implement in Java (for my Android app).

If you want to examine the data yourself:

Data used to make the graph (data from 2000-2014 run through the program with -p 50)
Program used to create the graph (with some instructions
in its comments).
Answer: It's not a good idea to take data and say "what functions might fit this" -- you can't account for the "researcher degrees of freedom" in this.
Worse, when you ask large numbers of experts you're potentially adding a large number of potential "guesses" but the only ones you will hear about are the "ones that work", so you can't hope to guess at the effective degrees of freedom used by asking our thoughts on your data.
(A less biased way to do this would be to randomly choose a fraction of your points, post those, then fit the parameters and assess the fit on other parts of the data.)
That said, by eye one can see that $1-\exp(-\theta\:\! x)$ will be a better fit than what you have (looking more closely at the picture, it looks like $\theta\approx 1.8$, or possibly a bit lower, would fit adequately).
However, until you can confirm the fit on data not used to identify or fit the curve, you should take the quality of the fit with a grain of salt; it will fit well but could have relatively poor out of sample performance.
(It's also not clear to me this is a suitable way to model data of this sort but I haven't looked at the paper nor at your data set.)


How can I know which childview is shown on the current Device screen in a scrollview?

Question: How can I know which childview is shown on the current device screen, in a scrollview?
I want to make an infinite Ruler App, so I need to dynamically add and remove view when the view is flipping, but how and where can I find out which childview is shown on the current device screen, so I can add or remove the correct view when I get that childview changed notify?
Or, can anyone who can give me some other idea to realize this function?
Answer: I have met this problem too. you can call getlocalonscreen function to get coordinate of view. for example:
1.
view.getlocaloncreen(xy);// xy[0] is x axis, xy[1] is y axis.

2.
int nScreenWid = getwindowsmanager().getdefaultdisplay().getwidth();
int nScreenHei = getwindowsmanager().getdefaultdisplay().getHeight();

3.
if( xy[0] > nscreenWid )
{
  // your view is beyond the x axis.
}
if( xy[1] > xxxxhei )
{ // beyond y axis }

Answer: Use scrollView.getScrollY() to find how far down the scroll view the scroll point is, and compare that to the heights of the child views (adding them up as you go along) to see which one must be on screen.
Comment: thanks
getScrollY() maybe right.
I just found anyview have scrollTo() function,so now i immediately use lineanerlayout instead ScrollView


Updating manually with CPanel

Question: I've updated my local site with composer.
Now I'm trying to update the production one:

Go to Cpanel.
On my local computer, take the local web folder and delete in it all 1-level files that are non-folders, and the sites folder.
Make a zip archive from the rest of the folders and upload it production (delete the invisible files too).
Delete on production all folders except the sites folder into trash.
Unzip the uploaded archive.
Change permissions for the uploaded folders:

find /home/zb/public_html/core -type d -exec chmod 755 {} \; find /home/zb/public_html/libraries -type d -exec chmod 755 {} \; find /home/zb/public_html/modules -type d -exec chmod 755 {} \; find /home/zb/public_html/profiles -type d -exec chmod 755 {} \; find /home/zb/public_html/themes -type d -exec chmod 755 {} \; find /home/zb/public_html/vendor -type d -exec chmod 755 {} \;

Reload the production site and it says that it encountered an unexpected error.

I've looked at error_log file and saw this:

Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Field uses_legacy_adjustments is unknown." at /home/zb/public_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 829

What do I do wrong? How to make the site work?
Comment: looks like you havent updated the database as the error is complaining about a missing file
Answer: I should've compressed the updated index.php file and extracted it into the root directory as well and changed permissions of that file to 644.
After I had done that the error disappeared and the site started working fine.
Then I updated the database.

Updating manually with CPanel