ComboBox.store.loadData can't load single-item array

Question: I am using ExtJS 3.4 .
I have a structure with data for combobox like this:
var a = [[1,"text1"],[2,"text2"]]

I load it like this:
ComboBox.store.loadData(a);

But when I have only 1 item in the array
var a = [[1,"text1"]]

then it doesn't load at all. I've read that:

an Array : Arrays will be converted to a Ext.data.ArrayStore
  internally, automatically generating field names to work with all data
  components. 1-dimensional array : (e.g., ['Foo','Bar']) A
  1-dimensional array will automatically be expanded (each array item
  will be used for both the combo valueField and displayField)
  2-dimensional array : (e.g., [['f','Foo'],['b','Bar']]) For a
  multi-dimensional array, the value in index 0 of each item will be
  assumed to be the combo valueField, while the value at index 1 is
  assumed to be the combo displayField.

But that doesn't explain how do I load an array with one element. Or whatever, it shouldn't be necessary an array, the point is to load only one item. I've tried loading this:
Code:
[{id:1,text:"text1"}]
[[{id:1,text:"text1"}]]
{id:1,text:"text1"}

Even creating a custom ArrayStore:
Code:
 var store = new Ext.data.ArrayStore({
                            autoDestroy: true,
                            storeId: 'Store1',
                            idProperty:"id",
                            fields: ["id","text"]);
ComboBox.store = store;
ComobBox.store.loadData([{id:1,text:"text1"}]);

But everything loads incorrectly  . Either the combobox is empty, or it displays id instead of text.
I can see that if I lazily init the combo:
Code:
{"xtype":"combo","width":250,"fieldLabel":"my combo","value":31029,"forceSelection":true,"hiddenName":"ComboHiddenName","minChars":1,"triggerAction":"all","store":[[31029,"gdfs"]]}

then the array with one item will load successfully. At which properties of ComboBox.store should I look to configure them properly for a single-item array to be loaded correctly using loadData method?
Comment: Which version of ExtJs are you using?
Comment: why would you want a store with one record?
Comment: @Jaitsu how do load one item to a combobox otherwise, without using a store?
Comment: that's exactly my point, why would you ever have a combo box that only has one option?
Answer: ComboBox.store.loadData(var a); would not work for any data. It would raise exception Unexpected token var. Instead one should use ComboBox.store.loadData(a); without var
Comment: ofcourse it won't, that's my misspelling, but it's not a correct answer
Comment: In extjs 3.3.1 your example works just fine. I've checked by invoking code var store = new Ext.data.ArrayStore({
                            autoDestroy: true,
                            storeId: 'Store1',
                            idProperty:"id",
                            fields: ["id","text"]});
var cc = new Ext.form.ComboBox({"fieldLabel":"my","value":31029,"forceSelection":true,"hiddenName":"ComboHiddenName","minChars":1,"triggerAction":"all","store":[[31029,"gdfs"]]});
cc.render(Ext.getBody()); c.store.loadData([[1,'dgkj']]);
So, maybe, there are issues with your version of extjs.
Answer: ComboBox.valueField = "id";
ComboBox.displayField = "text";
ComboBox.store = new Ext.data.ArrayStore({autoDestroy: true, fields: ["id", "text"]});


Discrepancy between FusedLocationClient.requestLocationUpdates documentation and google training documentation

Question: G'day
I'm currently learning Googles location services.
<code>private void startLocationUpdates() {
    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
            mLocationCallback,
            null /* Looper */);
}
</code>
The above code is taken from
https://developer.android.com/training/location/receive-location-updates.html
While in the documentation, every signature for the function requestLocationUpdates takes a GoogleApiClient. The above code just takes a LocationRequest, LocationCallback and looper.
https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
What is up with the discrepancy?
Cheers
Answer: It's a new "connectionless" API, that's why it doesn't require GoogleApiClient anymore, it's handled automatically.
The old documentation will probably be updated soon.


Find expected value using CDF

Question: I'm going to start out by saying this is a homework problem straight out of the book. I have spent a couple hours looking up how to find expected values, and have determined I understand nothing.

Let $X$ have the CDF $F(x) = 1 - x^{-\alpha}, x\ge1$.
  Find $E(X)$ for those values of $\alpha$ for which $E(X)$ exists.

I have no idea how to even start this. How can I determine which values of $\alpha$ exist? I also don't know what to do with the CDF (I'm assuming this means Cumulative Distribution Function). There are formulas for finding the expected value when you have a frequency function or density function. Wikipedia says the CDF of $X$ can be defined in terms of the probability density function $f$ as follows:
$F(x) = \int_{-\infty}^x f(t)\,dt$
This is as far as I got. Where do I go from here?
EDIT: I meant to put $x\ge1$.
Answer: Usage of the density function is not necessary
Integrate 1 minus the CDF
When you have a random variable $X$ that has a support that is non-negative (that is, the variable has nonzero density/probability for only positive values), you can use the following property:
$$
E(X) = \int_0^\infty \left( 1 - F_X(x) \right) \,\mathrm{d}x
$$
A similar property applies in the case of a discrete random variable.
Proof
Since $1 - F_X(x) = P(X\geq x) = \int_x^\infty f_X(t) \,\mathrm{d}t$,
$$
\int_0^\infty \left( 1 - F_X(x) \right) \,\mathrm{d}x = \int_0^\infty P(X\geq x) \,\mathrm{d}x = \int_0^\infty \int_x^\infty f_X(t) \,\mathrm{d}t \mathrm{d}x
$$
Then change the order of integration:
$$
= \int_0^\infty \int_0^t f_X(t) \,\mathrm{d}x \mathrm{d}t = \int_0^\infty \left[xf_X(t)\right]_0^t \,\mathrm{d}t = \int_0^\infty t f_X(t) \,\mathrm{d}t
$$
Recognizing that $t$ is a dummy variable, or taking the simple substitution $t=x$ and $\mathrm{d}t = \mathrm{d}x$,
$$
= \int_0^\infty x f_X(x) \,\mathrm{d}x = \mathrm{E}(X)
$$
Attribution
I used the Formulas for special cases section of the Expected value article on Wikipedia to refresh my memory on the proof. That section also contains proofs for the discrete random variable case and also for the case that no density function exists.
Comment: When you change the order of integration, how do you get the integration limits?
Comment: @Zaz we set the integration limits so that the same part of (t, x) space is covered. The original constraints are x >0 and t > x. We can't have the outer limits depend on the inner variable, but we can define the same region as t > 0 and 0 < x < t. Good examples of this process here: https://mathinsight.org/double_integral_change_order_integration_examples
Comment: +1 great result: the integral of the cdf is really simple, moreover, it is wise to avoid derivatives, whenever we can (they are not as well behaved as integrals ;)). Additional: using the cdf to calculate the variance see here https://math.stackexchange.com/questions/1415366/variance-formula-in-terms-of-the-cdf-for-a-continuous-nonnegative-random-variabl
Comment: The standard proof does not assume that $X$ has a density.
Comment: how is that $\int_0^t f_X(t)\,\mathrm{d}x = xf_X(t)\Big|_0^t$?
Answer: The result extends to the $k$th moment of $X$ as well. Here is a graphical representation:
Comment: an undervalued answer
Answer: Edited for the comment from probabilityislogic
Note that $F(1)=0$ in this case so the distribution has probability $0$ of being less than $1$, so $x \ge 1$, and you will also need $\alpha > 0$ for an increasing cdf.
If you have the cdf then you want the anti-integral or derivative which with a continuous distribution like this
$$f(x) = \frac{dF(x)}{dx}$$
and in reverse $F(x) = \int_{1}^x  f(t)\,dt$ for $x \ge 1$.
Then to find the expectation you need to find
$$E[X] = \int_{1}^{\infty}  x f(x)\,dx$$
providing that this exists.  I will leave the calculus to you.
Comment: @henry - $F(1)=1-1^{-\alpha}=1-1=0$, so support can't be below 1 (as CDF is a non-decreasing function)
Comment: $f(x)$ is indeed supposed to be the probability density function.  If the cdf has a derivative then it is the density, though there are distributions (for example discrete) where the cdf does not have a derivative everywhere
Comment: @styfle: If it exists then $E[X^2] = \int_{1}^{\infty}  x^2 f(x)\,dx$, and similarly for the expectations of other functions of $x$.
Comment: @probabilityislogic: You may be correct in terms of the book.  I will change my response.
Comment: Thanks for the response. What does f(x) represent? The probability density function? Is the derivative of the cdf always f(x)?
Comment: @Henry On a related question, $Var(X) = E(X^2) - E(X)^2$. How can I find $E(X^2)$? Thanks.
Answer: The Answer requiring change of order is unnecessarily ugly. Here's a more elegant 2 line proof.
$\int udv = uv - \int vdu$
Now take $du = dx$ and $v = 1- F(x)$
$\int_{0}^{\infty} [ 1- F(x)] dx = [x(1-F(x)) ]_{0}^{\infty} + \int_{0}^{\infty} x f(x)dx$
$= 0 + \int_{0}^{\infty} x f(x)dx$
$= \mathbb{E}[X] \qquad \blacksquare$
Comment: With your proof, we need to assume that $\lim _{x \rightarrow \infty} x(1 - F(x)) = 0$. Does it make sense to assume that for any continuous cdf F ?
Comment: I think you mean to let du-dx so that u=x.
Comment: @Eryna otherwise the expectation wouldn't exist i guess?
Answer: I think you actually mean $x\geq 1$, otherwise the CDF is vacuous, as $F(1)=1-1^{-\alpha}=1-1=0$.
What you "know" about CDFs is that they eventually approach zero as the argument $x$ decreases without bound and eventually approach one as $x \to \infty$.  They are also non-decreasing, so this means $0\leq F(y)\leq F(x)\leq 1$ for all $y\leq x$.
So if we plug in the CDF we get:
$$0\leq 1-x^{-\alpha}\leq 1\implies 1\geq \frac{1}{x^{\alpha}}\geq 0\implies x^{\alpha}\geq 1 > 0\implies x\geq 1 \>.$$
From this we conclude that the support for $x$ is $x\geq 1$.  Now we also require $\lim_{x\to\infty} F(x)=1$ which implies that $\alpha>0$
To work out what values the expectation exists, we require:
$$\newcommand{\rd}{\mathrm{d}}E(X)=\int_{1}^{\infty}x\frac{\rd F(x)}{\rd x}\rd x=\alpha\int_{1}^{\infty}x^{-\alpha} \rd x$$
And this last expression shows that for $E(X)$ to exist, we must have $-\alpha<-1$, which in turn implies $\alpha>1$.  This can easily be extended to determine the values of $\alpha$ for which the $r$'th raw moment $E(X^{r})$ exists.
Comment: (+1) Particularly for the sharp-eyed recognition that the given support was incorrect.
Comment: @styfle - the PDF can also be seen as the probability that a RV lies in an infinitesimal interval.  $Pr(x=1. How did you know to first differentiate the cdf to get the density function?
Comment: @styfle - because that's what a PDF is, whenever the CDF is continuous and differentiable.  You can see this by looking at how you have defined your CDF.  Differentiating an integral just gives you the integrand when the upper limit is the subject of the differentiation.
Comment: +1 because this post actually answers the question!
Answer: In case when a conditional expectation using only CDF is needed, we can formulate two cases,
$\mathbb{E}\left(x|x\geq y\right)=y+\frac{\int_{y}^{\infty}\left(1-F(x)\right)dx}{\left(1-F(y)\right)}$
$\mathbb{E}\left(x|x\leq y\right)=y-\frac{\int_{-\infty}^{y}F(x)dx}{F(y)}$
The derivation leverages on previous post such that we first define following integral,
$\int_{y}^{\infty} [ 1- F(x)] dx = [x(1-F(x)) ]_{y}^{\infty} + \int_{y}^{\infty} x f(x)dx$
$\int_{y}^{\infty} x f(x)dx=\mathbb{E}\left(x|x\geq y\right)(1-F(y))$
Then using this definition and some algebra we arrive at first result. The second result can be obtained in the same way.
Comment: Thank you very much @whuber for pointing that out. I solely, thought of a continuous one and did numerical experiments based on that.
Comment: The first formula is not fully correct.  Although it holds when $F$ is continuous at $y,$ if it has a jump at $y$ then the amount of that jump needs to be subtracted from the denominator.

Find expected value using CDF


Why decrement of variable inside loop returns no success status code?

Question: I can't understand why inside loop with condition of equal to 0 decrementing of variable returns non-zero status code (not success) if variable was decreased to 0?
If I use a different condition for the loop - for example - until [[ $RETR -eq 1 ]] it returns 0 status code after last decreasing, the same situation for while loop or if I use let for decreasing the variable, but decreasing by ((varr--)) returns a 0 status code.
+ RETR=3
+ [[ 3 -eq 0 ]]
+ WRONG_COMMAND
+ [[ 127 -ne 0 ]]
+ echo 'RETRIES = 3'
RETRIES = 3
+ echo 'STATUS before decrease = 0'
STATUS before decrease = 0
+ (( --RETR ))
+ echo 'STATUS AFTER decrease = 0'
STATUS AFTER decrease = 0
+ [[ 2 -eq 0 ]]
+ WRONG_COMMAND
+ [[ 127 -ne 0 ]]
+ echo 'RETRIES = 2'
RETRIES = 2
+ echo 'STATUS before decrease = 0'
STATUS before decrease = 0
+ (( --RETR ))
+ echo 'STATUS AFTER decrease = 0'
STATUS AFTER decrease = 0
+ [[ 1 -eq 0 ]]
+ WRONG_COMMAND
+ [[ 127 -ne 0 ]]
+ echo 'RETRIES = 1'
RETRIES = 1
+ echo 'STATUS before decrease = 0'
STATUS before decrease = 0
+ (( --RETR ))
+ echo 'STATUS AFTER decrease = 1'
STATUS AFTER decrease = 1
+ [[ 0 -eq 0 ]]
+ echo 0
0

The script:
#!/usr/bin/env bash

set -x

RETR=3

until [[ $RETR -eq 0 ]]; do
    WRONG_COMMAND 2>/dev/null
    if [[ $? -ne 0 ]]; then
        echo "RETRIES = $RETR"
        echo "STATUS before decrease = $?"
        ((--RETR))
        echo "STATUS AFTER decrease = $?"
    else
        RETR=0
    fi;
done;

echo $?

I expect it to returns 0 status code after the variable was decreased, but it always returns 1 if the loop condition consists of equal to 0 and the variable equals 0 after decreasing.
Answer: The exit status of ((...)) is 1 if the enclosed expression evaluates to 0, and is 1 otherwise.
When using the decrement operator, the value of the expression (and thus the exit status) depends on when the decrement occurs. With --RETR, the variable is decremented, and then the value of RETR is used. With RETR--, the value of RETR is used, then it is decremented.
For example:
$ x=1; ((x--)); echo $?  # Value of x-- is 1
0
$ x=1; ((--x)); echo $?  # Value of --x is 0

Comment: Note that this apparently somewhat weird behavior is explicitly to allow you to do concise things in loop conditions.  `while (( RETR-- )); do...` will encapsulate the decrement as well as the loop condition test all in one place.
Comment: Is this undocumented behavior? I can't find it in https://www.gnu.org/software/bash/manual/bash.html#Shell-Arithmetic.
Comment: @Xypron `man bash` and `/\(\(`. It says *If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.*
Comment: @Xypron That link only discusses the expressions that can appear in any arithmetic context,  including  `$((...))`, `((...))`, and `${array[...]}`. The [arithmetic statement](https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs) itself  (`((...))`) is for some reason lumped together with the conditional commands.


How to prove that $|Re\ h(z)|\leq\log M(r,h)$

Question: As part of a proof in complex analysis, I have encountered a claim that is presented as evident but that I don't understand and don't know how to prove. We have a function $h(z)$, and have just defined $L(z)=\log h(z)$, for reasons unclear as it doesn't seem like it is used later on in the proof. Right after this definition, comes this statement:

Since $h(z)$ has no zeroes, $L$ is an entire function, and it holds that $|Re\ h(z)|\leq\log M(r,h)$.

In this discussion, we consider:
$$M(r,h)=\underset{|z|=r}{max}|h(z)|$$
I wonder whether there is a typo and the author actually meant $|Re\ L(z)|\leq M(r,h)$. My attempt at trying to prove the claim is the following:
$$M(r,h)=\underset{|z|=r}{max}|h(z)|=\underset{|z|=r}{max}\sqrt{[Re\ h(z)]^2+[Im\ h(z)]^2}\geq\underset{|z|=r}{max}|Re\ h(z)|\geq |Re\ h(z)|,$$
$$\forall z: |z|\leq r$$
So, I have proven that $|Re\ h(z)|\leq M(r,h)$. But how to get the desired result from here? We have that $\log M(r,h)\leq M(r,h)$, not the other way around.
Any help or insights into this mystery would be greatly appreciated!
Context:
We are trying to prove that if a meromorphic function $f(z)$ satisfies the following relation:
$$\liminf_{r\to\infty}\dfrac{T(r,f)}{\log r}<\infty$$
then $f(z)$ is a rational function.
The outline of the proof is as follows. According to the first fundamental theorem of Nevanlinna, $f$ can only have a finite number of zeros ($a_1,...,a_M$) and poles ($b_1,...,b_N$). Then, $R(z)$ is a rational function with the same zeros and poles as $f(z)$ and h(z) is a meromorphic function without zeros that are not poles, that is, an analytic function without zeros, which will be rational if and only if $f(z)$ is rational:
$$h(z)=\dfrac{f(z)}{R(z)}=f(z)\dfrac{\prod_{j=1}^N(z-b_j)}{\prod_{i=1}^M(z-a_i)}$$
Using the Jensen-Poisson formula and several other results, we can prove that:
$$\liminf_{r\to\infty}\dfrac{\log M(r,h)}{\log r}=\liminf_{r\to\infty}\dfrac{T(r,h)}{\log r}<\infty$$
On the other hand, the function $L(z)=\log h(z)$ is analytical and uniform in the complex plane, and therefore is an entire function, since $h$ has no zeros. Moreover,
$$|Re\ h(z)|\leq\log M(r,h)$$
which means we can conclude
$$\liminf_{r\to\infty}\dfrac{Re\ h}{\log r}<\infty$$
and so, according to the generalized Liouville's Theorem, $h(z)$ is a constant functions, thus proving that $f(z)$ is rational.
Comment: @MartinR I added a sketch of the proof where the author introduces his strange claim. I agree that surely there must be a typo, but I can't fully understand which one or how he concludes the proof. I tried to summarize the proof as much as possible, skipping details that didn't seem necesarry to elucidate what is going on...
Comment: $|Re\ h(z)|\leq\log M(r,h)$ is surely wrong. Can you show more context how this inequality is used? That might help to recognize what the author actually meant.
Comment: What exactly is the "generalized Liouville's Theorem" that you are referring to?
Comment: Apparently the last statement should be $\liminf_{r\to\infty}\dfrac{\max_{|z|=r}Re\ L(z)}{\log r}<\infty$.
Comment: @MartinR The generalized Liouville's theorem states, according to these notes, that if an entire function $g(z)$ satisfies $\liminf_{r\to\infty} \frac{Re\ g(z)}{\log r}<\infty$, then $g$ is constant.
Comment: @MartinR I think the last statement is correct as is, because we are trying to prove that $h$ is constant by using the theorem that I just mentioned. But it seems strange to define $L$ to never use it again, and the inequality $|Re\ h(z)|\leq\log M(r,h)$ looks quite suspicious to me.
Answer: $|\operatorname{Re} h(z)|\leq\log M(r,h)$ is definitely wrong, as the example $h(z) = e^z$ shows: For $z = r > 0$ is
$$
 |\operatorname{Re} h(z)| = e^r > r = \log M(r,h) \, .
$$
The proof should go as follows: $h$ is an entire function without zeros, so $h(z) = e^{L(z)}$ with an entire function $L$. Then
$$
 |h(z)| = e^{\operatorname{Re} L(z)} \\
\implies \log |h(z)| = \operatorname{Re} L(z) \\
\implies \log M(r, h) = \max_{|z|=r} \operatorname{Re} L(z) \, .
$$
Then
$$
 \liminf_{r \to \infty} \frac{\max_{|z|=r} \operatorname{Re} L(z)}{\log r}
=\liminf_{r \to \infty} \frac{\log M(r,h)}{\log r} < \infty \, .
$$
It follows that $L$ is constant, say $L(z) = C \in \Bbb C$. Then $h(z) = e^C$ is also constant, and $f(z) = e^C \cdot R(z)$ is a rational function.


Python: title above two axes, but not above figure

Question: I'm looking for something similar toplt.subtitle() that puts a "main title" above two subplots of my choice which are in a grid. In my plot, the title Development of model parameter and Final model parameter should be something like a main title for the two axes. Is there a function for that? Or a smooth workaround?
Answer: One way would be to create an invisible axis for the common diagrams and use just the title from this axis:
import numpy as np
import matplotlib.pyplot as plt

#function for display
def f(t, a, b, c):
    return np.exp(a - t) * np.sin(b * t + c)

fig = plt.figure()

x = np.linspace(0, 10, 1000)
#curve 1
ax1 = fig.add_subplot(211)
ax1.plot(x, f(x, 5, 1, 0))
ax1.set_title("Curve 1")
#create common axis for curve 2 and 3, remove frame and ticks, set title
ax23 = fig.add_subplot(223, frameon = False)
ax23.set_xticks([])
ax23.set_yticks([])
ax23.set_title("Curve 2 and 3 together")
#create curve 2
ax2 = fig.add_subplot(245)
ax2.plot(x, f(x, 0, 3, 0))
#create curve 3
ax3 = fig.add_subplot(246)
ax3.plot(x, f(x, 2, 1, 7))
#create curve 4
ax4 = fig.add_subplot(224)
ax4.plot(x, f(x, -1, 3, -3))
ax4.set_title("Curve 4")
#display
plt.show()

Output
Comment: Perfekt! `frameon = False` was exactly what I was looking for.


Find derivative of an integral with parameter

Question: $$F(t)=\int_{0}^{t^2}\mathbb{dx}\int_{x-t}^{x+t}\sin(x^2+y^2-t^2)\mathbb{dy}$$
find $F'(t)$
Comment: Hint. $F(t)=\int_0^{t^2} g(x,t)\,dx$. Can you calculate $F'(t)$?
Answer: Recal that
$$
\small
F'(t)=\frac{d}{dt}\int\limits_{\alpha(t)}^{\beta(t)} f(t,x)dx=
\int\limits_{\alpha(t)}^{\beta(t)} \frac{df}{dt}(t,x)dx+f(t,\beta(t))\frac{d\beta}{dt}(t)-f(t,\alpha(t))\frac{d\alpha}{dt}(t)\tag{1}
$$
In your case
$$
\small
f(t,x)= \int\limits_{x-t}^{x+t}\sin(x^2+y^2-t^2)dy, \qquad \alpha(t)=0,\qquad \beta(t)=t^2
$$
So after substitution we get
$$
\small
F'(t)=\int\limits_{0}^{t^2}dx\left( \frac{d}{dt}\int\limits_{x-t}^{x+t}\sin(x^2+y^2-t^2)dy\right)+\left(\int\limits_{t^2-t}^{t^2+t}\sin(t^4+y^2-t^2)dy\right)\cdot 2t-\left(\int\limits_{0-t}^{0+t}\sin(0^2+y^2-t^2)dy\right)\cdot 0
$$
Thus
$$
\small
F'(t)=\int\limits_{0}^{t^2}dx\left( \frac{d}{dt}\int\limits_{x-t}^{x+t}\sin(x^2+y^2-t^2)dy\right)+2t\int\limits_{t^2-t}^{t^2+t}\sin(t^4+y^2-t^2)dy \tag{2}
$$
but this is not the end! Now you need to compute derivative of integral
$$
\small
\int\limits_{x-t}^{x+t}\sin(x^2+y^2-t^2)dy
$$
with respect to $t$. Though you have two parameters here you can think of $x$ as a number here. Formula $(1)$ will look like
$$
\small
G'(t)=\frac{d}{dt}\int\limits_{\gamma(t,x)}^{\delta(t,x)} g(t,x,y)dy
=\int\limits_{\gamma(t,x)}^{\delta(t,x)} \frac{dg}{dt}(t,x,y)dy+g(t,x,\delta(t,x))\frac{d\delta}{dt}(t,x)-g(t,x,\gamma(t,x))\frac{d\gamma}{dt}(t,x)\tag{3}
$$
In your case
$$
\small
g(t,x,y)=\sin(x^2+y^2-t^2)\qquad\gamma(t,x)=x-t\qquad\delta(t,x)=x+t
$$
So after substitution we get
$$
\small
G'(t)=\int\limits_{x-t}^{x+t}\cos(x^2+y^2-t^2)(-2t)dy+\sin(x^2+(x+t)^2-t^2)\cdot 1-\sin(x^2+(x-t)^2-t^2)\cdot (-1)
$$
$$
\small
=-2t\int\limits_{x-t}^{x+t}\cos(x^2+y^2-t^2)dy+\sin(2x^2+2xt)+\sin(2x^2-2xt)
$$
$$
\small
=-2t\int\limits_{x-t}^{x+t}\cos(x^2+y^2-t^2)dy+2\sin(2x^2)\cos(2xt)
$$
This finall result is
$$
\small
F'(t)=\int\limits_{0}^{t^2}dx\left( -2t\int\limits_{x-t}^{x+t}\cos(x^2+y^2-t^2)dy+2\sin(2x^2)\cos(2xt)\right)+2t\int\limits_{t^2-t}^{t^2+t}\sin(t^4+y^2-t^2)dy
$$


Role specific dashboard block

Question: I created a set of Views based blocks which will be displayed in the Dashboard's Main Content Region.But those all of them are not for the site admins. Some of them are for other roles. So I have configured those blocks' visibility settings. Added those specific roles to the "Show block for specific roles" tab. But the problem is those are being displayed in the admin dashboard as well but with no content, actually it says "empty".
Is there any way to get rid of this?
A possible duplicate but no answers in that post as well.
Dashboard - empty blocks are shown
Answer: One way to hide the blocks completely without doing any coding is to set up your own custom dashboard using the Panels module.  With Panels, you can override pages (such as the admin dashboard) and then add the blocks using Panels.  The advantage of this approach is that you can use the Visibility conditions feature of Panels to only show the block for certain roles, which will completely hide the block rather than showing an empty version.
The disadvantage of this approach is that this might be overkill if this is all you need to do.

Role specific dashboard block


If $f:\mathbb R\to \mathbb N$ is continuous, then it's constant.

Question: I have to prove that if $f:\mathbb R\to \mathbb N$ is continuous, then it's constant. Th result looks intuitive, but I can't prove it. I try by contradiction : suppose there is $x,y\in\mathbb R$ s.t. $f(x)\neq f(y)$. So in somehow $|f(x)-f(y)|\geq 1$, and thus, using the $\varepsilon -\delta $ definition with $\varepsilon <1$ I tried to get a contradiction, but since there is no reason to have $|x-y|\leq \delta $, I couldn't find a way to write it properly. Can someone give hint ?
Comment: Do you know the Intermediate Value theorem ?
Comment: Also: https://math.stackexchange.com/q/505472/42969
Answer: Method 1
Using your method : Suppose $x<y$ and $f(x)\neq f(y)$. Set $z=\inf\{t>x\mid f(t)\neq f(y)\}$. Using continuity of $f$ at $z$ should allow you to get a contradiction.
Method 2
$f^{-1}(\{f(0)\})$ is open and closed in $\mathbb R$.
Comment: **Method 3** : Use the IVT ! (+1)
Comment: Method 2 is the best one IMO, as that users the definition directly and it is still the shortest. When that happens it should be savoured.
Comment: I agree with you, but it's not sure that it's a good hint for the OP (depending on his/her topological knowledge) :-) @Arthur
Comment: @Arthur: What mean IMO ?
Comment: @Surb "in my opinion"
Comment: I don't understand the 2nd method but thanks to method 1, I could solve my exercise. Thank you.


Using images instead of text in menus

Question: I have a client who wants to use images instead of text for his menu items. Is there a native way to do this in Drupal 7?
Comment: @Jane What would be _un_-clean about hiding text with CSS? Use `text-indent` with a large negative value and you have the best solution possible: looks pretty, _and_ it remains accessible for users with disabilities. Win win
Comment: you can achieve that using CSS
Comment: I understand that, I just don't think hiding menu text with CSS is the cleanest approach, but if that is my only option, I might have to do that.
Answer: In Drupal 7 you can using

Menu Icons module

This module allows you to upload an image in the menu-item's configuration form.

Programmatically

Allow images in menu items in Drupal 7 OR Use images for menu items in Drupal

Reference:
Replacing menu items with images

Using images instead of text in menus


How to rewrite my  page URL to pagename.siteurl.com

Question: I have Dreamweaver CS3 and i was wondering if it is possible to make a html page go from idreesinc.com/research.html to research.idreesinc.com. Is it possible and if so how do i do it? I have to actually MAKE a page and not just a redirect.
Thanks!
Comment: The term you are looking for is `URL Rewrite`.
Comment: Here is a similar question: http://stackoverflow.com/questions/8490184/htaccess-mod-rewrite-subdomain
Answer: Create or edit a file in the root of your idreesinc.com site called '.htaccess'
Insert the line:
Redirect 301 /research.html http://research.idreesinc.com

Comment: Ummm sorry but how? I am new to this whole "website" thing so could you help me?
Comment: actually now that i think about i need to somehow create a page with the new url. not just redirect to it
Answer: This isn't a "rewrite", it's a redirect - but it'll be the easiest for you as a beginner.
Easy with JS. Not the "best" way mind you, but the easiest.
Add this inside the  tags or right after the opening  tag.

If you're looking for how to make a subdomain (subdomain.domain.com), you need to search:
"How to make a subdomain"
Comment: Oh so it is called a subdomain? I was looking for something completley different. Thanks!


Criar cabeçalho de tabela dinâmico

Question: Estou tentando criar um cabeçalho dinâmico baseado num array que a função recebe, a estrutura que tentei, e não funcionou, é a seguinte:
function createDynamicHeader(columns) {

          var table = document.querySelector('#table_teste');

          var header = table.createTHead();

          header.createElement('tr');

          for (var i = 0; i < columns.length; i++) {
              var header_row = header.createElement('th');
              header_row.innerHTML(columns[i]);
          }

      }

HTML:

Como posso resolver isso?
Answer: Você pode fazer assim:

function createDynamicHeader(columns) {
  var table = document.querySelector('#table_teste');

  // Cria um elemento
 vazio e o adiciona à tabela:
  var header = table.createTHead();

  // Cria um elemento
 vazio dentro do header da tabela:
  var row = header.insertRow();

  for (var i = 0; i < columns.length; i++) {
    // Insere uma nova célula () dentro do elemento
:
    var cell = row.insertCell();
    // Adiciona algum texto na nova célula:
    cell.innerHTML = columns[i];
  }
}

// Chama a função para testar.
createDynamicHeader(['Coluna TD 1', 'Coluna TD 2', 'Coluna TD 3'])

Mas, o seu código não estava dando certo por causa desses pontos:

Em header.createElement('tr'): O elemento thead não tem um método createElement(), você tem que usar o método do objeto document e depois adicionar o elemento tr criado no documento ao elemento thead; e você não estava armazenando a referência ao elemento tr criado, para depois adicionar as colunas a ele;
Em header_row = header.createElement('th'): Mesma coisa que o anterior;
Em header_row.innerHTML(columns[i]): Você estava usando innerHTML como um método, mas ela é uma propriedade, então você deveria fazer header_row.innerHTML = columns[i].

Segue a mesma solução usando o seu código original:

function createDynamicHeader(columns) {
  var table = document.querySelector('#table_teste');

  var header = table.createTHead();

  var row = document.createElement('tr');
  header.appendChild(row);

  for (var i = 0; i < columns.length; i++) {
    var cell = document.createElement('th');
    cell.innerHTML = columns[i];
    row.appendChild(cell);
  }
}

createDynamicHeader(['Coluna TH 1', 'Coluna TH 2', 'Coluna TH 3'])

Criar cabeçalho de tabela dinâmico


React Functional Component: Immediately calling getElementById returns null

Question: If I add a timeout with 0ms then I can console log the elements that I have selected with document.getElementById but if I remove the 0 ms timeout they all return null. What's going on here?
import React from 'react';

const Warning: React.FC = () => {

  setTimeout(() => {
    const confirm = document.getElementById("confirm");
    const invalid = document.getElementById("invalid");
    const confirmed = document.getElementById("confirmed");
    const warningBar = document.getElementById("warning-bar");
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  },0);

  return (

Confirm

Invalid

Confirmed

  );
}

export {Warning};

Comment: Why it happens? getElementById is executed before anything is rendered so you'll need to add the timeout or add it inside a lifecycle hook.

If for some reason you actually want a reference to the elements you should use the ref attribute on the element.
Comment: Similar question. Check the answer here. [Link](https://stackoverflow.com/a/57843088/2878777)
Answer: Use useEffect and provide an empty dependencies array as a second argument, the callback function will be called after the component renders for the first time
import React, { useEffect } from 'react';

const Warning: React.FC = () => {
  useEffect(() => {
    const confirm = document.getElementById("confirm");
    const invalid = document.getElementById("invalid");
    const confirmed = document.getElementById("confirmed");
    const warningBar = document.getElementById("warning-bar");
    console.log(confirm);
    console.log(invalid);
    console.log(confirmed);
    console.log(warningBar);
  }, []);

  return (

Confirm

Invalid

Confirmed

  );
};

Answer: It is executing before your component load, so you need to render your dom first and get dom element after that
Comment: ok sounds good, how do i delay the execution until the dom has rendered without using a timeout?
Comment: You can use useEffect hook for that


Install Bitnami Redmine stack on an existing Mysql database

Question: I'm using Ubuntu server. I'm already using a Mysql server and I want to add Redmine to it. The problem is that I'm not sure when Mysql server is installed by "Bitnami Redmine stack" again, if my old database will still be usable or not. Any ideas?
Answer: If you already had a MySQL database running in port 3306 when you installed the BitNami Redmine stack you should have prompted for entering a new port for the MySQL server bundled in the stack. Your old database should be still usable, but your BitNami installation will use its own MySQL server.
Answer: Incase if you using same port need to stop it and start the mysql of bitnami redmin using ctrlscript .
I have already add the installation document for bitnami redmine and issues related with that while installing in below mentioned link.
Issues related to starting mysql while installing redmine


WPF: How to reuse controls when ObservableCollection is concrete?

Question: I have a object that inherits from TabItem. I have a bunch of Database objects that will reuse the same code so I wanted only one TabItem class and then use DataTemplates to control how each object gets presented.
Problem is that the TabItem shows a collection of Objects and ObservableCollection is concrete.
I've pondered a few solutions but none of them work. Seems like I will have to create one class for each object type even when they will all be the same (except for ObservableCollection having different types). That's not very DRY.
I can't make a UserControl generic, I can't let the UserControl constructor take in a generic class ( unless I define the Type wihc I don't wan't to do). I guess creating a base UserControl class and then inheriting that will have to do. Does it inherit the XAML code as well or will I have to rely on styles and templates?
Am I missing something?
Answer: Look into using DataTemplateSelector to provide flexibily in how you present your data in WPF.
Here are three sites that helped me:

Data Templating Overview
How to use DataTemplateSelector to alter views of objects in a ListBox
WPF Tutorial - How To Use A DataTemplateSelector
Comment: Having not yet looked into Data templating I'm wondering if it's the solution. I have no problem applying the right DataTemplate. I have more of a problem in the Code Behind because I have to make a new class for each type to be able to put it into the correct ObservableCollection. I'll take a look.
Comment: Sorry I can't see how this is related to my problem. The real problem is the Generic class ObservableCollection. If I wan't to have one collection for multiple sibling types (all inherit from same base class) it doesn't work. Trying to typecast it into the collection results in some WPF error but no C# code error.


To catch id from gridview to fillgridview

Question: I have two gridview on one page.. i have listed the first one than from commandargument("id") i listed the second one.. but i am doing something on these gridviews i can fulfill the first gridview because it is not necessary to catch id to list it. it is listing all it has. but the second one, i want to list just the categoryid of that product. can you help me ? and the translation of the words;
Doldur : Fill / Guncelle : Update / Sil : Delete / vazgec : Cancel
The wrong place is with full of question mark. Thanks for your help
<code>     private void Doldur()
    {
        WebHelper.FillGridView(myGrid, Service.GetAllCategories());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            return;

        Doldur();
    }

    protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow row = null;

        if (e.CommandSource is ImageButton)
        {
            row = ((e.CommandSource as ImageButton).NamingContainer) as GridViewRow;
        }

        int id = 0;

        int.TryParse(e.CommandArgument.ToString(), out id);

        switch (e.CommandName)
        {
            case "sil":
                Service.Sil(id);
                break;
            case "guncelle":
                // textbox'ı yakalamak için
                TextBox txtKategoriAd = myGrid.Rows[row.RowIndex].FindControl("txtKategoriAd") as TextBox;
                var kategori = new Categories { CategoryID = id, CategoryName = txtKategoriAd.Text };
                Service.Update(kategori);
                // Edit moddan çıkılmalı..
                myGrid.EditIndex = -1;
                break;
            case "vazgec":
                myGrid.EditIndex = -1;
                break;
            case "link":
                int categoryId = Convert.ToInt32(e.CommandArgument);
                myGrid2.DataSource = Service.GetProductsByCategories(categoryId);
                myGrid2.DataBind();
                break;
        }

        Doldur();
    }
    protected void myGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        myGrid.EditIndex = e.NewEditIndex;
        Doldur();
    }

    private void Doldur2()
    {
        WebHelper.FillGridView(myGrid2, Service.GetProductsByCategories(??????));
    }

    protected void myGrid2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow row = null;

        if (e.CommandSource is ImageButton)
        {
            row = ((e.CommandSource as ImageButton).NamingContainer) as GridViewRow;
        }

        int id = 0;

        int.TryParse(e.CommandArgument.ToString(), out id);

        switch (e.CommandName)
        {
            case "sil2":
                Service.Sil2(id);
                break;
            case "guncelle2":
                // textbox'ı yakalamak için
                TextBox txtKategoriAd2 = myGrid2.Rows[row.RowIndex].FindControl("txtKategoriAd2") as TextBox;
                var product = new Products { ProductID = id, ProductName = txtKategoriAd2.Text };
                Service.Update2(product);
                // Edit moddan çıkılmalı..
                myGrid2.EditIndex = -1;
                break;
            case "vazgec2":
                myGrid2.EditIndex = -1;
                break;
        }

        Doldur2();
    }
    protected void myGrid2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        myGrid2.EditIndex = e.NewEditIndex;
        Doldur2();
    }
}
</code>
Answer: you should save category id for second grid.
<code>case "link":
                int categoryId = Convert.ToInt32(e.CommandArgument);
                Session["CategoryID"] = categoryId;
                myGrid2.DataSource = Service.GetProductsByCategories(categoryId);
                myGrid2.DataBind();
                break;
</code>
and
<code> private void Doldur2()
    {
        int catid = (int)Session["CategoryID"];
        WebHelper.FillGridView(myGrid2, Service.GetProductsByCategories(catid));
    }
</code>
thats all.


Doob's inequality in probability

Question: In the book "Optimal Stopping and Free-Boundary Problems" there is given Doob's inequality of the following form.

Let $X = (X_t,F_t)$ be a submartingale. Then for any $\varepsilon>0$ and each $T>0$
  $$
\mathsf P\left\{\sup\limits_{t\leq T}|X_t|\geq \varepsilon\right\}\leq \frac 1\varepsilon \sup\limits_{t\leq T}\,\,\,\mathsf E\,|X_t|.
$$

On the other hand, George Lowther presented the following example. Let $X_0 = 0$,
$$
X_1 = \begin{cases}
1, &\quad p = 1/3;
\\
0, &\quad p = 1/3;
\\
-1,&\quad p =1/3.
\end{cases}
$$
and $X_2 = 1$ if $X_1 = 1$, $X_2 = 0$ if $X_1 = -1$ and
$$
X_2 = \begin{cases}
1, &\quad p = 1/2;
\
-1,&\quad p =1/2.
\end{cases}
$$
if $X_1 = 0$. Finally, $X_n = X_2$ for all $n\geq 2$.
It is easy to check that this is a submartingale. On the other hand, for $\varepsilon = 1$ we have
$$
\mathsf P\left\{\sup\limits_{n\leq 2}|X_n|\geq 1\right\} = 1
$$
but $\mathsf E[|X_0|] = 0$, $\mathsf E[|X_1|] = 2/3$ and $\mathsf E[|X_2|] = 2/3$ - so we have inequality $1\leq 2/3$.
Could you help with finding a mistake since I am confused?
The reference can be seen here:
http://books.google.com/books?id=UinZbLqpUDEC&pg=PA60&source=gbs_toc_r&cad=4#v=onepage&q&f=false page 62.
This question raised from the discussion here:
Bounds for submartingale
Comment: I've deleted my incorrect answer.
Comment: @mpiktas: I wish it was correct )
Answer: Doob inequality is stated for nonnegative submartingales $X_t$:
$$E\sup_{t\le T}X_t\le EX_T$$
Note, no modulus. In your case you have a submartingale $X_t$, which is not nonnegative. Furthermore $|X_t|$ is not actualy a submartingale, so you cannot apply this inequality here.
The probability space here is $\Omega=\{\omega_1,...,\omega_4\}$, with $P(\{\omega_1\})=1/3$, $P(\{\omega_2\})=1/3$, $P(\{\omega_3\})=1/6$ and $P(\{\omega_4\})=1/6$.
We have $X_1(\omega_1,...,\omega_4)=(1,-1,0,0)$ and $X_2(\omega_1,...,\omega_4)=(1,0,1,-1)$. Now $Y_1=|X_1|=(1,1,0,0)$  and $Y_2=|X_2|=(1,0,1,1)$ and we have that
$$E(Y_2|Y_1)=(1/3,1/3,1,1)$$
Update: I've finaly found the correct answer in another book of Shyriaev (page 492, Probability, second edition, 1995). The actual inequality for any submartingales is
$$P(\sup_{t\le T}|X_t|>\varepsilon)\le \frac{3}{\varepsilon}\sup_{t\le T}E|X_t|$$
Note the missing constant 3. This means that there is an error in the book in the link.
Comment: $|X_1(\omega_2)| = 1$, isn't it?
Comment: @Gortaur, ah yes :) Sorry
Comment: @Gortaur, the error is somewhere else. I will try to find it and fix the answer.
Comment: @Gortaur, here is the second try. Hopefully it is ok :) But with my recent luck of incorrect answers I do not hold my breath.
Comment: @mpiktas: I am interested exactly in the correctness of the result from the book I quoted. Do you mean that there is a mistake?
Comment: @mpiktas: I think that's it. There is also written that if $X_n$ is a sign-semidefinite supermartingale, then $C = 1$ - so inequality which I stated in topic http://math.stackexchange.com/questions/45886/bounds-for-submartingale is still correct. Anyway, either in the book of 2006 the proved that $C=1$ for all cases - but then there is a counterexample by George.

Doob's inequality in probability


Showing the Clairaut theorem in higher dimensions -- partials commute

Question: Suppose $f$ has all partial derivatives up to and including $k$ and all of these partials are continuous. Prove that if $\sigma$ is a permutation on $n$ letters (any reordering), then $$D_{i_1i_2...i_n}f = D_{i{\sigma (1)}i{\sigma (2)}...i{\sigma (n)}}f$$ Basically, prove that we can reorder mixed partials however we like, as long as every partial is continuous.
I get that this is basically the Clairaut theorem extended, but I'm not sure how to extend it appropriately. One thought was just to observe that you can get to any order by a sequence of 'flipping' two adjacent partials -- i.e if we have 123 we can make it 321 through 123 -> 132 -> 312 -> 321. This would involve only 2 at once so, I think, would be just an application of the Clairaut. But I'm not sure how to formalize this.
Answer: Your idea is good since adjacent transpositions generate all permutations. So it suffices to show that Clauraut's theorem holds for adjacent transpositions.
Comment: I know how to show that it holds in the classic way, i.e. $D_{12}f = D_{21}f$, but I'm not sure how to go the next step to saying that that holds even if it's in a string of other ones (i.e. adjacent ones in a bunch of them). Thanks!
Comment: @Craig: could you clarify the trouble? What happens if you emulate the two dimensional proof in higher dimensions?
Comment: I think my problem was more with how to set up the proof. I had it intuitively, but was having trouble formalizing it.


How to treat -classpath attribute Java 10 in JNI

Question: My project is highly dependable on JNI to communicate with C code. I have been using Java 8 for years now. I decided to upgrade to Java 10 but I have faced a problem with JNI implementation.
I have some imported libraries in the Java class that contains the native methods as follows:
import com.abc.repair.Results;

public class DataSupport {

    public native Results getPartResults(String x);
    public native Results getItemResults(String x);
}

Java 8 Implementation:
javah -jni -classpath ../lib/Results.jar com.abc.jni.DataSupport

Java 10 implementation:
javac -h . ../build/com/abc/jni/DataSupport.java

Java 10's implementation works great if there is no import from any other library. However it fails to build complaining about com.abc.repair.Results does not exist when here is any import. Adding class path the same way used in Java 8 did not solve the problem.
How can I use -classpath or what is the alternative to it in Java 10?
Comment: Did you try adding the jar to the `modulepath` instead?
Answer: You must specify sourcepath. In your case, it would look like
javac -h . -sourcepath ../build ../build/com/abc/jni/DataSupport.java

Comment: That `.` is where to store the generated header
Comment: It actually worked with javac -h . -classpath ../build ../build/com/abc/jni/DataSupport.java. I just had to put the "." (the current directory) before -classpath attribute. Your hint helped. Thank you!


Is there a color representation of music?

Question: I was wondering, is there a color representation of music? If someone ever tried to represent frequencies with colors could the whole music piece be represented by color somehow?
What do Beethoven's pieces look like if represented as color diagrams or images?
I know this may sound silly but maybe someone thought about it and did eventually try.
Comment: See this interesting video about synthesia: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjf1uGrk-zYAhUBXLwKHWofAxAQtwIIJjAA&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZAqyw606WQQ&usg=AOvVaw36Kxa8Vw7lW7z-Frdos4bl
Comment: This questions is not a duplicate of "is there a color code for notes". The other is a practical question, about relating notes and colors for pedagogical reasons. This question is deeper and raises questions related with several areas like sound preception.
Comment: A very direct conversion would not work as our eyes sense frequencies very differently to our ears.  For a start, the whole visible range of light is less than one octave.
Comment: No, I haven't seen Fantasia!
Answer: Check out the wiki article on the Scriabin Colour Organ - the very earliest precursor of coloured lighting accompanying a performance.
Answer: What you're looking for is probably music visualization.
Talking about color representation of music may be a bit basic. There are too many combinations and it depens on how you create the relation note/color. There isn't a unique way for sure.
There is a video with a very simple example:

For more complex visualizations of music I would look at the work of Stephen Malinowski http://stephenmalinowski.com/
He is a composer and programmer who created software to generate animations based on music.
But even before this, much before computer animation, at the beginning of the 20th century (1920) there were already people thinking on how music would look like, creating animations to visulize both color, fades, movement and form. You should definitely look at the seminal work of Oskar Fischinger https://en.wikipedia.org/wiki/Oskar_Fischinger
Answer: I used to use a couple of beginner piano books for kids called 'Through the Rainbow', I seem to remember. Each of the white piano keys was represented by a colour from the rainbow. Are you thinking more along the synaesthesia lines?


Proper way to setup propensity matching

Question: I'm involved in a study where we want to examine the effects of two different types of implant on a variety of health outcomes.  We've collected a ton of data on about 200 patients who received either type of implant and we were about to examine outcomes but we realized that our patient populations for each implant type were a little bit different (due to a variety of reasons like which surgeon was doing what operation/time period/etc...).
So the other investigators I'm working with suggested we match our patients into two groups that have relatively similar values of these covariates:  age (a number), obesity (true/false), smoking history (four levels), radiation history (true/false), and plane of reconstruction (subpectoral versus prepectoral) for the surgery.
So, given I was new to matching, I followed this tutorial to match based on those covariates, but then I realized I ran into some problems.  When I used the code:
mod_match <- matchit(graft ~ Age + other_comorbidities___4 + smoking + radiation + subpec_vs_prepec, method = "nearest", data = Data_nomiss)

dta_m <- match.data(mod_match)

to match my data, it returned data that was wildly NOT matched.  I.e. obesity in one group was 70% while 20% in the other group.  Age was decades different, etc..
From what I can determine from answers like this one, it seems like my problem stems from matching on the propensity score specifically, rather than matching on the covariates (which it sounds like is what I wanted to do).  It also seems like factor variables are treated differently than continuous ones and can cause some problems.
So my question is two-fold:

If I'm trying to match groups that have relatively similar values for those 5 covariates, should I still use the matchIt package? (If so I would love input on which "method" and how to setup that code.  For instance I didn't understand his comment about "exact" in that answer)
If there is a different package or method to match, I would love some
direction on what that is called/where to look.

Thank you!
Answer: Matching is in art in the sense that you may need to try a variety of specifications to find one that works for your data, if at all (I'll get back to the "if at all" at the end). 1:1 propensity score matching without replacement is almost certainly the worst matching method to use, especially in your case with so few observations. It is the default because other methods can be layered on top of it to create a matching specification that works. You need to try many different matching specifications to find one that achieves balance without destroying your (effective) sample size. Did you try full matching (setting method = "full")? Did you try cardinality matching (setting method = "cardinality")? Did you try adding a caliper (using the caliper argument)? Did you try adding an exact matching restriction (using the exact argument)? There are so many ways to customize a matching specification, and all the ones available in MatchIt are described in the Matching Methods vignette. I also highly recommend using the MatchIt tutorial vignette instead of the one you found.
My next point is whether matching is the right method for you. Why do you want to use matching over other methods of confounding control, like regression? With such a small sample, it is probable that variability in the effect estimate will be vastly greater than the bias that matching would eliminate that wouldn't be eliminated with regression. If you have a problem with separability number of events per variable, try penalized logistic regression (e.g., using the brglm2 package). It may also be the case that you tiny sampel simply doesn't contain enough information for you to reliably remove confounding and estimate an effect with precision, and you will need to decide on a tradeoff between the two or collecting more data.
Comment: That is correct and a given in matching. As long as you don't involve the outcome in your analysis, you are not "cheating". You should report your failed attempts to match in your manuscript so readers understand that matching is an iterative process and you didn't just choose the one that gave you the best effect estimate.
Comment: Thank you for your insightful comments!  To answer some of those questions, I'll have to discuss with my co-investigators first.  Sounds like (and this may be just opinion), the best bet is to try several methods and see how well they each "match"?  I.e. there may not be one absolutely best rule we should use. Correct?

Proper way to setup propensity matching


Most efficient way to download and process a large database (1 GB I think)?

Question: I am looking to download the entire US Government Lobbying Disclosure Act (LDA) Contributions Database and based on some quick math it looks like it will be about 1 GB large (https://lda.senate.gov/api/v1/contributions/).
What is the most efficient way to use the LDA API to download all of this data and create my own database? I have never done a project like this and have no concept for how large this actually is. I am using Python also.
I ask because I don't want to have to keep using the url queries to get the information I need. The lobbyists who filed all of these contributions use alternate spellings and typos when writing in the names of the candidates they donated money to so I am going to use regex or fuzzywuzzy to account for those differences (something I can't pass in the url queries).
Some quick math to make sense of the scale:
(https://lda.senate.gov/api/v1/contributions/)
I used this JSON size analyzer to get the size of page 1/19,892 of the database and it said it is 50.2 KB.
50.2 KB * 19892 = .998 GB (size of entire database)
My previous database where I tediously queried each of the few dozen candidates has a csv file that is 22.1 MB (.0221 GB) and has 30,852 rows of data.
So 30,852 rows / .0221 GB = 1,396,018 rows for 1 GB?
Does this math follow, and if so, is this a crazy large database?
Would it take a very long time to download all of this, and once I have the database, is it going to be very slow if I wanted to iterate through the entire database to select for the specific candidates that I want (esp. when using tools like regex)?
Do I want to use an iJson for this?
Also would csv be the best file format to store this data?
Again I have no clue if this is a massive dataset that will crash my code and computer or if this is peanuts to what some of you professionals are doing on a daily basis.
Thank you so much for any help on this!
Comment: How often are you going to download the entire database?  My suggestion is to download the entire database as JSON, process the JSON as much as you possibly can by correcting misspelled names, and writing the corrected information to a relational database.  If it takes two days to download the database, it's two days once every few weeks or months.
Answer: I suggest you after download, use AVL tree method to indexing the database. AVL tree requires long time to make the searching index but after that you Will have a very fast way to find specific candidate you are looking for.
Comment: Hi Emilio! Wondering what would be the fastest way to fetch all of the data with python. I read that for loops are much slower and perhaps another method could allow me to download the data to a csv file much faster?
Comment: I'm not expert to download but after download,

I have 4 Gbyte DataBase consisting in 80000 files, using python with AVL tree methods,

it takes 100 hours to generate 1286012 index files.

After that I am able to reach every single fetch in 50 msec. It's very fast, doesn't it?

It's complicated I know, and also if you need often modify the content of Db it takes long time, for me medium each single modification takes few sec.


Screen. Turn on logging(like -L) by screenrc

Question: Which option in screenrc working like "screen -L"?
I want turn on logging globaly. Try option "log on" into /etc/screenrc, but write "log: window required" when screen startup.
Answer: Use deflog on instead of log on.
From the manpage:
 deflog on|off

   Same as the log command except that the default setting for new windows is changed. Initial setting is off.

If you really want to use log on, you need to first select a window with screen 0, but be aware this configuration does not configure logging for all windows...


Do I use the Chi-squared test for independence to check whether or not I should put two predictor variables into the same regression model?

Question: I don't have a statistical background, so a lot of this stuff confuses me (sorry if this is a bad question).
But, I am trying to construct a few Probit regression models in R on a dataset that consists of only categorical variables. All my dependent and independent variables are categorical.

I have already identified what my dependent and independent variables are. However, when I am constructing the Probit model I am pretty sure I need to make sure all my independent variables that will be included in each model are, well, independent from each other. So to do this, I would run the Chi Squared test of independence between each of the independent variables, right?

If the Chi Squared Test of independence says the two predictor variables are not independent, then I think I should only choose one to put in my regression model. Is there a test to run that tells me which predictor variable to include over the other?

I think I have to convert all variables into a 0, 1 dummy variable before constructing the regression. Can I do the Chi-squared test on the variables before making them into dummy variables?
Answer:
The chi-squared test is a good test of the independence of two categorical variables, yes.

Generalized linear models like probit regression make no assumptions about feature independence. There are advantages of feature independence, such as narrower confidence intervals and ease of interpretation, but there are disadvantages to dropping variables, such as biasing coefficient estimates and lowering predictive capacity. It is not a given that you should drop features just because they are related. Each could contain its own unique contribution to the outcome. Further, feature selection is known to lack stability, so determining which features to drop and which to keep is iffy. See Frank Harrell's post about feature selection.

To a large extent, this is about the particular software in which you conduct the test. If the function wants 0/1 encoding, you have to do it that way. If the software wants a contingency table, you do it that way. If the software wants a data frame, you do it that way. (A good exercise might be to figure out how to run the test in each of those ways and why they are equivalent.)


Loop through Ansible variable in in .j2 file

Question: I have one ansible var list defined in group_vars
<code>member_list:
        - a
        - b
</code>
I have one proxy.j2 template
<code>{% for var in members_list %}
server {

server_name {{ var }}-{{ server_name }};
{% endfor %}
</code>
How could I loop through that list to get the value in .j2 file?
Comment: jinja loops use curly braces, check jinja documentation
Comment: Your iterator is named `var`, so use `var` not `var.members_list`.
Comment: I am getting error var is undefined
Answer: You should be using {{ item }} instead of {{ var }}.


Colocar um valor default no binding.value Vue Directive

Question: Gente to criando uma directive simples e queria saber como coloco um valor se o binding.value for undefined de uma forma mais simples, bem parecido como o Vue Component em que pode setar o defalut value?
Exemplo:
Vue.directive('color', {
    bind: function (el, binding) {
        var prop = binding.value,
            color = prop.color

            if(color == undefined) color = '#FFFFFF'

        el.style.backgroundColor = color
    }
})

Answer: De forma mais objetiva e direta você pode resolver assim:
Vue.directive('color', {
    bind: function (el, binding) {
        var prop = (binding.value || { color: '#FFFFFF' }),
            color = prop.color

        // Não vai mais precisa dessa checagem.
        //if(color == undefined) color = '#FFFFFF'

        el.style.backgroundColor = color
    }
})


When should I create multiple Displays of a View instead of multiple Views?

Question: Is it simply a matter of convenience to create multiple Displays of a View instead of multiple Views, or is there a performance benefit?
Does having any of the following items present in some Displays but not others affect the View as a whole?

contextual filters
content type filters
aggregation

For example, I'm curious whether having a display show just Article content type results, another showing Forum results, another showing a custom Photo content type makes each display run slower.  Or if the Views all share the same content type, but differ only in that one has a contextual filter for nid, and the others don't, do they all slow down?
If I have 30 Displays for a single view, should I refactor it for performance benefit, or just because the UI wasn't meant to show that many Displays.
Answer: Code-wise, both Views and displays are represented by objects. When a View is being processed, it loads all it's child displays into memory, regardless if you are rendering only one View in the page you are looking at. While database queries are executed only for the active display, the properties of the inactive displays are still loaded into memory.
This means that if you have 50 displays in one View, 50 displays will be loaded into memory, regardless if you are only displaying only one of them. So the answer to your question is yes, typically the more displays in a view you have, the more inefficient the View becomes memory-wise.
With that being said, I personally think that having anywhere between 2-10 displays in a View should prove negligible memory-wise. Having a discreet amount of displays in a View does serve it's practical purposes, after all (otherwise, why would they be there in the first place?).
As to your second question (performance impact of additional filters, etc), yes, adding certain parameters to your View will affect performance. If you want to know by exactly how much, you can go to admin/structure/views/settings (if you are in D7) and select Show information and statistics about the view during live preview, Show the SQL query, and Show performance statistics. Here is a screenshot of the performance screen:

If you are further interested in the behavior of the queries (how many rows are analyzed, which keys are used), you can copy the query from the Views interface (once you've selected "Show SQL query"), and analyze the query using the MySQL explain command. There's plenty of articles like this one for explain usage on Google.
Comment: One follow up question: When you say the child displays are loaded into memory, are the result sets of all displays loaded, or just the query strings themselves?
Comment: @PetroleumJelliffe A class instance representing each display is attached to a View class instance. Database results are only fetched for the current "active" display, so none of the other attached display instances hold database results or query strings, for that matter. As far as I know, query strings in Views displays are constructed only for the active display being executed.


I want to Bind this 2 monthly tax table

Question: I have an example SQL table which has invoice details (Total amount , date exc..). I want to make a SQL View using this invoice table. This view has to include MyInvoiceTax and CustomerInvoiceTax and month parameters.Also if one of this 2 column (MyInvoiceTax and CustomerInvoiceTax) has 0 value, I need to write zero. That calculations should be done by month. FaturaTuru is defining which invoice is mine (1 = sales , 0= goings ).
Screenshot
Select SUM(KdvTutari) as MyIncoiceTax , DATENAME(MONTH,TumFaturaTbl.Tarih) as Month from TumFaturaTbl where  FaturaTuru=1 Group By DATENAME(MONTH,TumFaturaTbl.Tarih)

Select SUM(KdvTutari) as CustomerInvoiceTax , DATENAME(MONTH,TumFaturaTbl.Tarih) as Month from TumFaturaTbl where  FaturaTuru=0 Group By DATENAME(MONTH,TumFaturaTbl.Tarih)

I`ve tried bind with nested select query. But it didn't work.
Comment: [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Answer: Conditional aggregation Sum(Case...)
.
SELECT SUM(case when FaturaTuru=1 then KdvTutari else 0 end) as MyIncoiceTax,
       SUM(case when FaturaTuru=0 then KdvTutari else 0 end) as CustomerInvoiceTax,
       DATENAME(MONTH,TumFaturaTbl.Tarih) as Month
FROM TumFaturaTbl
WHERE FaturaTuru in (1,0)
GROUP BY DATENAME(MONTH,TumFaturaTbl.Tarih)
--ORDER by month(TumFaturaTbl.Tarih) ASC

Caution should be warranted if you're just grouping by month, you will get multiple years in a given month unless yo have year limits somehow....
Alternatively one could use a pivot function...  Though I generally I try and avoid presentation aspects in SQL.
Comment: Hi. thx for your answer. It`is working great but I need to use a month for once.I mean if april has value for MyInvoiceTax  it has to be in same row with CustomerInvoiceTax in april . Your solution`s export like this : https://i.hizliresim.com/c1akj7h.PNG
Comment: remove `FaturaTuru` from the `group by`  oversight on my part from.

I want to Bind this 2 monthly tax table


Remote Desktop to 80% of my servers do no longer work ("User account restriction") from just one of my PCs

Question: I came into work last week, checked my first ticket (easy to fix one), RDP'd into the server needed for this and the login did not work. After clicking 'connect' I got the "Unable to Log You on Because of an Account Restriction" message. Checked another server (all machines are 2008R2/2012R2), the same message. No, I do not habe an empty password, not using network auth, my clint is Windows 10 (1607).
Here is what I did:

Used another client (Win10.1607), same ou, same setup. Can perfectly login from anywhere to anywhere (so I am asuming it's no my user account or a GPO)
Checked servers: I can RDP into all my DC's and a few other machines (2008R2/2012R2), looks random to me (all server in the same OU, no special software installed)
Deleted the mstsc cache (%appdata%..\local\Microsoft\Terminal Server Client* )
Cleaned up HCU\SOFTWARE\Microsoft\Terminal Server Client
Watched the eventlogs: nothing. Absolutely nothing. So I assume it's my client, not the servers. But I can RDP into all my servers at home and in another (customers) network ...
Checked date/time on client/server (0.0002ms apart)
Checked account restrictions on ma account (neither time nor machine restrictions are present)
Checked if logon at the console works (vm/ilo): works perfectly fine with my credentials
Checked if Share-Access would work (\\server\share): Does not work, I am seeing the same error message. Works from clientB, but not from alientA.
When doing the same thing from one of the 'working' machines (sever or client), everything is fine.

Any Ideas where to look for this? It is haunting me into my sleep :-(
Updates: Surely I checked the local policies on the server(s). any changes would have surprised me - there are a lot of servers. Also checked the clients GPO, nothing.
Comment: Try logging on with a different account.
Comment: First, a good sleep is required for solving stuff... Anyway, maybe there's a local GPO that blocks it (allow\deny remote\network access under security settings). Can you post results of 'gpresult /h gpresoprt.html'?
Comment: @GregAskew: does not work either (eg 'administrator', the default and first domain admin). Not from this client. Works from other clients/servers.
Comment: @EliadTech: my client is not member of the domain, so my report is rather short. The gpresult of the server(s) are somewhat larger, but due to the intimate details I am not allowed to post it completely. I checked the resultset before (using rsop.msc) and found nothing (no User/Group restrictions). Do you have any special places I should have look at?
Comment: You can RDP to and from servers and desktops that belong to the domain. You cannot RDP from this PC1 that is in workgroup mode. Is there a different PC2 that is also in workgroup that you can try to RDP from?
Comment: @bjoster GPEdit.msc > Computer settings > Windows settings > Security settings > Local policies > User rights assignments > 1. Allow\Deny log on through Remote Desktop Services 2. Access this computer from the network. Also, for clarity, you get the error after typing username and password, right?
Comment: @bjoster One more thing, you contradicted yourself: you wrote "Used another client (Win10.1607), same ou..." in the question, but you wrote in the comments the the client is not domain-joined. So... ?
Comment: @Craig620: Yes, I can use any other computer here, part of the domain or not.
Comment: To clear thing up (sorry for my somewhat chaotic description): We do have multiple (client) computers here, some are part of the domain, some are not. My primary personal machine is not joined. RDP works from any other computer, joined or not. My test clients are Win10.1607(joined), Win10.1607(not-joined), Win8.1(joined), Win8.1(not-joined), and the servers. The only machine RDP is not working from (here), is my personal Win10 (not joined) machine. @EliadTech: Yes. Skipped (sure) when using saved credentials.
Comment: What do the logs on the server and your client show?
Comment: @bjoster I'd say dive again into the event logs, maybe even set some more audit options. Otherwise, just format your PC (maybe try a Live-cd first, just to be on the safe side).
Comment: @user5870571: The mstsc client does not have logging besides the eventlogs TerminalService-Client* (which do show nothing). The server logs are completely clean. I can see the TCP-Connection when sniffing with Wireshark.
Comment: If you are getting a logon error from the server and you don't have anything in the server logs, my first suggestion is get your logging corrected. The logs will likely contain helpful information but if you don't have logging enabled then you are doing a lot of guessing.
Comment: @user5870571: Do you knwo how to enable logging on the client? @ EliadTech Booting from another OS works, it's not my Hardware :-) It even work from within a VM.
Comment: If the error is being generated by the server then you want to enable logging on the server.
Comment: @bjoster You get an error regarding the account, so the RDP itself (probably) isn't the issue. Look at the security logs, maybe [add more auditing](https://rdpguard.com/windows-server-how-to-catch-failed-logons.aspx).
Answer: The solution in my case was the option "Restrict delegation of Credentials to remote Servers".
Basically, there is a new Group policy settings that can prevent a system to pass credentials to a remote server.  This was exactly the issue. you can find this setting in your lokal oder domain group policy under:
<code>Computer Configuration > Administrative Templates > System > Credential Delegation
</code>


What's the simplest forwarding class definition in Python?

Question: I'd like to implement a forwarding class in Python, implementing some base class, which takes in its constructor another implementation of the same base class and forwards through to that class for each method in the base class.
This can be useful to provide a customization point, adding in caching for certain methods, logging around each call site, and the like.
It's simple to write this manually. Given this base class:
class BaseClass(object):
    def method_a(self, *args):
        pass

    @property
    def prop_b(self):
        pass

    def method_c(self, a, b, **kwargs):
        pass

Here's a straightforward forwarding implementation.
class ForwardBaseClass(BaseClass):
    def __init__(self, underlying_implementation):
        self._impl = underlying_implementation

    def method_a(self, *args):
        return self._impl.method_a(*args)

    @property
    def prop_b(self):
        return self._impl.prop_b

    def method_c(self, a, b, **kwargs):
        return self._impl.method_c(a, b, **kwargs)

The downside of just writing the code is that there's a lot of boilerplate code, and that code has to be written for each method. As methods are added to the base class, similar code has to be added into the forwarding class; and if changes are desired in how the class does its forwarding, they have to be spread through all the methods. (Imagine, for instance, that we wanted to change the class so that it took a context manager which it used around each call.)
Is there a short, Pythonic way to do this, either in the base language, with built-in modules, or with some reliable module on PyPI?
Desired features:

Exact method signatures

The forwarded signature should match the base class
No *args, **kwargs on every signature

Methods with the @property decorator are wrapped properly
__<method>__ methods, if they exist, are wrapped properly
No extra cost per method call over the straight-forward implementation
dir(instance) does the same thing as a straight-forward implementation

Nice to have:

Error messages where the base class doesn't meet some necessary criteria
Meaningful docstrings
Ability to derive from the resulting object
Methods with the @staticmethod decorator are forwarded to the class of the passed-in implementation
Methods with the @classmethod decorator are forwarded to the class of the passed-in implementation
__init__ and __new__ are not forwarded

Places where there is likely additional complexity:

Base class has a metaclass
Base class has multiple base classes of its own
Some of the more esoteric __<method>__s and their semantics

Don't really care about:

Multiple base classes
Custom descriptor decorators other than @property, @staticmethod, and @classmethod
Modifications to the base class after forwarding class creation
Comment: you could use `getattr` to forward everything except `__init__` and `__new__` (and other things you do not want) to `self._impl`. this may not have all your desired properties though...
Comment: I doubt there is a short, Pythonic or otherwise way to do this, frankly!
Comment: In particular the "No extra cost per method call over the straight-forward implementation" seem to be hard to satisfy, at least if you want to catch all kind of odd situations. The solution you suggests for example redirects the calls to the `self._impl` object - this extra call carries some extra cost per call. Also the requirement for `dir(instance)` to work means some more work that could hurt per call cost.
Answer: just to clarify my comment: what i mean is +/- this (needs more work though... and again: may not satisfy all your requirements):
class BaseClass(object):
    def method_a(self, *args):
        pass

    @property
    def prop_b(self):
        pass

    def method_c(self, a, b, **kwargs):
        pass

class ForwardBaseClass(BaseClass):
    def __init__(self, underlying_implementation):
        self._impl = underlying_implementation

    def __getattr__(self, name):
        # here you may have to exclude thigs; i.e. forward them to
        # self.name instead for self._impl.name
        try:
            return getattr(self._impl, name)
        except AttributeError:
            # do something else...

bc = BaseClass()
fbc = ForwardBaseClass(bc)
print(fbc.prop_b)
print(fbc.method_c(1,2,c=5))
print(dir(fbc))

note that due to python name mangling you will not be able to access members starting with __ this way.
Comment: This won't work for most `__special__` methods, as those are looked up in slots, and never through `__getattr__`. You might also want to implement `__dir__` to list the wrapped object's attributes.
Comment: I think my previous comment came out more harsh than I had intended it to be. The approach you show is really the best one in general, the questioner's criteria are fairly silly.
Comment: i agree (and have mentioned one of your points already). but as long as there is no reaction from the OP i will not go further with this idea...
Comment: no worries! your comment is absolutely correct and to the point and in no way harsh or offending.
Comment: @Blckknght, I am always astounded that people so boldly state a need to be "fairly silly" just because they cannot think of/foresee one. Let me give you an example - backwards compatibility/regression testing which can be controlled programmatically.


what does exit do in this ruby if fork block

Question: some code like following:
def start
    if fork
        do something
        exit 0
    end
end

fork duplicate a child process,am i right?
But my question is which process does exit 0 really exit?the parent process or child process?
Answer: fork, if given no block, has two different returns. To the parent it returns the process id (PID) of the child. To the child it returns nil which is false.
This is taken advantage of like so:
if fork
    ...this is the parent...
else
    ...this is the child...
end

So your code above forks, the parent does something, then the parent exits and the child lives on.


IDE para desenvolvimento em ionic framework?

Question: Estou procurando uma IDE para desenvolver em Ionic framework. Tentei usar o NetBeans mas não estou conseguindo instalar o plugin IonicExtension, aqui: http://plugins.netbeans.org/plugin/59028/ionicextension
Lendo a documentação do projeto IonicExtension para Netbeans o desenvolvedor apenas diz para clonar o git e adicionar o arquivo IonicExtension no downloaded do netbeans, porem nao existe esse arquivo IonicExtension no projeto.
Qual IDE seria a melhor opção para desenvolver em Ionic Framework ?
Answer: Eu estou utilizando o Visual Studio Community e até o momento está dando conta do recado.
Comment: estou estudando com o Sublime Text 3 ...Para o VS existe plugin para desenvolvimento Ionic ?
Comment: Da pra utilizar o bower para baixar o pacote do Ionic, sem problemas. Além disso, o Visual Studio já possui plugin para o Cordova. Outra ferramenta que passei a utilizar recentemente para criar os protótipos dos meus aplicativos é o [Codepen](http://codepen.io). É bem produtivo.


Java: make constants accessible anywhere

Question: I have a Java program that should read configuration parameters from file, Like this:
java -jar myapp.jar --config config.txt ...

Once loaded, these parameters do not change and should be accessible by any class in the program.
Is it possible to make these parameters accessible from any class without explicitly adding them as parameter to constructors and methods? For example, I would like to be able to do this:
public class Main {

    public static void main(String[] args){

        // This list should be visible by any class
        List<String> CONFIGS= readMyConfigsFromFile(args[0]);
        ...
    }
}

public class MyClass(){
    public MyClass(){
        String thisConf= CONFIGS.get(0); // Do something with this conf param taken from Main.
        ...
    }
}

public class MyOtherClass(){
    public MyOtherClass(){
        String thisConf= CONFIGS.get(0); // Do something with this conf param taken from Main.
        ...
    }
}
...

Is this possible at all? And is it an advisable set up to do? If not, what is the recommended design to go about it?
(I have read similar questions but I'm still unsure if and how it is possible in the situation I described)
Comment: Yes. Make CONFIGS a static, preferrably final, field of a class. https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html. This will make your code harder to unit test, though, and you'd better use dependency injection, or just pass it around in constructors.
Comment: Alternatively you can provide system properties via "java -Dname=value". And then all your classes can use the System to retrieve those values.
Comment: https://www.mkyong.com/java/java-properties-file-examples/
Comment: @Jonathan Portorreal I don't think your link is relevant here. I know how to read the config file. The problem I have is how to make its content visible anywhere.
Comment: You make properties visible anywhere by creating an object (possibly of type `Properties`) and storing a public reference to it in a well-known location, possibly via constructor injection, or in a static member of a configuration class, as others suggested. If the latter perhaps you make it accessible via a public getter method rather than a variable.
Answer: You could use the Singleton pattern.
To model it, I assume you have 2 fields in your configuration: a String and an integer.
public class Config {
    private static Config INSTANCE;

    private final String field1;
    private final int field2;

    public Config(String field1, int field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    public String getField1() {
        return field1;
    }

    public int getField2() {
        return field2;
    }

    public static Config getInstance() {
        if (INSTANCE == null) {
            INSTANCE = loadInstance();
        }
        return INSTANCE;
    }

    private static Config loadInstance() {
        // read your config from properties
        String field1 = ...
        int field2 = ...
        return new Config(field1, field2);
    }
}

And then use Config.getInstance() everywhere you need to get that instance.
Please note that this implementation has a flaw: it may be initialized several times if getInstance() gets called from different theads.
Double-checked locking https://en.wikipedia.org/wiki/Double-checked_locking may be used to overcome this flaw if it is important to you to only initialize once.
Answer: This solution, like others, would require a mock object to unit test. But I think it's best as it encapsulates the arguments in an immutable object.  This also makes thread-safety a non-issue. Use a HashMap instead of an array to access these by key instead of index if you prefer:
 public class Main {

    public static void main(String[] args){

       new CONFIG(readMyConfigsFromFile(args[0]).toArray());
       ...
    }

    public static final class CONFIG {

       private final String[] args;

       private static final CONFIG instance;

       private CONFIG(String[] args) {
           this.args = args;
           instance = this;
       }

       public static CONFIG getInstance() {
          return CONFIG.instance;
       }

       public String[] getArgs(){
           return Arrays.copy(this.args, this.args.length);
       }

       public String getArg(int index) {
          return args[index];
       }

}

To get arguments:
Main.CONFIG.getArgs();

Answer: "Is this possible at all?". Yes, it is. You can easily do it with the help of static in java
public class Config {
private static final List<String> config = new ArrayList<String>();

public static void addConfig(String value){
    config.add(value);
}

public static List<String> getConfig(){
    return config;
}

}
To add values to config you can do
public static void main(String[] args) {
        //Read value from file here in some variable say configValue
        Config.addConfig(configValue);
}

To access config
public class MyOtherClass(){
    public MyOtherClass(){
        Config.getConfig().get(0); // Do something with this conf param taken from Main.
        ...
    }
}

Note above code is not thread safe. You can make it thread safe by adding synchronization concepts
Now "And is it an advisable set up to do?". It depends on your requirements. As you mentioned these values does not change runtime then you can use this. But is the requirement we need to enforce that these values "should not change" once initialized then answer will be different and you should use something like Singleton Pattern and modify to make sure you can only read and not write once the object is constructed. Also note that with static methods, like I suggested, testing becomes really hard.


ExtDoc + @private Properties

Question: I'm using ExtDoc [code.google.com/p/ext-doc/] to generate the Documentation associated to a Javascript Application.
The problem is that when I try to declare a Private Property, that Property will never appear in the generated documentation.
This is the used annotation
<code>/**
* This is a Private Property
* @type String
* @property name
* @private
*/
</code>
Answer: ExtDoc is outdated and no more maintained. Instead use JSDuck, which is the new official docs generator of Ext JS.

ExtDoc + @private Properties


Any way to prevent emacs key bindings to bug in Eclipse?

Question: I'm wondering if I'm the only one struggling (i.e. failing) to keep the emacs key bindings working in Eclipse.
I set them. It works fine. The it stops working fine. Some keys still work, others don't. I find myself in a kind of weird quantum state of uncertain key-binding setup superposition. Some key bindings from the standard set work, some from the emacs set work, some things I can achieve with neither set of bindings.
I'm the only one to experience this? I've seen this on at least 4 computers in the past few months.
I set key bindings back to standard set. Sometimes it works. I use the reset to defaults button. Try to set it back to emacs. Doesn't work. Pressing the apply button between the different steps or not... Drives me crazy.
On some computers, the bindings are just whatever. Can only save using the mouse, C-d and C-k don't work to delete/cut lines, most emacs keys still work but back to C-space for auto-completion, etc.
Anyone knows what can cause this? How to prevent it? Am I pressing some key binding key-bindings by mistake?
Comment: What version of eclipse are you using? I am recently having trouble with it, because the "emacs" scheme randomly gets activated, but i want the default scheme. But i'm still using 3.5...
Comment: Yeah, there's clearly a few big problems with the key binding schemes. I have somewhere between 5 and 10 setups... pretty sure they're all Indigo or Juno. I try to keep up with the versions as much as possible. Didn't notice a difference between versions so far...
Answer: I had a similar problem with the Ctl-K, Ctl-D commands: after doing an upgrade (I forget whether it was Eclipse itself or the Android plugin) I saw Eclipse offering a little pop up menu on both these keys, offering to do either the correct Emacs command or some completely unrelated command. So, for example, Ctl-D offered to either delete the next character (correct) or delete the line (incorrect).
After some poking around in the key bindings (Windows>Preferences>General>Keys), I discovered that sure enough, someons in the Eclipse project supplied these wrong bindings in addition to the correct ones. So I deleted the incorrect bindings and left the correct ones.
So I thought I would be out of the woods at this point. But I also discovered that I had to add the correct binding back in a couple of times before it would stick.
Look for Cut to End of Line under the Command column and make sure it has Ctl-K when Editing Text and in the Text Editing Category. The same for Delete Next (which means next character). But make sure Ctl-D does NOT show up for the Delete Line Command.
Test it out in an editor window; if it fails, go edit the bindings again, test again, repeat until it sticks, making sure you click Apply after editing the bindings.


Make a relationship to last element of a Field Collection

Question: I have a View with a relationship to Field Collection (with unlimited cardinality). I need this relationship to connect only to the last element (having the largest delta). How can I do this?
Comment: Just, FYI, the ability to [reference last delta in views](https://www.drupal.org/node/547732) (and last -n) has been requested before, and I don't think it is possible. Although the issue linked to is old and I suppose something might have changed. Interesting topic regardless. Good luck.
Comment: I'm sure it is possible with custom code but maybe not via the UI. The code may not be trivial though. If it is possible via code then it may also be possible to create a module that does allow users to do it via the UI.
Comment: Wow, there is a 5 year old issue for that!
Answer: In order to show only the Field Collection item having the largest delta, you can use the Field Collection Views module as your formatter (i.e., Views field-collection items) in your View (i.e., parent View). With this formatter you can select another View (i.e., sibling View) to display your field collection items (so you will get a View within a View).
In the parent View you simply specify in the 'Multiple field settings' to display only the last result (i.e., Display 1 value(s), starting from 0, reversed checked), see screenshot below:

Note: in order to output the results in the order that is specified on your node, you have to set a relationship in the sibling View <view_name_for_field_collection> to 'Field collection item: Entity with the {Field Collection field}' and mark it as required. See this issue for the Field Collection Views for an extended explanation.
Let me know if you need any help with this.


Calling class constructor with parameter - request of a member in 'x' which is of non-class type

Question: I have a class A that accepts class B as a constructor parameter. Class B can be constructed from int value. My original code is quite complex, but I hope I've reduced it to the very base case:
class B {
public:
    explicit B(int a) : val(a) {}
private:
    int val;
};

class A {
public:
    A(const B & val) : value(val) {};
    void print() {
        //does nothing
    }

private:
    B value;
};

int main() {
    int someTimeVar = 22;
    A a(B(someTimeVar));
    a.print();
}

And this is the error code I'm getting:
$ g++ test.cpp -Wall -O0
test.cpp: In function 'int main()':
test.cpp:22:7: error: request for member 'print' in 'a', which is of non-class type 'A(B)'
     a.print();
       ^
test.cpp:20:9: warning: unused variable 'someTimeVar' [-Wunused-variable]
     int someTimeVar = 22;
         ^

I use GCC (4.9.2 20150304 (prerelease)), platform: arch linux.
The following modification to the main function compiles fine:
int main() {
    A a(B(22));
    a.print();
}

I'm well aware that using A a(); declares a function, not a object. But I didn't expect that A a(B(some_val)) will do the same, and in my opinion this is what's happening here.
Do you have ideas why this is happening?

Edit: Thank you for all the answers, looks like I need to research more on most vexing parse idea.
BTW it turns out that compiling my code using clang provides more useful error message plus a solution:
$ clang test.cpp
test.cpp:21:8: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
    A a(B(someTimeVar));
       ^~~~~~~~~~~~~~~~
test.cpp:21:9: note: add a pair of parentheses to declare a variable
    A a(B(someTimeVar));
        ^
        (             )
test.cpp:22:6: error: member reference base type 'A (B)' is not a structure or union
    a.print();
    ~^~~~~~
1 warning and 1 error generated.

Comment: Well, your opinion is a fact. `a` is a function.
Answer: A a(B(someTimeVar)) is interpreted as A a(B someTimeVar), so a is a function taking parameter of type B and returning A.
This is one of the reasons the uniform initialization was added to C++11:
A a{B{someTimeVar}};

Answer: This problem has its own tag here on stackoverflow. most-vexing-parse
Wikipedia har a clear description of the problem and its solution. https://en.wikipedia.org/wiki/Most_vexing_parse.

The line
TimeKeeper time_keeper(Timer());

could be disambiguated either as

a variable definition for variable time_keeper of class TimeKeeper, passed an anonymous instance of class Timer or
a function declaration for a function time_keeper which returns an object of type TimeKeeper and has a single (unnamed) parameter which
  is a function returning type Timer (and taking no input). (See
  Function object#In C and C++)

Most programmers expect the first, but the C++ standard requires it to
  be interpreted as the second.

The solution is to add parenthesis to the argument like:
     A a( (B(22)) );

or as others have noted use universal initialization like
     A a { B{22} };

Comment: @kamilm the rule is that if it is syntactically valid as a declaration then it is treated as a declaration.
Comment: _Most programmers expect the first, but the C++ standard requires it to be interpreted as the second._ - For me this is really counter-intuitive - can someone explain the reasoning behind that?
Answer: A a(B(someTimeVar)); declares a function with the return type A and one argument of type B named someTimeVar. It's the same as A a(B someTimeVar);
It works in A a(B(22)); because 22 is not a valid identifier, so the functio declaration would be invalid.
If your codebase uses C++11 (or newer), you can use uniform initialization with curly braces: A a(B{someTimeVar});


how to read nucleotide sequence of a DNAstring

Question: i'm new on R.
I have an assembly genome and I read the stringset
x <- readDNAStringSet("GCA_000146045.2_R64_genomic.fna", format = "fasta")

Then I obtained this
    A DNAStringSet instance of length 16
           width seq                                            enter code here   names
    [1]  230218 CCACACCACACCCACACACCCAC...GGTGTGGGTGTGGTGTGTGTGGG BK006935.2 TPA_in...
    [2]  813184 AAATAGCCCTCATGTACGTCTCC...GTGGGTGTGGTGTGTGGGTGTGT BK006936.2 TPA_in...
    [3]  316620 CCCACACACCACACCCACACCAC...GTGTGGTGGGTGTGGTGTGTGTG BK006937.2 TPA_in...
    [4] 1531933 ACACCACACCCACACCACACCCA...TAAAGGTAGTAAGTAGCTTTTGG BK006938.2 TPA_in...
    [5]  576874 CGTCTCCTCCAAGCCCTGTTGTC...GTTTCATTTTCATTTTTTTTTTT BK006939.2
TPA_in...
...     ... ...
    [12] 1078177 CACACACACACACCACCCACACA...GGAGACGTACATGAGGGCTATTT BK006945.2 TPA_in...
    [13]  924431 CCACACACACACCACACCCACAC...GTGGGTGTGGTGTGTGTGTGGGG BK006946.2 TPA_in...
    [14]  784333 CCGGCTTTCTGACCGAAATTAAA...GTGTGTGTGGGTGTGGTGTGGGT BK006947.3
TPA_in...
     [15] 1091291 ACACCACACCCACACCACACCCA...GAGAGTGTGTGGGTGTGGTGTGT BK006948.2 TPA_in...
     [16]  948066 AAATAGCCCTCATGTACGTCTCC...TTTTTTTTAATTTCGGTCAGAAA BK006949.2 TPA_in...

The next operation that i made was the sorting of the width
 width(x)
[1]  230218  813184  316620 1531933  576874  270161 1090940  562643  439888
[10]  745751  666816 1078177  924431  784333 1091291  948066

 sort(width(x))
[1]  230218  270161  316620  439888  562643  576874  666816  745751  784333
[10]  813184  924431  948066 1078177 1090940 1091291 1531933

Now how can I read the nucleotide sequence in therms of letters of the string 745751? Supposing that I hAVE a bigger genome and I know only the length of a string of my interest but i don't know where it is exactly located whitout sorting, how can I find it?
Answer: Do you mean this?
Extract all DNAStrings inside x that have a width of 745751:
x[width(x) == 745751]

To convert to character
as.character(x[width(x) == 745751])

Here is an example based on some minimal sample data
x <- DNAStringSet(x = c("AGTCTATCTA", "ACTAA", "ATGAA"))

Extract all sequences of length 5:
x[width(x) == 5]
#A DNAStringSet instance of length 2
#    width seq
#[1]     5 ACTAA
#[2]     5 ATGAA

Convert to a character vector
as.character(x[width(x) == 5])
#[1] "ACTAA" "ATGAA"

Comment: I have another problem. How can I check if this sequence has the identical nucleotide sequence of another string of a different string set? I must check if there are differences, I mean, I have to compare x with y but y belongs to another dnastringset from another fasta file. Thank you
Comment: @Su.Doku I'm not entirely clear what you're asking. Are you looking for *identical* sequences in two `DNAStringSet` objects? Or for *similar* sequences? Either way, SO generally favours one question at a time. It might be best to ask your follow up as a new question; also please include reproducible sample data similar to what I do in my post.
Comment: Ok I'll do it. Thank you!


9/8 hybrid vs compound time

Question: I'm just reading about hybrid meters: which combine simple time and compound time.
It seems to me that the time signature 9/8 can have two possible (yet distinct) meanings.
One possibility is that it could represent compound time, with three beats per measure, with a dotted quarter note having one beat.
Another possibility is that it could represent hybrid quadruple time, which would have four beats per measure, with one of the beats containing 3 pulses and the others containing two pulses.
Are these two time signatures related somehow? or are they completely distinct, with the accompanying score being the only clue to figuring out which one you're dealing with?
Answer: These are distinct. One shows it in general by beaming. I have seen some (I think Greek) piano pieces with a 2+2+2+3 rhythm; the eighth notes were beamed as such.
Answer: The second would be an Additive meter of (8+1)/8.

9/8 hybrid vs compound time