Soma de números da direita para a esquerda

Question: Preciso fazer a soma dos dígitos de um número digitado pelo usuário.
Por exemplo:

Se a entrada igual a 20, fazer 2 + 0 = 2
Se a entrada igual a 45, fazer 4 + 5 = 9

Podem ser usados VisualG e C.
Comment: Tentei usar o enquanto. Em VisualG, mas não dá certo. do tipo. Enquanto num%10. Escreva(num), mas esta a dar erro
Comment: Você fez alguma coisa até agora? Precisamos avaliar seu código para poder ajudar!
Comment: Edite a pergunta ([clicando aqui](https://pt.stackoverflow.com/posts/316581/edit) se não souber como) e adicione o código que já fez e até onde tentou
Comment: Só pode ser digitado dois números ou não tem limite?
Comment: Edita sua pergunta ai em cima no botão editar e posta o código... Vou tentar olhar aqui seu código.
Comment: Tu pode manter o input como string e iterar por cada caractere... vai facilitar bastante.
Comment: @MartinDala coloquei a solução, testei ta ok!
Answer: Usa o resto da divisão por 10:
<code>int resto= 20 % 10; //obtem o resto da divisão por 10
int valorSemDireita= 20 / 10; //Como é um inteiro vai retirar o nº da direita
resultado= resto + valorSemDireita;
</code>
Answer: Pressupondo que esse número de entrada possa ser de 0 a várias casas decimais.
A lógica para resolver o problema  seria de individualmente dividir o número por 10 até chegar a 0;
Então o código pode ficar assim:
<code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main()
{
    int a,soma=0,aux;
    printf("Digite um numero:");
    scanf("%d",&a);
    while(a!=0)
    {
        aux=a%10;
        a=a/10;
     soma+=aux;
    }
    printf("\nA soma dos digitos eh:%d",soma);
}
</code>


Interpreting non-orthogonal contrasts R

Question: I'm having trouble finding information on helping me understand how to interpret non-orthogonal contrasts in a regression model.
I have simulated some data to show what I am working with:
set.seed(5552)
Subject <- 1:30
Group <- c(rep("Control", times = 10), rep("Experimental 1", times = 10), rep("Experimental 2", times = 10))
Pre <- round(rnorm(n = Subject, mean = 25, sd = 5), 1)
Post <- c(round(rnorm(n = 10, mean = 25, sd = 5), 1),
            round(rnorm(n = 10, mean = 28, sd = 3),1),
            round(rnorm(n = 10, mean = 33, sd = 4),1))

dat <- data.frame(Group, Subject, Pre, Post)
dat$Diff <- with(dat, Post - Pre)
dat

Model 1: Here is the regression model using the default contrasts in R:
model1.lm <- lm(Diff ~ Group, data = dat)
summary(model1.lm)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)
(Intercept)            0.750      1.960   0.383  0.70495
GroupExperimental 1    3.530      2.772   1.274  0.21365
GroupExperimental 2    8.430      2.772   3.042  0.00519 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

The interpretation here is easy as each coefficient is the difference between that group and the reference (control) group, reflected as the intercept.
Model 2: Now, I change the contrasts to orthogonal:
contrast1 <- c(-2,1,1)
contrast2 <- c(0,1,-1)
contrasts(dat$Group) <- cbind(contrast1, contrast2)

Now re-run the regression model:
model1.lm2 <- lm(Diff ~ Group, data = dat)
summary(model1.lm2)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      4.7367     1.1315   4.186  0.00027 ***
Groupcontrast1   1.9933     0.8001   2.491  0.01917 *
Groupcontrast2  -2.4500     1.3858  -1.768  0.08837 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

Okay, this output makes sense. The intercept now reflects the grand mean. The coefficient for contrast 1 (1.99) is the difference between the pooled mean of the 2 experimental groups and the control group, divided by3. The coefficient for contrast 2 now represents the difference between experimental group 2 and experimental group 3, divided by 2.
Model 3: Now, what if I make the contrasts non-orthogonal. I'll keep the first contrast the same (Control Group vs Both Experimental Groups) and change the second contrast to the Control Group vs Experimental Group 2. Because the Control group is entered back into another contrast, this analysis is non-orthogonal. Here are the contrasts:
contrast1 <- c(-2,1,1)
contrast2 <- c(-1,0,1)
contrasts(dat$Group) <- cbind(contrast1, contrast2)

Now re-run the regression:
model1.lm3 <- lm(Diff ~ Group, data = dat)
summary(model1.lm3)

Call:
lm(formula = Diff ~ Group, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-17.250  -2.958  -0.015   3.743  13.950

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      4.7367     1.1315   4.186  0.00027 ***
Groupcontrast1  -0.4567     1.6002  -0.285  0.77753
Groupcontrast2   4.9000     2.7716   1.768  0.08837 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.197 on 27 degrees of freedom
Multiple R-squared:  0.2569,    Adjusted R-squared:  0.2018
F-statistic: 4.666 on 2 and 27 DF,  p-value: 0.01817

How do I best interpret these non-orthogonal contrasts? The intercept is the same as the orthogonal model, the grand mean. Coefficient 1 has changed yet the contrast is the same as the orthogonal model, it doesn't really make sense to me as to why? I can't make sense of the 2nd coefficient either.
Comment: The interpretation of the contrasts, in relation to the group means, is given by `solve(cbind(1, contrast1, contrast2))`. I'll add a more detailed answer when I have time to do so.
Answer: The $\beta$s can be interpreted as weighted group means. However, the weights are not given by the coding matrix $\mathbf{B}$ that you specified, but by its inverse, namely, the contrast matrix $\mathbf{C} = \mathbf{B}^{-1}$:
    $$\beta = \mathbf{C} \mu = \mathbf{B}^{-1} \mu.$$
You can find details in the vignette of the R package codingMatrices, and I have a blog post about it here.
I'll go through your three models to illustrate the interpretation of the $\beta$s. (Instead of calculating the inverse by hand, I'll use codingMatrices::mean_contrasts(), which is really just a wrapper around solve(cbind(1, B)), but has nicer output.)
Dummy Coding
Looking at $\mathbf{C}$ instead of $\mathbf{B}$ we directly see that $\beta_0=1\mu_1$ (m1), $\beta_1=-1\mu_1+1\mu_2$ (-m1+m2), and $\beta_2=-1\mu_1+1\mu_3$.
(B1 <- contr.treatment(3))
#>   2 3
#> 1 0 0
#> 2 1 0
#> 3 0 1
codingMatrices::mean_contrasts(B1)
#>     m1 m2 m3
#> Ave  1  .  .
#> 2   -1  1  .
#> 3   -1  .  1

Orthogonal Contrasts
Here, $\mathbf{C}$ and $\mathbf{B}$ are structurally so similar that you knew the meaning of the $\beta$s without explicitly knowing $\mathbf{C}$.
(B2 <- cbind(c(-2, 1, 1), c(0, 1, -1)))
#>      [,1] [,2]
#> [1,]   -2    0
#> [2,]    1    1
#> [3,]    1   -1
codingMatrices::mean_contrasts(B2)
#>     m1   m2   m3
#> Ave  1/3  1/3  1/3
#>     -1/3  1/6  1/6
#>        .  1/2 -1/2

Nonorthogonal Contrasts I
Here, $\mathbf{C}$ and $\mathbf{B}$ are structurally completely different. You wanted to compare $\mu_3$ with $\mu_1$ but actually compared it with $\mu_2$ ($9.18 - 4.28 = 4.90$). As you can see, multiplying the contrasts of $\mathbf{C}$ with the group means gives you the $\beta$s.
(B3 <- cbind(c(-2, 1, 1), c(-1, 0, 1)))
#>      [,1] [,2]
#> [1,]   -2   -1
#> [2,]    1    0
#> [3,]    1    1
codingMatrices::mean_contrasts(B3)
#>     m1   m2   m3
#> Ave  1/3  1/3  1/3
#>     -1/3  2/3 -1/3
#>        .   -1    1

(group_means <- tapply(dat$Diff, dat$Group, mean))
#>        Control Experimental 1 Experimental 2
#>           0.75           4.28           9.18
codingMatrices::mean_contrasts(B3) %*% array(group_means, dim = c(3, 1))
#>           [,1]
#> Ave  4.7366667
#>     -0.4566667
#>      4.9000000

model1.lm3 <- lm(Diff ~ Group, data = dat, contrasts = list(Group = B3))
coef(model1.lm3)
#> (Intercept)      Group1      Group2
#>   4.7366667  -0.4566667   4.9000000

Nonorthogonal Contrasts II
We can use this the other way round and specify a matrix $\mathbf{C}$ to to compare $\mu_3$ with $\mu_1$. Then, we use its inverse as input to lm(), and this will give you the desired result, namely the difference between group 3 and group 1 which is $9.18 - 0.75 = 8.43$.
(C4 <- rbind(1/3, c(-1, 0.5, 0.5), c(-1, 0, 1)))
#>            [,1]      [,2]      [,3]
#> [1,]  0.3333333 0.3333333 0.3333333
#> [2,] -1.0000000 0.5000000 0.5000000
#> [3,] -1.0000000 0.0000000 1.0000000
solve(C4)
#>      [,1]       [,2] [,3]
#> [1,]    1 -0.6666667    0
#> [2,]    1  1.3333333   -1
#> [3,]    1 -0.6666667    1

model1.lm4 <- lm(Diff ~ Group, data = dat,
                 contrasts = list(Group = solve(C4)[, -1]))
coef(model1.lm4)
#> (Intercept)      Group1      Group2
#>    4.736667    5.980000    8.430000

In summary, if you want to know how to interpret the estimated $\beta$s, you have to look at the inverse of your design/coding matrix. It may be obvious for standard schemes (e.g., dummy) or for orthogonal contrasts, but definitely not for non-standard non-orthongonal coding schemes.

Interpreting non-orthogonal contrasts R


Should I use odds ratio or risk ratio?

Question: I am doing a retrospective cohort study with sample size 600 and disease prevalence rate greater than 10%. I am leaning more towards using risk ratio because it is easier to interpret and because disease prevalence is over 10%. Do you have any thoughts on this matter?
Also, if possible can someone briefly explain the differences between odds ratio and risk ratio? A specific and brief example would be helpful.
Thanks in advance.
Comment: Probably the best place for this question is this: http://stats.stackexchange.com/
Answer: Odds ratio and relative risk are two measures used to describe the likelihood of an event happening. The odds ratio is defined as the ratio of the odds of an event or disease occurring in one group to the odds occurring in another group. The standard formula is $[X/(1-X)]/[Y/(1-Y)]$, where $X$ and $Y$ are the probability of that event in the two groups, respectively. In contrast, the relative risk is the risk of an event or disease relative to exposure. The standard formula is $A/B$.
For your study, I would strongly suggest to use the risk ratio. A general rule is that when the prevalence of the disease is <10%, the relative risk and the odds ratio tend to be very similar, so that for rare diseases both indexes  can be used nearly in an interchangeable manner. On the other hand, for diseases with relatively high prevalences, the odds ratio is considerably different from the relative risk. In particular, it overstates the real effect: the odds ratio is smaller than the relative risk for odds ratios <1 (for example, it could lead to an overestimation of the beneficial effect of a pharmacological agent for the prevention of a disase), and larger than the relative risk for odds ratios >1 (e.g. it could lead to an overestimation of the real effect of a factor in increasing the risk of a disease). Also note that the magnitude of this overestimation increases as both the initial risk (prevalence of the disease) increases and the odds ratio departs from 1.
Lastly, we have to take into account that odds (unlike risks) are rather difficult to understand, particularly for readers that are not particularly trained in statistics. The risk of an event is a very simple concept: it is the ratio between the number of subjects who experience the event and the total number of subjects at risk. It is classically expressed as a proportion ranging between 0 and 1 or between 0 and 100%. In contrast, the odds of an event is the ratio between the number of subjects who experience the event and those who do not. It ranges from zero to infinity, and is clearly less intuitive. For instance, a relative risk of 70% corresponds to an odds ratio of 0.7/(1-0.7)=2.33: however, it is clearer to say to the layman that a certain risk factor "increases the probability of a disease by 70%" (relative risk) rather than that it "increases the probability of the disease by an odds ratio of 2.33".
Comment: OR and RR do not describe the likelihood of an event any more than the slope of a linear regression describes the mean response. It's a second moment estimator, a contrast, between groups.
Answer: In a two by two table of exposure $X$ versus response $Y$,
\begin{array}{c|cc}
& Y & \bar{Y} \\ \hline
X & a & b \\
\bar{X} & c & d \\
\end{array}
The odds ratio is calculated as $ad/bc$ whereas the risk ratio is $a(c+d)/(c(a+b))$.

For hypothesis testing, if the OR > 1 then the RR > 1 and the likelihood ratio test for the logistic model is the uniformly most powerful test.
The prevalence of the outcome only matters for using the OR as an approximation to the RR - the approximation is good when the outcome is rare, VERY rare. It's best just to report an OR as an OR always.
Either modeling approach provides the chance to predict response probabilities across a range of exposures. Without this, I argue an OR or an RR on their own mean very little. Some reviewers demand also to see the risk difference as yet another contrast.

Should I use odds ratio or risk ratio?


Tricky Schwarz Lemma Type Qualifying Exam Question

Question: I have a question from a past complex analysis qualifying exam that I would like some help on. Let $f(z)$ be an analytic function on the unit disk $\mathbb{D}$ such that $\lvert f(z)\rvert \leq 1$. Suppose that $z_1,z_2,...,z_n\in \mathbb{D}$ are zeroes of $f(z)$.
Show that
\begin{align}\lvert f(0)\rvert \leq \prod_{j=1}^n \lvert z_j\rvert,\end{align}
where each $z_j$ is repeated in the product on the right hand side corresponding to its multiplicity. For instance, if $z_1$ has multiplicity 3, then we would see $\lvert z_1\rvert^3$ on the right hand side.
This is what I have so far. Suppose that $f(z_j)=0$ with an order of $m_j\geq 1$. Letting $g_j:= f\circ \psi_j$, where $\psi_j$ is the FLT $\psi_j(z)=\frac{z+z_j}{1+\overline{z_j}z}$, we have that $g$ is analytic on $\mathbb{D}$ with a zero of order $m_i$ at $z=0$ and satisfies $\lvert g(z)\rvert \leq 1$. Thus, $\lvert g(z)\rvert \leq \lvert z\rvert ^{m_j}$ by the Schwarz Lemma, and in particular $\lvert g(-z_j)\rvert = \lvert f(0)\rvert \leq \lvert z_j\rvert^{m_j}$. However, I don't know how to combine this over all of the $z_j$ to get the desired inequality.
Comment: Not  a good idea to use $i$ for a running index in Complex Analysis!
Comment: I replaced the $i$'s with $j$'s.
Answer: Hint: Use induction on $n$. Let $\phi_j (z)=\frac  {z-z_j}{1-\overline {z_j}z} =\psi_j^{-1}(z)$ and consider $\frac {f{(z)}} {\phi_1(z)....\phi_{n-1}(z)}$. Use MMP to show that this is bounded in  modulus by $1$.
Comment: @MSA2016 Don't be so negative. Be patient. I wish you al the best in your exam.
Comment: (MMP = maximum modulus principle)
Comment: I don't see how I would ever come up with that. No chance I pass this exam.
Comment: Ok I think I see what's happening. It's enough to just do it for $n=1$ since $k(z):=\frac{f(z)}{\phi_1(z)\phi_2(z)...\phi_{n-1}(z)}$ has only a simple zero at $z=z_n$.


Silverlight nested RadGridView SelectedItem DataContext

Question: I'm developing a Silverlight 4 app and am using the 2010 Q1 release 1 RadGridView.  I'm developing this app using the MVVM pattern and trying to keep my codebehind to a minimum.
On my View I have a RadGridView and this binds to a property on my ViewModel.  I am setting a property via the SelectedItem.  I have a nested RadGridView and I want to set a property on my ViewModel to the SelectedItem but I cannot.  I think the DataContext of my nested grid is the element in the parent's bound collection, rather than my ViewModel.  I can easily use codebehind to set my ViewModel property from the SelectionChanged event on the nested grid, but I'd rather not do this.  I have tried to use my viewModelName in the ElementName in my nested grid to specify that for SelectedItem, the ViewModel is the DataContext, but I cannot get this to work.  Any ideas?
Here is my Xaml:
<grid:RadGridView
                    x:Name="master"
                    ItemsSource="{Binding EntityClassList, Mode=TwoWay}"
                    SelectedItem="{Binding SelectedEntityClass, Mode=TwoWay}"
                    AutoGenerateColumns="False"
                    >

                <grid:RadGridView.Columns>
                    <grid:GridViewSelectColumn></grid:GridViewSelectColumn>
                    <grid:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description"/.
                </grid:RadGridView.Columns>

                <grid:RadGridView.RowDetailsTemplate>
                    <DataTemplate>
                        <grid:RadGridView
                            x:Name="child"
                            ItemsSource="{Binding EntityDetails, Mode=TwoWay}"
                          /* Note: SelectedItem here is not setting my property in my ViewModel*/
                            SelectedItem="{Binding DataContext.SelectedEntityDetail, ElementName='RequestView', Mode=TwoWay}"
                            AutoGenerateColumns="False"
                            >
                                <grid:RadGridView.Columns>
                                    <grid:GridViewSelectColumn></grid:GridViewSelectColumn>
                                    <grid:GridViewDataColumn DataMemberBinding="{Binding ServiceItem}" Header="Service Item" />
                                    <grid:GridViewDataColumn DataMemberBinding="{Binding Comment}" Header="Comments" />
                                </grid:RadGridView.Columns>
                        </grid:RadGridView>
                    </DataTemplate>
                </grid:RadGridView.RowDetailsTemplate>

            </grid:RadGridView>

Answer: Looks like you are on the right track, if your "SelectedEntityDetail" prop on your VM is at the same level as "SelectedEntityClass"
Try binding at the same level as you "master" grid or soemthing above in the tree "LayoutRoot" etc.. as I only guess what requestView is.
SelectedItem="{Binding ElementName=master, Path=DataContext.SelectedEntityDetail}"
Comment: Yes, "SelectedEntityDetail" and "SelectedEntityClass" are at the same level in my VM.  "requestView" is the xName of my View, so what I was trying to do was set the ElementName to the root of the View so I have access to the original View DataContext.  This kind of syntax works in WPF as far as I know but I can't seem to get it in Silverlight.  Binding to master as you have suggested also doesn't work.
Answer: Have been in contact with Telerik support and they tell me that this is a framework limitation.  They have suggested a workaround using an attached behaviour.  So far I've stuck with the small piece of codebehind


How to know if a vector is in a region created by 2 tangential line from one end of the vector to a circle?

Question:
My question will be clearer looking at the picture.
The dash area is the area I want to know if the vector is inside of it or not. With the picture drawn out, the question seems to be trivial but I want to have a mathematical answer. My end goal is to have this problem solve through programming.
Let:
-The circle O(xc, yc) has a radius of R.
-The vector u(a,b) with the starting point of (xu, yu)
Comment: You need to specify what is given. Also, there are a lot of vectors that are equal to the one in the picture but have a different starting point. Do you care about that?
Comment: @Vasya Thanks for the comment. I'm trying to have a general answer for an arbitrary vector and arbitrary circle in XY plan. I have added some more details in the question.
Comment: Is it $\mathbf u$ that you wish to test? Is $(x_u,y_u)$ the cone's apes?
Comment: @amd Yes, **u** is the vector I want to test and $(x_u, y_u)$ is the pointy end.
Answer:
Because triangles OAP and OBP are right,
$$x^2+R^2=OP^2, \mbox{or} $$
$$x=\sqrt{OP^2-R^2}$$
From properties of right triangles:
$$\frac{x}{OP}=\cos\frac{\alpha}{2},$$
where $\alpha$ denotes the angle BPA. Then
$$\cos\frac{\alpha}{2}=\frac{\sqrt{OP^2-R^2}}{OP^2}$$
Because triangles BPO and APO have a side equal to R and share the side OP, then BPO and APO are identical and therefore OP cuts $\alpha$ into two equal angles $\frac{\alpha}{2}$.
Now plot an arbitrary vector $\vec{PC}$ (the coordinates of C are assumed known). The vectors
$$\frac{\vec{PC}}{PC} \mbox{  and  } \frac{\vec{PO}}{PO}$$
are unit vectors.
Then
$$\frac{\vec{PC}}{PC} \cdot \frac{\vec{PO}}{PO}=\cos\gamma.$$
If $\vec{PC}$ is between the two tangents,
$$\cos\gamma \ge \cos\frac{\alpha}{2},$$
because $\gamma \le \frac{\alpha}{2}$.
Therefore the condition for an arbitrary vector $\vec{PC}$ drawn from P and ending in C, to be between the two tangents, is
$$\frac{\vec{PC}}{PC} \cdot \frac{\vec{PO}}{PO} \ge \frac{\sqrt{OP^2-R^2}}{OP^2}$$.
To ensure the vector does not cross the circle, add these two conditions:
$$OC \ge R$$
and $PC \le PA$, that is
$$PC \le \sqrt{OP^2-R^2}$$
Comment: Good job, beautiful equation, easy to program. I haven't check out the math yet but looks good so far.


Unresolved symbol: sql::mysql::get_driver_instance(void)

Question: I have a program that uses MySQL connector to talk to a MySQL database.  The application runs fine using Visual Studio 2008.  I'm trying to get the application to build with Visual Studio 2010 and that's where the problems began.
The MySQL Connector 1.05 is not supported with VS 2010, and they don't have a binary version of 1.1.0 that works with VS 2010.  The MySQL information says to download the source for Connector C++ 1.10 and build with VS 2010.  After much work, I build it.  The examples run.
However, when I build my application with the newly built Connector C++ 1.1.0, I get the following error message:
error LNK2019: unresolved external symbol "class sql::mysql::MySQL_Driver * __cdecl sql::mysql::get_driver_instance(void)" (?get_driver_instance@mysql@sql@@YAPAVMySQL_Driver@12@XZ) referenced in function "private: void __thiscall Database_NS::Manager::initialize_db_driver(void)const " (?initialize_db_driver@Manager@Database_NS@@ABEXXZ)

This is caused by the following source line:
sql::Driver * p_driver = sql::mysql::get_driver_instance();

The MySQL Connector C++ 1.1.0 examples use the above line and they get no errors.
I've tried linking with mysqlconn-static.lib, mysqlconn.lib, mysqlclient.lib, libmysql.lib and still the error message persists.
An interesting point is that according to VS 2010, the above source line uses this declaration:
CPPCONN_PUBLIC_FUNC MySQL_Driver * get_driver_instance();

Note the different return values.
When I use Visual Studio 2010 and the connector project example, VS 2010 can't find the declaration or function declaration of get_driver_instance() used by connect.cpp.  The statement in my program is the exact statement used by connect.cpp, since I copied it over without any changes.
Other people have resolved this issue by using another driver.  However, I don't want to change my code that works with VS2008 unless I have to.
Another reply to this issue says to define "mysqlcppconn_EXPORTS", but this didn't work either, also reported in the comment to the reply.
Here are my questions:
1.  Has anybody got MySQL Connector 1.1.0 to work with Visual Studio 2010?
   If so, please reply with step by step example and indicate whether dll or static library.
2.  How is the VS compiler selecting the get_driver_instance() function that returns    MySQL_Driver * rather than the function that returns the Driver *?
    I'm not even getting any warnings or errors about ambiguous functions (since overloading must differ by more than only return type).
I am using Visual Studio 2010 on Windows-7x64-bit, MySQL Connector C++ 1.1.0.
See also:
get_driver_instance() crashes with Qt
undefined reference to 'get_driver_instance'
MySQL C++ Connector: undefined reference to `get_driver_instance'
mysql-connector-c++ - 'get_driver_instance' is not a member of 'sql::mysql'
How to fix unresolved external symbol due to MySql Connector C++?
Answer: Some function names have changed.  My best solution is to differentiate between them by using preprocessor conditionals.
Answer: I too have the same problem, I keep getting:
*sampletest.obj : error LNK2001: unresolved external symbol __imp__get_driver_instance*

Although I tried a 32 bit connector and the issue was resolved (you may want to try that as, if you are lucky it may work for you), but I was using a 64bit mysql,windows 7 , so there was a bit of compatibility issue .. I am still searching for the solution for the above problem.
Followed the tutorials word by word , linked all libraries
I think the C++ 1.10 connector might have some issue.
Comment: I finally used an "#ifdef" statement between OS / Compiler versions.  The MySQL connector has function names changed.


Refactoring into ReactiveCocoa

Question: So I have just recently started with ReactiveCocoa, and I figured the best way to learn would be just to jump right in and start refactoring some existing code that I have. I was wanting to get some critique and make sure I am heading in the right direction.
So in the app I am refactoring, I have a ton of code that goes like this:
[self.ff getArrayFromUri:@"/States?sort=name asc" onComplete:^(NSError *theErr, id theObj, NSHTTPURLResponse *theResponse) {
    if(!theErr) {
       //do something with theObj
    }
    else {
       //handle the error
    }
}];

I currently have this refactored in ReactiveCocoa like so:
-(void)viewDidLoad {
 //ReactiveCocoa
RACCommand *command = [RACCommand command];
RACSubject *subject = [RACSubject subject];
[[[command addSignalBlock:^RACSignal *(id value) {
    NSError *err;
    NSArray *array = [self.ff getArrayFromUri:@"/States" error:&err];
    err ? [subject sendError:err] : [subject sendNext:array];
    return [RACSignal empty];
}]switchToLatest]deliverOn:[RACScheduler mainThreadScheduler]];

[subject subscribeNext:^(NSArray *x) {
    [self performSegueWithIdentifier:kSomeSegue sender:x];
} error:^(NSError *error) {
    NSLog(@"the error = %@", error.localizedDescription);
}];

self.doNotLocation = [UIButton buttonWithType:UIButtonTypeCustom];
[self.doNotLocation setBackgroundImage:[UIImage imageNamed:@"BlackButton_small.png"] forState:UIControlStateNormal];
[[self.doNotLocation rac_signalForControlEvents:UIControlEventTouchUpInside] executeCommand:command];
RAC(self.doNotLocation.enabled) = RACAbleWithStart(command, canExecute);
RAC([UIApplication sharedApplication],networkActivityIndicatorVisible) = RACAbleWithStart(command, executing);    }

Is this about how I should be going about it, using the RACSubject, or is there a better way? This whole concept is new to me, as my only programming languages thus far have been Java and Objective-C, so this functional reactive way of thinking is throwing me off a bit.
Answer: Unfortunately, there are a couple problems with the code sample you presented:

The block passed to -addSignalBlock: is returning an empty signal. That should be a warning flag, since there are almost never junk return values. In this case, it means that the block performs its work synchronously. To avoid blocking the main thread, you should create a signal which does that work asynchronously, and return it.
The -switchToLatest and -deliverOn: are not doing anything. Most signal operators only do work when the resulting signal is subscribed to. In this case, it just disappears into the aether.

We can solve both of these problems at once. -addSignalBlock: returns a signal of the signals returned in the block. If we return something meaningful, it can be handled outside of that method.
First of all, this needs to be added to the top:
@weakify(self);

When @strongify(self) is used below, it will prevent a retain cycle. This is necessary because the RACCommand lives as long as self.
Now, the creation of the inner signals:
RACSignal *requestSignals = [command addSignalBlock:^(id value) {
    return [RACSignal start:^(BOOL *success, NSError **err) {
        @strongify(self);

        NSArray *array = [self.ff getArrayFromUri:@"/States" error:err];
        *success = (array != nil);

        return array;
    }];
}];

Within the block, this simply creates a signal which will invoke -getArrayFromUri:error: and pass back its results or an error, if one occurred. +start: will ensure that the work happens in the background.
Out of all of this, we get requestSignals, which is a signal of those created signals. This can completely replace the RACSubject used originally:
RACSignal *arrays = [[[requestSignals
    map:^(RACSignal *request) {
        return [request catch:^(NSError *error) {
            NSLog(@"the error = %@", error);
            return [RACSignal empty];
        }];
    }]
    flatten]
    deliverOn:RACScheduler.mainThreadScheduler];

First, we transform each inner signal to log, then ignore, errors. (It's a little complicated, but a RAC operator might be added to do it in the future.)
Then we flatten the signal of signals. The result, arrays, is a signal that passes through the values of all the inner signals. This is why we had to ignore errors – if any of them reached this point, we would stop getting all values from the inner signals, forever.
Finally, we "lift" the selector to invoke:
[self rac_liftSelector:@selector(performSegueWithIdentifier:sender:) withObjects:kSomeSegue, arrays];

This will resend -performSegueWithIdentifier:sender: whenever arrays sends a new value (which will be an NSArray returned from the network). You can think of it like invoking a method over time. This is better than a subscription because it simplifies side effects and memory management.
Comment: Thanks for the reply, I do appreciate it. I am getting one problem with your provided code, in the second to last sample. `[request catch:]`  is saying that it needs to return a `RACSignal` and not void. Am I just missing something there?
Comment: Ah, sorry, you're completely right. You can just return `[RACSignal empty]` (to indicate that the error signal should be replaced with an immediately-successful one). I'll update my answer.
Comment: Ok, so I have everything updated, and it is working, except I get a substantial delay (about 3 second) and also it seems to be blocking the main thread (all user interaction is non responsive) from the time I tap the button to when `prepareForSegue:sender:` gets called. However, if I do `RACSignal starWithScheduler:block` and pass in `[RACScheduler mainThreadScheduler]` for the scheduler, it executes as I would expect. So what am I missing here? Honestly, this stuff makes me feel like an idiot, maybe I should go back to "Haskell for pre-K" before I tackle this stuff.
Comment: @terrylewis Are you using the latest version of the code above (with `+start:` inside the signal block)? I also added a `-deliverOn:` to the flattened signal, to make sure that the segue is performed on the main thread. Sorry about all of the complexity! Commands are generally more complicated to use and understand than the rest of the framework.
Comment: Yeah, I had the latest version of the code. Here is a gist of what I currently have that is working, [link](https://gist.github.com/tLewisII/5667301)
Comment: @terrylewis What happens if you replace `RACScheduler.mainThreadScheduler` with `[RACScheduler scheduler]`?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30795/discussion-between-terry-lewis-and-justin-spahr-summers)
Comment: `[RACScheduler scheduler]` gives me the same problems as before. `+start:` is just a convenience method for `startWithScheduler:block:` that uses `[RACScheduler scheduler]` for the scheduler.
Comment: @terrylewis Can you please [file an issue](https://github.com/ReactiveCocoa/ReactiveCocoa/issues)? The behavior you're running into is quite unexpected. Running on the main thread should result in more blocking than running on a background scheduler, so it's not clear to me what could be happening.
Answer: In my experience with the framework, I've found that there's very little reason to use RACSubject directly, especially for one-off signals like this.  RACSubjects represent mutable signals, which you do not need in this case, and can actually increase the complexity of your code.  It would be far better for you to return a vanilla signal (through +[RACSignal createSignal:]) inside that command block, then have the resulting request code make up the body of the signal:
[[[command addSignalBlock:^RACSignal *(id value) {
    //
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        //Request code here
            return nil;
    }];
}]switchToLatest]deliverOn:[RACScheduler mainThreadScheduler]];

Or, better still, you can refactor getArrayFromUri:error: to return a signal and get rid of that ternary statement:
 [[[command addSignalBlock:^RACSignal *(id value) {
     return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        //...
        [[self getArrayFromUri:@"/States"]subscribeError:^(NSError *error) {
            [subscriber sendError:error];
        } completed:^{
            [subscriber sendNext:array];
        }];
            return nil;
        }];
  }]switchToLatest]deliverOn:RACScheduler.mainThreadScheduler];

As for the problem of the subscription on the next line, those can be considered side effects of the signal, so we can make them explicitly so with the corresponding variants of do: applied to the signal for the command:
    [[[command addSignalBlock:^RACSignal *(id value) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [[[[self getArrayFromUri:@"/States"]doError:^(NSError *error) {
                NSLog(@"the error = %@", error.localizedDescription);
                [subscriber sendError:err];
            }] doNext:^(NSArray *array) {
                [subscriber sendNext:array];
                [self performSegueWithIdentifier:kSomeSegue sender:array];
            }] subscribeCompleted:^{
                [subscriber sendCompleted];
            }];
            return [RACDisposable disposableWithBlock:^{
                 // Cleanup
            }];
        }];
    }]switchToLatest]deliverOn:[RACScheduler mainThreadScheduler]];

Finally, because commands work a differently from signals, the outermost operators will not be evaluated (thanks, @jspahrsummers), so you can remove them.
[command addSignalBlock:^RACSignal *(id value) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                [[[[self getArrayFromUri:@"/States"]doError:^(NSError *error) {
                    NSLog(@"the error = %@", error.localizedDescription);
                    [subscriber sendError:err];
                }] doNext:^(NSArray *array) {
                    [subscriber sendNext:array];
                    [self performSegueWithIdentifier:kSomeSegue sender:array];
                }] subscribeCompleted:^{
                    [subscriber sendCompleted];
                }];
                return [RACDisposable disposableWithBlock:^{
                     // Cleanup
                }];
            }];
        }];

Comment: Unfortunately, I cannot refactor `getArrayFromUri:error` as it is a third party framework and I only have access to the headers. I did however switch everything to the way you have it, and it does work just the same. Learning this feels like starting from the beginning all over again almost.
Comment: Yeah, the framework certainly does have a painfully steep learning curve, but once you get around to learning how it works, it's really powerful.
Comment: @CodaFi `switchToLatest]deliverOn:[RACScheduler mainThreadScheduler]]` is a no-op in all of the samples you've provided, since no subscription occurs afterward. Same with your `-do…` methods.
Comment: Yes, I understand (probably should iterated that in the body of the post).
Comment: In the `do` case for your final code sample, I mean that _the network request will never fire_, because there's no subscription there.
Comment: Yes, so I'll change that to `subscribeCompleted:` and move the side effects into that

Refactoring into ReactiveCocoa


given a series of stock prices in an array. Pick when to buy and when to sell to gain max profit

Question: given a series of stock prices in an array. Pick when to buy and when to sell to gain max profit.
from one website i got something like this-ef maxprofit(prices):

buydate, selldate = 0, 0
maxprof = 0 minprice = prices[0] mindate = 0
for d, p in enumerate(prices[1:]): if p < minprice: minprice = p
  mindate = d + 1 continue
prof = p - minprice
if prof > maxprof: maxprof = prof buydate, selldate = mindate, d + 1
return (buydate, selldate), maxprof

but i think..we should consider negative prices too..isn't? any other solution or comments are most welcome
Answer: Since you have the history and there appears to be no penalty for a transaction, simply take the derivative of the prices and buy when d/dx goes from negative to positive and sell when it goes from positive to negative.
This way you are buying before every gain and selling before every loss.
Answer: Ideally you want to buy stocks when they're at their lowest and sell when they're highest. So figure out where the peaks and the troughs are in your data and those are your sell and buy points, respectively.
This is as simple as going through the data set, looking at two adjacent points at a time, and keeping track of the current "trend" (whether or not the market is going up or down). If the trend was going up and the price fell, then you should sell on the day before it fell. On the other hand, if the trend was going down and the price rose, you should buy on the day before it rose.
Comment: to be precise you want to know where *every* peek and *every* trough is which is really just looking first derivative.
Comment: Right. I hesitate to use the word derivative in non-continuous situations but yes :)
Comment: good point. In my engineering mind I filled the gaps and ran a numerical method on the data.
Answer: This is a code in java for the above problem which calculates the max profit
<code>class Solution {
public int solution(int[] a) {

    if(a==null || a.length==0 || a.length==1)
    {
        return 0;
    }
    int buyDay=0;
    int sellDay=0;
    int profit=0;
    for(int i=1;i<a.length;i++)
    {
    int diff=0;

        if(a[buyDay]>a[i])
        {
            buyDay=i;

        }
        else if(a[sellDay]<a[i])
        {
            sellDay=i;
        }

        if(sellDay<buyDay)
            sellDay=buyDay;
        diff=a[sellDay]-a[buyDay];
        if(diff>profit)
        {
            profit=diff;
        }

    }
    return profit;

}
}
</code>


Prove that $\frac{3}{4}<\int_{0}^{1} x^x dx <\frac{85}{108}.$

Question: Let $I=\int_{0}^{1} x^x dx$, the function $f(x)=x^x$ attains a local minimum at $x=e^{-1}$ and $f''(x)>0, \forall x\in (0, \infty).$ So $f(x)>e^{-e^{-1}}\approx 0.69.$ Next, one may choose a point $x=1/2$, the chords in $x \in (0,1/2)$ and in $x \in (1/2,1)$ lie above the curve $y=f(x)$ due to its positive definite curvature. So, $I$ will be less than the area under these two identical trapeziums, we get $I<\frac{2+\sqrt{2}} {4}\approx 0.85,$ whereas $I=0.787....$ Hoever, in the process of finding better bounds on $I$, I found that
$$\frac{3}{4}<\int_{0}^{1} x^x dx <\frac{85}{108}.$$
I hope that you will find it interesting to prove this result.
Comment: What is the question ? It seems more like a proposed exercise, but that's not the point of posts.
Answer: According to Sophomore's dream we have
$$
I = \int_{0}^{1} x^x dx = \sum_{n=1}^\infty (-1)^{n+1}n^{-n} = 1 - \frac{1}{2^2} +\frac{1}{3^3} - \frac{1}{4^4} +- \ldots \, .
$$
That is an alternating series and the absolute values of the elements are decreasing, so that the value of the series lies between consecutive partial sums.
In particular,
$$
\underbrace{1 - \frac{1}{2^2}}_{3/4}  < I < \underbrace{1 - \frac{1}{2^2} +\frac{1}{3^3}}_{85/108}
$$

One can also mimic the proof of Sophomore's dream: For $0 < x < 1$ is
$$
 x^x = e^{x \log x} = \sum_{n=0}^\infty \frac{(x \log x)^n}{n!}
$$
an alternating series  whose absolute values are decreasing, so that
$$
 1 + x \log x < x^x < 1 + x \log x + \frac 12 (x \log x)^2
$$
Integrating these inequalities gives the desired estimate.


Como alterar um arquivo HTML por outro?

Question: Tenho os arquivos:

h1.html
h2.html
start.html

Start.html:
<frameset cols='20%, *'>
<frame src='h1.html' name='menu'>
<frame src='h2.html' name='resto'>
</frameset>

Gostaria de saber de que maneira posso alterar, por exemplo, um texto do arquivo h1.html utilizando um botão no arquivo h2.html.
Comment: Tu pode passar a variável por post e o texto será a variável recebido caso ela exista, vc faz isso usando o php e o html
Comment: Por que está utilizando `frame` e `frameset`? Ps.: Ambos estão deprecado.
Comment: @Valdemir sou iniciante, mas fazer o que estou em um mesmo html será cansativo e desorganizado. Woton Sampaio dê um exemplo, nunca usei php xD
Comment: @Raptador Realmente não estou conseguindo nem com o `contentDocument`, o navegador está bloqueando o acesso, removi a resposta enquanto procuro uma solução :) Uma dúvida. Você utiliza jQuery?
Comment: tenho importado, mas não sei utilizar sozinho, se tiver um código pronto agradeço.
Answer: Vamos supor para o seu exemplo a seguinte estrutura:
start.html
   h1.html (iframe menu)
       function alterarInput()...
   h2.html (iframe resto)
       <input id="input1" />

Em qualquer dos iframes, você pode acessar a página parent (start) com Javascript, e em seguida qualquer elemento da página parent, incluindo os iframes. Então, no exemplo que coloquei na function que está no iframe menu, vamos acessar o input do iframe resto assim:
function alterarInput() {
   parent.resto.document.getElementById('input1').value= 'novo valor';
}

Obs.: evite usar iframes, eles estão obsoletos e as permissões de alguns navegadores podem fazer com que não funcionem. Se precisar usar arquivos separados existem outras alternativas mais modernas.
Comment: creio q o código teria funcionado, o navegador bloqueou o frame de acessar o outro pois tem origem "cross-origin". se existir alguma maneira de definir a origem do arquivo funcionaria
Comment: sim, o código funciona, mas no seu caso não será possível mesmo, restrições de segurança do browser. De qualquer forma, usar `iframe` já é algo obsoleto, e ainda de domínios diferentes? Definitivamente não é uma boa prática

Como alterar um arquivo HTML por outro?


Freq. Response of Discrete System

Question: Let's say that I have the following continuous system:
$$G(s)= \frac{2}{1+s}$$
I could convert it to a discrete system using for example the Tustin approximation https://en.wikipedia.org/wiki/Bilinear_transform
So I replace s with:
$$s \rightarrow{}  \frac{2(1-z^{-1})}{T_e(1+z^{-1})} $$
Hence I get the approx. discrete transfer function:
$$G(z)= \frac{2}{1+\frac{2(1-z^{-1})}{T_e(1+z^{-1})}}$$
Now my question is, how can I compute its frequency response ?
In the end, I would like to be able to compare the discrete approx. freqe. response with the  freq. response of the continuous original transfer function.
Answer: Given
$$
\left|H(j\omega)\right| = \left|G(j\omega)\right|=\frac{2}{\sqrt{\omega^2+1}}
$$
from $G'(z)$ we can obtain $G'(j\omega)$ by considering the transformation associated to the sampling phenomena
$$
z = e^{-j\omega T}
$$
hence
$$
G'(z) = \frac{2 T (z+1)}{(T+2) z+T-2}\to G'(j\omega) = \frac{2 T \left(1+e^{i \omega  T}\right)}{(T+2) e^{i \omega  T}+T-2}
$$
and
$$
\left| H'(j\omega)\right| = \sqrt{\frac{4 T^2 (\cos (\omega  T)+1)}{\left(T^2-4\right) \cos (\omega  T)+T^2+4}}
$$
Attached the comparison between $|H'|$ (red) and $|H|$ (blue) for $T = 1$

and also $\angle{H}$,$\angle{H'}$
Comment: Wow ! Thank you very much ! Your answer is perfect !! One can clearly see the approximation as the red and the blue curve do not completely overlap for the magnitude plot. I know that one can replace z with $z = e^{-j\omega T}$ but I have never quiet understood why... Do you know why?
Comment: Nicely illustrated. +1

Freq. Response of Discrete System


What is the effect of "Conglomerising" your percussion?

Question: When writing music, I use a program called Fruity Loops.
Of the music that I write that has percussion, some of them are written with all the percussion instruments being grouped into one pattern. This has the advantage that you can see where all the beats are in relation to the beats of the other instruments.
The rest of my music involves writing separate patterns for each instrument. This has the advantage that I can move the combinations about to do things like breifly offset the hi-hats to make it feel "disjointed" or something.
My question is this. When writing music, in what ways could it conceivably affect the way you compose, having all the drums on one pattern versus having them on many?
For bonus points, suggest a compromise with a reason.
Answer: I suppose it depends on how you're thinking about your instruments and what you need for your piece.
If you put them together, you'll conceive of the music for them as a singular unit. If you separate them, you'll likely think of each instrument as a more independent entity. The effect here is how you envision your percussion to function: is it just to provide a simple backing, or are you going to be writing incredibly complex parts for each instrument that requires they be independent?
Since I primarily write acoustic music, I think of the people performing what I write. Your questions is similar to: all instruments on a staff, or multiple staves?
So for me, because I deal with people (though I have a lot of work that uses electronics, and I myself also use FL Studio for some of my work), separating instruments also serves a practical / logistical function:
If I group my instruments together, I need to think about how much time it takes for the player to actually play each instrument, to switch between them, to switch mallets, and the coordination of playing multiple instruments simultaneously. I also need to think about choosing instruments that aren't too difficult to find or are a pain to lug around. If I separate the instruments out, then I need more percussionists, which costs more $$.
Since you're primarily electronic, you have a couple different considerations: your own workflow. Before FL Studio created that thing where you can see other patterns on the piano roll, it was a nightmare for me to bounce between instruments because I couldn't see all the music at the same time. So the advantage to grouping there is that you can see everything at once.
Moral of the story, ask yourself these two questions: "What does my piece need?" and "What do I need?"
Answer: What you describe will be common for those who prefer using drumsynths instead of samples.  However, if you are using TR-XYX emulators or similarly developed drumsynths, a prefered method is to build many distinct patterns which include all of the triggers for the drumsynths.  This is done to replicate the programming that was done on the original synthesisers and the intention is to create a drum style that was popular in the 1980s and 1990s.
One reason why you might want to separate them is if you want to do some syncopating, or delaying a particular drum behind or before the beat, especially if you are using drumsynths and therefore have to use two instances.  The reason you would use two instances instead of relying on MIDI signals is if you wanted a particular delay measured in milliseconds (like say 40 ms).
With samples, I found grouping them was important and to collect all the ideas for specific groups, it was important to break it down into many patterns for each group.  It is simply an organisation habit that I have.  You might not have that habit which is perfectly okay.
Comment: I usually group them myself. I just wanted to word the question as unbiasedly as I could.
Answer: Whenever I write unpitched percussion parts, I almost never put all of them on one pattern. If my DAW came with only unpitched percussion soundfonts that sounded like several percussion instruments being played at once, I'd quickly find other percussion soundfonts (for single instruments) and use them instead.
In short, I generally reject composing with all the drums on one pattern.
(I have put the snare drum, the bass kick pedal drum, and a cymbal on the same pattern before for 4-bar phrases, but that was for some pretty distinctive parts of one of my compositions.)
Comment: I think that by pattern, OP means a rhythm made from several instruments interacting, not unison playing on many instruments, maybe this was the source of confusion. The question is as far as i can tell about how to write rhythms in a DAW, if you should put each instrument on separate tracks, or all percussion on one track.
Comment: This doesn't answer the question. For a complete answer, at least tell us why you do it that way.
Comment: Alright, my percussion-writing style is hugely influenced by my exposure to real percussion instruments, especially the immersive exposure I got by playing in school concert bands (and looking back at the percussion players). It's also influenced by all the times I've watched drummers of bands. In both cases, people strongly do not tend to play 4 or more percussion instruments in unison. I don't find sticking several percussion instruments on the same pattern to be realistic, which is why I avoid it at nearly all costs.
Comment: Ye Dawg is correct. A pattern is a drumloop featuring multiple drums at different times.
Comment: When I looked up FL Studio definitions of a pattern, all the unpitched percussion ones I found were for one instrument only and seemed to support only one music channel each.


Arrays' Length exploding when appending Values to it from CSV

Question: below is some code written to open a CSV file. Its values are stored like this:
03/05/2017 09:40:19,21.2,35.0
03/05/2017 09:40:27,21.2,35.0
03/05/2017 09:40:38,21.1,35.0
03/05/2017 09:40:48,21.1,35.0

This is just a snippet of code I use in a real time plotting program, which fully works but the fact that the array is getting so big is unclean. Normally new values get added to the CSV while the program is running and the length of the arrays is very high. Is there a way to not have exploding arrays like this?
Just run the program, you will have to make a CSV with those values too and you will see my problem.
from datetime import datetime
import time

y = []    #temperature
t = []    #time object
h = []    #humidity

def readfile():
 readFile = open('document.csv', 'r')
 sepFile = readFile.read().split('\n')
 readFile.close()
 for idx, plotPair in enumerate(sepFile):
     if plotPair in '. ':
         # skip. or space
         continue
     if idx > 1:  # to skip the first line
         xAndY = plotPair.split(',')
         time_string = xAndY[0]
         time_string1 = datetime.strptime(time_string, '%d/%m/%Y %H:%M:%S')

         t.append(time_string1)
         y.append(float(xAndY[1]))
         h.append(float(xAndY[2]))
         print([y])

while True:

    readfile()
    time.sleep(2)

This is the output I get:
[[21.1]]
[[21.1, 21.1]]
[[21.1, 21.1, 21.1]]
[[21.1, 21.1, 21.1, 21.1]]
[[21.1, 21.1, 21.1, 21.1, 21.1]]

Any help is appreciated.
Comment: you can use collections.deque with maxlength and append data to it.
Comment: Your appeding a list inside a while True loop. You can declare your lists inside readFile method or use insert instead of append
Answer: You can use Python's deque if you also want to limit the total number of entries you wish to keep. It produces a list which features a maximum length. Once the list is full, any new entries push the oldest entry off the start.
The reason your list is growing is that you need to re-read your file up to the point of you last entry before continuing to add new entries. Assuming your timestamps are unique, you could use takewhile() to help you do this, which reads entries until a condition is met.
from itertools import takewhile
from collections import deque
from datetime import datetime
import csv
import time

max_length = 1000     # keep this many entries

t = deque(maxlen=max_length) # time object
y = deque(maxlen=max_length) # temperature
h = deque(maxlen=max_length) # humidity

def read_file():
    with open('document.csv', newline='') as f_input:
        csv_input = csv.reader(f_input)
        header = next(csv_input)    # skip over the header line

        # If there are existing entries, read until the last read item is found again
        if len(t):
            list(takewhile(lambda row: datetime.strptime(row[0], '%d/%m/%Y %H:%M:%S') != t[-1], csv_input))

        for row in csv_input:
            print(row)
            t.append(datetime.strptime(row[0], '%d/%m/%Y %H:%M:%S'))
            y.append(float(row[1]))
            h.append(float(row[2]))

while True:
    read_file()
    print(t)
    time.sleep(1)

Also, it is easier to work with the entries using Python's built in csv library to read each of the values into a list for each row. As you have a header row, read this in using next() before starting the loop.


Minimum of the Gamma function

Question: Working on one of other question Show the inequality $\frac{\sqrt{\pi}}{2}<\left(\pi-e\right)!$ I found :
$$\frac{\left(\pi-e+\frac{1}{2}\right)}{2}\simeq x_{min}=0.4616\cdots$$
Where $x_{min}$ verify $f'(x_{min})=0$ of $f(x)=x!$ for $x>0$
Now I refine it to get :
$$\frac{\left(\pi-e+\frac{1}{2}\right)}{2}-\frac{2\left(\pi^{2}-e^{2}\right)^{e+\pi}}{\left(\pi^{2}+e^{2}\right)^{e+\pi}}\simeq x_{min}$$
Edit after Tyma Gaidash comment :
We have a better result with :
$$x_{min}\simeq\frac{\left(\pi-e+0.5\right)}{2}-2\frac{\left(\pi^{2}-e^{2}\right)^{\left(\pi+e\right)}}{\left(\pi^{2}+e^{2}\right)^{\left(\pi+e\right)}}+\frac{\left(\pi^{3}-e^{3}\right)^{\frac{7}{4}\left(\pi+e\right)}}{\left(\pi^{3}+e^{3}\right)^{\frac{7}{4}\left(\pi+e\right)}}-\frac{\left(\pi^{4}-e^{4}\right)^{2\left(\pi+e\right)}}{\left(\pi^{4}+e^{4}\right)^{2\left(\pi+e\right)}}+\frac{\left(\pi^{5}-e^{5}\right)^{\frac{13}{5}\left(\pi+e\right)}}{\left(\pi^{5}+e^{5}\right)^{\frac{13}{5}\left(\pi+e\right)}}-\frac{\left(\pi^{6}-e^{6}\right)^{\frac{18}{5}\left(\pi+e\right)}}{\left(\pi^{6}+e^{6}\right)^{\frac{18}{5}\left(\pi+e\right)}}$$
We can continue but it converge very slowly .
Is it the beginning of something like a power series or can we find something like $$\frac{\left(\pi-e+\frac{1}{2}\right)}{2}+\sum_{n=2}^{\infty}\frac{a_{n\ }\left(\pi^{n}-e^{n}\right)^{b_{n}\left(e+\pi\right)}}{\left(\pi^{n}+e^{n}\right)^{b_{n}\left(e+\pi\right)}}=x_{min}$$ where $a_n,b_n$ are rational. How to explain that ?
Comment: See also the value $$\left(\pi-e+0.5\right)\cdot\frac{1}{2}-2\left(\frac{\left(\pi^{2}-e^{2}\right)}{\pi^{2}+e^{2}}\right)^{\left(\pi+e\right)}-\left(\frac{\left(\pi^{3}-e^{3}\right)}{\pi^{3}+e^{3}}\right)^{\left(\frac{7}{4}\left(\pi+e\right)\right)}$$
Comment: I want to says that $a_n,b_n$ can be negative .
Comment: Can you give a few more terms, 4 maybe, than the part directly after "Now I redefine to get:"?
Comment: @TymaGaidash Thanks for the edit ,let me the time to do that .
Comment: It might be just a coincidence, however, I would advise you to look at [link](https://en.wikipedia.org/wiki/Lagrange_inversion_theorem). Inverting the digamma function might give you interesting series expansions for $x_{min}$.
Answer: Let
$$f_n(a_n)=\left(\frac{\pi ^n-e^n}{\pi ^n+e^n}\right)^{a_n(e+\pi ) }$$
$$\frac{1}{2}\left(\pi-e+\frac{1}{2} \right)-2 f_2(1)-f_3\left(\frac{7}{4}\right)-f_4\left(\frac{5}{2}\right)+f_5\left(3\right)+$$ $$f_6\left(\frac{7}{2}\right)-f_7\left(\frac{17}{4}\right)+f_8\left(6\right)+f_9\left(7\right)-f_{10}\left(\frac{35}{4}\right)-f_{11}\left(\frac{23}{2}\right)+f_{12}\left(14\right)$$ gives
$\color{red}{0.4616321449}82$ to be compared to
$\color{red}{0.461632144968}$
Comment: Perhaps you mean $f_{n}(a)$ in the first line?
Comment: @TianVlašić. Thanks for pointing it !
Answer: Like Claude Leibovici's answer we have :
Let :
$$f\left(x\right)=x!$$
And :
$$h(x)=f'(x)$$
Then set :
$$A=\frac{\left(\pi-e+0.5\right)}{2}-2\frac{\left(\pi^{2}-e^{2}\right)^{\left(\pi+e\right)}}{\left(\pi^{2}+e^{2}\right)^{\left(\pi+e\right)}}+\frac{\left(\pi^{3}-e^{3}\right)^{\frac{7}{4}\left(\pi+e\right)}}{\left(\pi^{3}+e^{3}\right)^{\frac{7}{4}\left(\pi+e\right)}}-\frac{\left(\pi^{4}-e^{4}\right)^{2\left(\pi+e\right)}}{\left(\pi^{4}+e^{4}\right)^{2\left(\pi+e\right)}}+\frac{\left(\pi^{5}-e^{5}\right)^{\frac{13}{5}\left(\pi+e\right)}}{\left(\pi^{5}+e^{5}\right)^{\frac{13}{5}\left(\pi+e\right)}}-\frac{5}{4}\frac{\left(\pi^{6}-e^{6}\right)^{\frac{18}{5}\left(\pi+e\right)}}{\left(\pi^{6}+e^{6}\right)^{\frac{18}{5}\left(\pi+e\right)}}+\frac{6}{5}\frac{\left(\pi^{7}-e^{7}\right)^{\frac{19}{4}\left(\pi+e\right)}}{\left(\pi^{7}+e^{7}\right)^{\frac{19}{4}\left(\pi+e\right)}}-\frac{251}{200}\frac{\left(\pi^{8}-e^{8}\right)^{\frac{31}{5}\left(\pi+e\right)}}{\left(\pi^{8}+e^{8}\right)^{\frac{31}{5}\left(\pi+e\right)}}+\frac{\left(\pi^{9}-e^{9}\right)^{\frac{48}{5}\left(\pi+e\right)}}{\left(\pi^{9}+e^{9}\right)^{\frac{48}{5}\left(\pi+e\right)}}-\frac{\left(\pi^{10}-e^{10}\right)^{\frac{52}{5}\left(\pi+e\right)}}{\left(\pi^{10}+e^{10}\right)^{\frac{52}{5}\left(\pi+e\right)}}$$
Then a numerical approximation gives :
$$|h(A)|<4* 10^{-15}$$
We have $A=0.461632144968\cdots$

Minimum of the Gamma function


Can I debug a program with LLDB-MI via Eclipse?

Question: It seems that LLDB plugin for Eclipse is still not developed yet, but this article claims that one can debug a program with LLDB-MI driver in Linux. However described way of integrating Eclipse and LLDB doesn't work for me (I always get "command --exec-continue not recognized" error message) and it looks suspicious that embedding LLDB-MI to Eclipse may be so easy.
Could anyone point me to curren materials on this topic? Google shows me only old Eclipse-bug-tracking threads.
Answer: There is a project called lldbmi2 that provides most of the functionality one would need.  I know it's been developed primarily for the Mac and I don't know if it's been tested on Linux.  It's not perfect, but I've been using it on the Mac for months and I'm pleased with its functionality.
See https://github.com/freedib/lldbmi2


Unable to create folder in class library in asp.net.

Question: I have a web application that include a reference which will create a new folder when the reference's method is called.
However i have an error when my application call the method.
<code>Access to the path 'TempPDFStorage/' is denied.
</code>
I try the same thing in windows form. It have no issue and the new folder will be created in the bin/debug/
What should i do??
Answer: Are you trying to access this path on the client machine or server?  If you have rights to IIS you can impersonate a user for your application that has rights to that directory and you should be fine then.
To set the security context of a user with permissions:

Open up IIS Manager (Run -> "inetmgr")
Locate your web application
Click on your web application and on the right side click "Basic Settings..."
Click "Connect as..."
Select "Specific User"
Click "Set..."
Enter the credentials of the user with permissions to that directory

Conversely, to impersonate as an unauthenticated user you can do this:

Follow the above steps 1 and 2
On the Features View double click "Authentication"
Depending on how you have authentication set up you can configure the "Anonymous" to use specific credentials (by default it is set to IUSR)
Comment: on server. so what should i do?
Comment: @DEN check out my Edit on my post.  That should allow you to modify the context of your user.
Comment: can't proceed after step 2. after i click on the web application, it only show me the folder and aspx file. it doesn't have Basic Settings
Comment: @DEN do you not see the "Actions" section on the right side?  What version of IIS are you running?
Comment: dear @shark , http://images.static-webwiz.co.uk/kb/asp-tutorials/images/installing_iis_winXP_iis_console.gif the image link is similar with my inetmgr. check it out
Comment: unfortunately,it doesn't state what version of my IIS is. but the os is microsoft server 2003
Comment: Click on "Help" -> "About IIS..." or something along those lines to get the version.
Comment: ya. i did. it just show me "Internet Information Services(IIS) Manager Microsoft Corporation"
Comment: @DEN maybe you can try something like this: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/4ec9116c-7ca2-4126-9dc4-b7f82b67cd76.mspx?mfr=true
Comment: i have read the article and set  , but the result is just the same. I guess i have to go for another alternative of accessing the folder.
Comment: @DEN Set it in full.  You need to provide credentials in your `` tag.  Like so: ``
Comment: thanks for your solution. However, it will b better if i just create the folder using AppDomain.CurrentDomain.BaseDirectory . I will mark your question. Thank you very much!
Answer: A web application is normaly only executed on the server and has with standard settings no write privilages on a desktop. A winform executes on the desktop. I think what you want to do is not a very good praktice for security.
Comment: so what's the better practise for this? since i need to create a new folder when calling the method of the reference.


Dry Suit Shorts: Do they exist?

Question: Is it possible to purchase dry shorts/bottoms that keep the water out in a similar way that a dry suit does?
Thank you!
Answer: As far as I know they don't exist.
First of all because of the constructional borders: How would you build them? When you think about it, normal shorts end up around your knees. The problem is that your muscles aren't that static in their shape, so how would you prevent the water from flowing in?
Secondly, dry-suits are made for cold water and for diving for a longer time below 10°C. So it wouldn't make any sense to construct one as shorts.
Comment: While I doubt they exist and they would likely be impractical,  it should be possible to make them. Latex seals could be used, just placed on the biceps and thighs.
Answer: You could theoretically get semi-dry shorts but not full dry. I've never seen any though. By the time you're on shorts you might as well go for neoprene and accept that you're getting wet.
Answer: It does not exists, and even if it did, it would probably be one of the worst items to dive with, as you would have a floating air bubble that would make you float feets first. You would have trouble keeping your buoyancy to neutral, and risk breathlessness for trying too much.
Comment: This answer is not off topic as it describes another reason why the asked item does not exists. It does not break any rule found at https://sports.stackexchange.com/help/deleted-answers. Moreover, this answer brings forward a serious safety concern with the equipement seeked, I find important to point it out.

Dry Suit Shorts: Do they exist?


Mixed models with R - convert from SAS code

Question: I have this SAS code running a mixed model:
proc mixed data = Data;
  class Treatment SubjectID Technique;
  model Time = Treatment;
  random Technique;
  random SubjectID(Technique);
  lsmeans Treatment / cl pdiff=control('New') adjust=dunnett;
run;

I want to run this analysis in R, what is the equivalent R code ?
Thank you !
(I find the R code for mixed models to be extremely confusing).
Comment: To my knowledge, ```lme``` and ```proc mixed``` use completely different methods, especially if you would write ```type=UN``` in the random statement.
Comment: So you are saying there is no way to get the same results in both SAS and R ? It makes no sense, how would I know which one is better than ?
Comment: There are plenty of variance component procedures for mixed models, MINQUE, MIVQUE0, REML, ANOVA etc. Rao wrote some books about this. You can change them by the ```method``` option in the ```proc mixed``` statement. I hope someone else knows more regarding R.
Comment: SAS is using REML by defualt
Comment: I don't understand why you have a first random effect as Technique is also part of your second.
Answer: I believe the equivalent R code, using the lme package, would be:
res <- lme(Time ~ factor(Treatment), random = ~ 1 | Technique/SubjectID, data=Data)

As for the lsmeans part, you should check the lsmeans package.


Remove every object inside the array

Question: I'm trying to delete all matched items from an array but it leaves Always one item in it.
var item1 = {item: "item1"},
    array = [{
        item: "item1"},{
        item: "item_non"},{
        item: "item1"},{
        item: "item_non"},{
        item: "item1"},{
        item: "item1"},{
        item: "item1"},{
        item: "item_non"},{
        item: "item_non"
    }];
array.forEach(function(items){
    if(item1.item === items.item){
        var index = array.indexOf(items);
        if(index !== -1){
            array.splice(index,1);
        }
    }
});

I also fiddle it, it deletes only 4/5 items that matches instead of 5/5.
Fiddle
There is no option to use Array#filter I need to delete the objects.
Comment: Modifying the array while iterating via `.forEach()` is the fundamental problem. The right way to do this is with `.filter()` or with a simple `for` loop. If you *think* you can't use `.filter()`, you should explain why.
Comment: When you remove an item, you change following indexes. You can fix it by iterating backwards.
Comment: Related: http://stackoverflow.com/questions/25994909/difference-between-foreach-and-for-loop-in-javascript
Answer: The problem is that .splice() moves all the elements after the deleted element down. So if you delete element 3, element 4 becomes 3, 5, becomes 4, and so on. The next iteration of the loop will process element 4, but that's the original element 5 -- the original element 4 is skipped.
The way to solve this is to process the array in reverse. .forEach can't do this, AFAIK, so you have to use a for loop:
for (var i = array.length - 1; i >= 0; i--) {
    item = array[i];
    if (item1.item == item.item) {
        array.splice(i, 1);
    }
}

Comment: I hope the guy asking the question realizes this is the right answer for what he is asking..
Answer: Here's another version that does in-place manipulation of the array.
http://codepen.io/anon/pen/XmZrww?editors=001
// remove the matching item and return the array
var filterArray = function (arr, obj) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (arr[i].item === obj.item) {
      arr.splice(i, 1);
      len--;
      i--;
    }
  }
  return arr;
};

var item1 = {item: "item1"};
var data = [
  {item: "item1"},
  {item: "item_non"},
  {item: "item1"},
  {item: "item_non"},
  {item: "item1"},
  {item: "item1"},
  {item: "item1"},
  {item: "item_non"},
  {item: "item_non"}
];

console.log(filterArray(data, item1));

Comment: You're initializing `i` to `0`, and then doing `i--`. So it will then try to test `arr[-1]`, which doesn't exist.
Comment: Oh, I see. You decrement `i` inside the loop, then the `for()` increments it back.
Comment: Yeah but your answer is the more succinct way to do this. Upvoted
Answer: Here's my version http://codepen.io/anon/pen/VvQZVe?editors=001
Note I cleaned up the code a bit.
Repeatedly using indexOf in a loop is expensive. The worst case for doing that in a big array is having to go to almost the end of the loop many times.
This version potentially uses almost 2x the memory (imagine a big array where there's only a single item to be removed). But, its faster.
// indexOf is expensive, especially in a loop.
// here we just iterate straight through the array and append
// mismatching properties to another array that gets returned.
var filterArray = function (arr, obj) {
  var returnArray = [];

  arr.forEach(function (el) {
    if (el.item !== obj.item) {
      returnArray.push(el);
    }
  });

  return returnArray;
};

var item1 = {item: "item1"};
var data = [
  {item: "item1"},
  {item: "item_non"},
  {item: "item1"},
  {item: "item_non"},
  {item: "item1"},
  {item: "item1"},
  {item: "item1"},
  {item: "item_non"},
  {item: "item_non"}
];

console.log(filterArray(data, item1));

Comment: Your `filterArray` function is equivalent to `Array.prototype.filter`, which he said won't work for him.
Comment: He said he can't use Array.filter. He doesn't say anything about not being able to use a function that does something like a polyfill.
Comment: He said "I need to delete the objects". I think that means that he needs to keep the same array, not create a new array like `filter` does.

Remove every object inside the array


What is the baseline model in structural equation modeling analysis, what it may look like?

Question: I am reading (also learning) a paper using structural equation modeling (SEM) as their analysis method. Their analysis was constructed by using a correlation matrix and asymptotic variances. They follow the two-step method (Anderson and Gerbing, 1988) with the baseline model being constructed first to confirm the stability of the latent variables. I am still confused about the term "baseline model" here. The author proposed a causal model (all paths), which is later examined. However, I cannot find they defined "baseline model". What is the baseline model here?
Thanks
Answer: There are a few definitions of baseline model. Typically, it's also the null model, which contains no parameters (except means and variances). It's (just about) the worst model you could have.  But that can get more complicated: https://www.researchgate.net/publication/10764067_On_Specifying_the_Null_Model_for_Incremental_Fit_Indices_in_Structural_Equation_Modeling (you probably don't need to worry about that).
It's a long time since I've read that paper, but IIRC, they might also be talking about the structural baseline model, which is the model with all of the measurement parameters estimated, but the structural parts (relationships between the latents - both regression and correlation) constrained to zero.
That paper is pretty old, and the way that things are thought about has changed somewhat (e.g. people now put measured variables into the structural model, which wasn't possible in 1988, without some hacks).
Perhaps describe what the problem is that you are trying to solve with the baseline model?
Comment: Thanks so much for your reply. The paper is Vance, D. E., Roenker, D. L., Cissell, G. M., Edwards, J. D., Wadley, V. G., & Ball, K. K. (2006). Predictors of driving exposure and avoidance in a field study of older drivers from the state of Maryland. Accident Analysis & Prevention, 38(4), 823-831. https://doi.org/10.1016/j.aap.2006.02.008.
Comment: The study examined age, gender, health, cognitive as predictors of driving avoidance, and driving exposure. They used SEM as the analysis model, health, cognitive, and physical are latent variables measured by various tests or questionnaires.  They said that they followed the two-step SEM method, started with a baseline model. However, I have no idea what is the baseline model, what the "baseline model" referred to. All they preposed or presented is their casual model. The purpose of the baseline model is to "check the validity of the latent variables", as stated in the paper.
Comment: I don't have access to the paper.
Comment: Sorry about the paper, but I think I have described clearly. The baseline model is for checking the validity of the latent variables, no specific problem included, it is the first step of the routine two-step SEM (Anderson and Gerbing, 1988). Thanks for your reply.
Comment: The first step in the A&G approach is a saturated structural model. This is not (usually) called a baseline model. A baseline model is (usually) a null model, with no parameters. See. e.g. https://stats.idre.ucla.edu/stata/faq/what-are-the-saturated-and-baseline-models-in-sem/ This is why I'm confused.


tela de loading aparece so o ícone sobre o conteúdo

Question: minha tela de loading aparece só o icone sobre o conteúdo da tela inicial. quero adicionar uma cor solida ao fundo que desaparece junto com o icone quando o site carregar. como adiciono?

css:
.load {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 40%;
    left: 45%;
  }

Answer: Pra isso acontecer você precisa fazer com que a classe .load esteja com width:100% e height:100vh. e com isso vc define a cor e a opacidade do fundo e a imagem centralizada.

.load {
  width: 100%;
  height: 100vh;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.2);
  transition: 5s;
}

.load img {
  margin-top: 50%;
  width: 200px
}

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


An Argument of Function Date has wrong data type or result is too small or too large Error

Question: Getting the error

An Argument of Function Date has wrong data type or result is too small or too large

when the following measure is included in any graph. However, the Value is shown properly in KPI.
LastYear =
VAR lastFromDate =
    DATE ( YEAR ( [From_Date] ) - 1, MONTH ( [From_Date] ), DAY ( [From_Date] ) )
VAR lastToDate =
    DATE ( YEAR ( [To_Date] ) - 1, MONTH ( [To_Date] ), DAY ( [To_Date] ) )
RETURN
    IF (
        [DateDiff] > 365,
        0,
        SUMX (
            FILTER (
                ALL ( WUSA_CAL_DIM ),
                WUSA_CAL_DIM[End_Date] >= lastFromDate
                    && WUSA_CAL_DIM[End_Date] <= lastToDate
            ),
            [Sales_Value]
        )
    )

I want to show last year sales based on from and to date in the slicer. Removing -1 solves the problem but it doesn't show previous year sales in that case which is needed.
Answer: I think this has to do with a lack of context around the [From_Date] and [To_Date] in your Variables. However, without access to your source data and not knowing anything about your datamodel due to lack of context I'm making huge assumptions here.
PowerBI ( or rather the DAX ) has no idea which set of dates you want it to use.
Attempt something like:
LastYear =
VAR lastFromDate =
    SELECTEDVALUE(From_Tbl[From_Date], TODAY()) - 365
VAR lastToDate =
    SELECTEDVALUE(To_Tbl[To_Date], TODAY()) - 365
RETURN
    IF (
        [DateDiff] > 365,
        0,
        SUMX (
            FILTER (
                ALL ( WUSA_CAL_DIM ),
                WUSA_CAL_DIM[End_Date] >= lastFromDate
                    && WUSA_CAL_DIM[End_Date] <= lastToDate
            ),
            [Sales_Value]
        )
    )

Comment: Just watch out for leap years if you're doing -365 days.
Answer: I came across this issue today, its late but, It has to do with Blank dates present somewhere in the column.
In this Instance,
DATE ( YEAR ( [From_Date] ) - 1, MONTH ( [From_Date] ), DAY ( [From_Date] ) )
if From_Date is BLANK, it is one of the reason for the error.
Suggested Alternative,
IF( ISBLANK([From_Date]), BLANK(), DATE ( YEAR ( [From_Date] ) - 1, MONTH ( [From_Date] ), DAY ( [From_Date] ) ))
Answer: The simple solution for that is to understand are you applying -1 (day before) to the day or to the full date (yyyy,mm,dd) or just to the day (dd).
For Example: If you are applying -1 to the day and the today is 1st of the month it througn an error as it try to find 1-1 with no date reference where if you apply end of the date that work absolutely fine even for the 1st of the month.
If you want to get last 12 months dates
Correct solution is -
VAR Days = CALENDAR(DATE(YEAR(TODAY())-1,MONTH(TODAY())-1,DAY(TODAY())),DATE(YEAR(TODAY()),MONTH(TODAY()),DAY(TODAY())))

If you want get the last year same date + 1 day before
VAR Days = CALENDAR(DATE(YEAR(TODAY())-1,MONTH(TODAY())-1,DAY(TODAY()))-1,DATE(YEAR(TODAY()),MONTH(TODAY()),DAY(TODAY())))

However this give you an error if you add -1 after the day shown below
Wrong approach this thrown an error date is too small or too large
VAR Days = CALENDAR(DATE(YEAR(TODAY())-1,MONTH(TODAY())-1,DAY(TODAY())-1),DATE(YEAR(TODAY()),MONTH(TODAY()),DAY(TODAY())))


Generate js variable before javascript loaded

Question: I have a block with invocation code inside(it invokes js code from OpenX ads server), my site is responsive and this block get cloned(with jquery .clone() function) on ipad or iphone version of the site. So to avoid calling the invocation js code 2 times i need to set js variable (like this - > window.isScriptLoaded = FALSE) and then inside my block i can easy do next thing:
if (window.isScriptLoaded == FALSE) {
    window.isScriptLoaded = TRUE;
    //invocation code...
}

in this case all working fine, i can easy add this variable to any js file in drupal.
But in my case admin can add new block and insert new invocation code - SO I need to generate window.isScriptLoaded2 and output this variable BEFORE code in block is loaded
i tried next thing
function HOOK_page_alter(&$page) {
  //get all the variables
  //i generate my variables in database
  $var = db_query("SELECT * FROM {banners}")->fetchAll();
     $full_array = array();
     foreach($var as $object) {
         //for example Anyvariable = FALSE;
         $array[$object->name] = $object->value;
     }
      drupal_add_js(array('common' => array(
    'vars' => $array,
    )), 'setting');

}

this works but, code in block is loaded before drupal.settings.vars.Anyvariable is loaded.
So my variables is always false
Answer: It is also hard to say if this will work without seeing exactly what you need to do, but you may want to play with the scope, group, and weight options for drupal_add_js().  These may help you get the order that you need.  From the docs

The exact ordering of JavaScript is as follows:

First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by
  the theme.
Then by group.
Then by the 'every_page' flag, with TRUE coming before FALSE.
Then by weight.
Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js()
  that happened later in the page request gets added to the page after
  one for which drupal_add_js() happened earlier in the page request.

When I have been in similar situations, I implement a template_preprocess_html(), create some markup, stuff it into $variables, and then output this before the print $scripts in html.tpl.php  I have to use this in some very specific situations where I need to output JS very early in the  before CSS and JS is loaded.
Comment: oh my god, this task is pissed me off, thank you (^_^;) i generated variable in `preprocess_html` and used it before `$scripts` ITS `TRUE` u made my day <3


IOAT enabled but not being used with Linux?

Question: On our R610s with igb version 4.1.2 I do see the ioatdma module loading (and loaded with lsmod):
ioatdma: Intel(R) QuickData Technology Driver 4.00
ioatdma 0000:00:16.0: irq 80 for MSI/MSI-X
ioatdma 0000:00:16.1: irq 81 for MSI/MSI-X
ioatdma 0000:00:16.2: irq 82 for MSI/MSI-X
ioatdma 0000:00:16.3: irq 83 for MSI/MSI-X
ioatdma 0000:00:16.4: irq 84 for MSI/MSI-X
ioatdma 0000:00:16.5: irq 85 for MSI/MSI-X
ioatdma 0000:00:16.6: irq 86 for MSI/MSI-X
ioatdma 0000:00:16.7: irq 87 for MSI/MSI-X

We have a quad port Intel nic that should support it:
07:00.0 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
07:00.1 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
08:00.0 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
08:00.1 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)

However, it looks like it isn't being used for any network traffic:
[root@or-rtlb01 ~]# cat /sys/class/dma/dma*/bytes*
0
0
0
0
0
0
0
0

Does anyone know how to make it so ioat is used for network traffic?
Kernel is Linux or-rtlb01.ds.stackexchange.com 3.7.7-1.el6.elrepo.x86_64 #1 SMP Mon Feb 11 22:28:07 EST 2013 x86_64 x86_64 x86_64 GNU/Linux
Comment: Does the motherboard chipset have support for IOAT? Is IOAT turned on in the system BIOS? Do you see "Intel(R) I/OAT DMA Engine found" in dmesg? This would indicate a NIC which supports IOAT has been located. Do you see "DCA is disabled in BIOS" in dmesg? This would indicate no BIOS support or enablement for DCA.
Comment: Right, as guys stated what does "dmesg |grep DCA" show?
Comment: redhat 6 right?
Comment: @mdpc: CentOS 6.3, tried a much newer kernel to see if it would help, but it didn't. This was a secondary issue discovered when having high si% on ksoftirqd with ipsec traffic (not that I expect offloading on the ipsec traffic itself, but would seems there is no ioatdma at all.
Comment: When I last asked Dell (several years ago) they said the R610 BIOS does not support DCA nor do they have plans to add support for it.
Answer: How big are the packets you're sending through?  By default the IOATDMA driver is only used on large packet sizes.  You can view the current setting with:
cat /proc/sys/net/ipv4/tcp_dma_copybreak

If you want the value to be lower, you can set it using sysctl.  For example, to set the packet size to 1, use:
sysctl net.ipv4.tcp_dma_copybreak=1

Answer: Before starting, update complete server like BIOS including hard drive firmware.
Secondly, always use latest Intel Network Driver igb. Just compile it from the source.
BIOS enable both DCA and IOATDMA. In linux try this:
# modprobe ioatdma
# dmesg
You should see the ioatdma driver loaded.
Now, the igb driver is different to ixgbe which is 10GBps one. Since I dont use igb at all, I can tell you to try to stop network /etc/init.d/network stop and rmmod igb and modprobe igb again to see if there are any differences and post results if you can pls.


Drush not working properly on Ubuntu

Question: I am using Ubuntu 14.04 . When I try to download, enable, disable any module drush gives the following error:
Additional uncaught exception thrown while handling exception.OriginalDrupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).Drupal::getContainer()
drupal8_bootstrap(0)
_drush_bootstrap_drupal_configuration()
drush_bootstrap(3, 7)
drush_bootstrap_max()
drush_bootstrap_to_phase(-2)
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
drush_main()
AdditionalDrupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).Drupal::getContainer()
Drupal::theme()
_drupal_log_error(Array, 1)
_drupal_exception_handler(Object)
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Comment: Trying to get more info: Are you accessing drush from the root folder? Does Drush respond to other commands such as `drush --version`? Can you post the command that produces that output (and give the folder location).
Comment: Any command from anywhere is the drupal folder gives the same result.
Comment: At this point I'm placing bets on @greg_1_anderson response. D8 moves fast. APIs change. The drush version may be off. I'm going to advise on using a Dev VM that has Drupal 8 installed along with proper dependencies. That *greatly* reduces the headache of D8 development -- at least right now. Best of luck.
Comment: Just another potential helpful article: Install Drush 7 for Drupal 8 without throwing away Drush 6 http://x-team.com/2015/02/install-drush-drupal-8
Answer: Sounds like you are not using the right version of Drush.  For Drupal 8.0-beta7, you need Drush 7.0.0-alpha9.  For Drupal 8.0-beta6, you need Drush 7.0.0-alpha8.
Drupal 8 APIs are changing rapidly; if you have mixed versions, you can easily encounter spurious problems.  Tracking HEAD of Drupal 8.0.x and Drush master is another viable strategy.
Comment: yes, D8 development has made me upgrade drush several times while facing error messages like these. I'm just doing it old school for now not to get too frustrated :)
Comment: I am having drush version 7.0-dev. Is it right version. If not how can I find which version is suitable for my drupal installation?
Comment: Drush 7.0-dev is not a version, it is a branch.  If you install like darol100 suggests, Drush should work on the day you install it, but you might occasionally need to run `git pull` from the Drush directory to update to the latest head.  To install a specific version of Drush, install via Composer as described in the Drush installation documentation: http://docs.drush.org/en/master/install/
Comment: Thanks this worked I installed an alpha release for drush and its now working.
Answer: For D8 don't you need php 5.4+? Check your version of PHP. I believe Ubuntu 14.x has 5.3 by default but that's just a wild guess.
What do you see when you execute php --version on the commandline?
You may need to upgrade through a back channel upgrade through other PPAs or run Drupal in a Virtual Machine / Vagrant.
Comment: PHP 5.5.9-1ubuntu4.5 (cli) (built: Oct 29 2014 11:59:10)
Comment: Well that qualifies!  IF this is just a dev project, you may still want to investigate the vagrant route. This repo is pretty much a fully configured machine to run D6, 7, or 8. https://github.com/geerlingguy/drupal-dev-vm
Comment: But on the same thing is working with another local installation of drupal on same machine... What can be the reason for this ?
Answer: You probably have the wrong version or you installed wrong.
Here are the instruction on how to install Drush on Ubuntu.
# Install Composer
php -r "readfile('https://getcomposer.org/installer');" | php

# Access composer from anywhere on your system:
sudo mv composer.phar /usr/local/bin/composer

# Install Drush
cd /usr/share
sudo git clone --branch master https://github.com/drush-ops/drush.git
cd drush
composer install
cd ~/
# Access drush from anywhere on your system:
ln -s /usr/share/drush/drush /usr/bin/drush

Source: lazydubuntu/bin/basictools.sh
This would make sure that you installed the latest version

Drush not working properly on Ubuntu


RaptureXML Problems parsing a certain rss feed

Question: I'm trying to parse a certain rss feed of a popular german news site (taz.de). Unfortunately, their description tag doesn't only contain plain text but a mixture of anything, including pictures, links etc.
<description>
    <![CDATA[Das Land ist von einem funktionierenden Rechtsstaat weit entfernt. Zehn Jahre nach dem Irakkrieg zeigt sich eine niederschmetternde Bilanz. mehr...]]>
</description>

The only thing I'm interested in is the text Das Land ist von einem funktionierenden Rechtsstaat weit entfernt. Zehn Jahre nach dem Irakkrieg zeigt sich eine niederschmetternde Bilanz. How would I do that in an efficient way (without terrible string operations)? Since there is no attribute name, I guess I'm screwed? I'm using RaptureXML but if there's a better library for this problem, I'd switch the xml parser.
Answer: I'm afraid it's worse than that: The "CDATA" section means that the description (modulo surrounding whitespace) is the literal string
Das Land ist von einem funktionierenden Rechtsstaat weit entfernt. Zehn Jahre nach dem Irakkrieg zeigt sich eine niederschmetternde Bilanz. mehr...

i.e. your snippet is equivalent to
<description>
    <a href="http://www.taz.de/10-Jahre-nach-dem-Irakkrieg/!113046/"><img align="left" style="margin-right:5px;" src="/uploads/images/152x76/18032013_Bush_Irakkrieg_rtr.jpg" border="0" width="152" height="76" /></a>Das Land ist von einem funktionierenden Rechtsstaat weit entfernt. Zehn Jahre nach dem Irakkrieg zeigt sich eine niederschmetternde Bilanz. <a href="http://www.taz.de/10-Jahre-nach-dem-Irakkrieg/!113046/">mehr...</a>
</description>

A conforming XML parser cannot give you the text you're looking for. You have two options:

Wrap the string in e.g. <foo>...</foo>, pass that through the XML parser, and pull out all the text children of the root element.
Wrap the string in something like <title></title>..., pass it through an HTML parser (or any tag-soup-du-jour parser), and pull out all the text children of the body element.

I wonder if taz.de breaks if the description contains ]]>...


Is it possible to restore a Kafka Streams state store after a restart without using changelog topics?

Question: We have 2 compacted topics, each containing terabytes of data, which we want to join using Spring Cloud Stream and Kafka Streams. The (simplified) code looks like this:
@Bean
public BiConsumer<KTable<String, LeftEvent>, KTable<String, RightEvent>> processEvents() {
    return ((leftEvents, rightEvents) -> {
      leftEvents.join(rightEvents, this::merge)
        .toStream()
        .foreach(this::process);
    });
}

The problem with this approach is that using KTables as input parameters results in the creation of changelog topics which essentially duplicate the source topics since, as mentioned above, both of these topics are already compacted. To avoid duplicating terabytes of data in Kafka, our first attempt was to use KStreams as inputs instead, and to transform them into KTables as follows:
stream.toTable(
  Materialized
    .<K, V, KeyValueStore<Bytes, byte[]>>as(stateStoreName)
    .withLoggingDisabled()
);

thereby disabling logging and hence dispensing with the changelog topics, which in our context seem useless.
However, the following scenario now no longer works:

Generate a LeftEvent with key k1
Restart the application
Generate a RightEvent with key k1

The events are no longer joined, although the join works fine if the application is not restarted in-between (i.e. step 1, then 3).
When the application restarts, we would have expected the state stores to be reconstructed from the souce topics in the absence of changelog topics, but this is apparently not the case. In some occasions, we observed that rocksDB files (located in /tmp/kafka-streams/...) were used to retrieve data consumed prior to the restart, however we cannot assume that these files will still be available after a restart since we are working in a containerized environment.
Is there a way to support restarts (and achieve fault tolerance) without having to use changelog topics, which in our case duplicate the input topics? If not, we might have to reconsider our use of Kafka Streams...
Answer: You want to enable optimization of the Kafka Streams: https://docs.confluent.io/platform/current/streams/developer-guide/optimizing-streams.html#optimization-details (#1 is what you are looking for).
Currently, there are two optimizations that Kafka Streams performs when enabled:

The source KTable re-uses the source topic as the changelog topic.
When possible, Kafka Streams collapses multiple repartition topics into a single repartition topic.

A key thing to point out, since I have made this mistake myself, is do not forget to send the configuration to both the build() and to the construction of KStreams (optimization, as indicated here from the link provided) is done in the build.
// tell Kafka Streams to optimize the topology
config.setProperty(StreamsConfig.TOPOLOGY_OPTIMIZATION, StreamsConfig.OPTIMIZE);

// Since we've configured Streams to use optimizations, the topology is optimized during the build.
// And because optimizations are enabled, the resulting topology will no longer need to perform
// three explicit repartitioning steps, but only one.
final Topology topology = builder.build(config);
final KafkaStreams streams = new KafkaStreams(topology, config);

Now optimization is enabled for all of the Topology, so if you keep that in mind that the #2 optimization is also performed.


Creating tags in SVN from trunk

Question: We are using SVN for data repository. I've created branches for our project successfully from eclipse
Now i am trying to create Tags so that i can put the project releases over there. But when i am trying to create "Tags" from eclipse its giving me following error.

Get repository folder children operation failed. svn: E160013: URL
  'svn://svnsrv.yash.com/svn/repo/MyProject/tags' non-existent in that
  revision

Please suggest what to do to create "Tags" from eclipse.
Comment: possible duplicate of [Subversion E160013: '/svn/xxx/!svn/me' path not found\* error](http://stackoverflow.com/questions/9928285/subversion-e160013-svn-xxx-svn-me-path-not-found-error)
Comment: Can you use the command line? svn copy svn://svnsrv.yash.com/svn/repo/MyProject/trunk svn://svnsrv.yash.com/svn/repo/MyProject/tags I think should do the trick. If not, what plugin are you using to interface with SVN from Eclipse?
Comment: I am using Subversion 1.8.9 and SVNKit 1.8.3
Answer: I had the same problem with Kepler and svn Eclipse 1.8.8. The solution was:
SVN perspective> Select repository> New> Folder ... And put: tags
Answer: Go to the "Location properties..." of you repository (right click on the repository at "SVN Repositories" view). Then to "Advanced" tab and disable "Enable Structure Detection". This also applies to the same error when trying to create branch for some folder outside of the trunc.
See Error while creating branches and tags with SVN from Eclipse

Creating tags in SVN from trunk


Android UI lag from setting image

Question: I'm trying to create a simple app to learn about navigation drawers and setting images. I based this app on the template that Android Studio created for me.
I read that getting the drawable can be a long process so I made an Asynctask for it. Despite this, my UI still lags and I get the message that frames are being skipped due to too much work on the main thread. I figured out that the following line is causing those issues:
pic.setImageDrawable(drawable);    //(in onPostExecute)

I did all the processing in the background and this line should just be setting the drawable. Why is this lagging so much?
I read somewhere that setting the dimensions might make a difference. Right now I have both dimensions set to match_parent and the image is centered in the view. I don't want to give it a definite size.
public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private ImageView pic;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    pic = (ImageView) findViewById(R.id.pic);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //set first item to be selected and set its image
    navigationView.getMenu().getItem(0).setChecked(true);
    new ImageSetter().execute();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    try {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    } catch (NullPointerException e) {
        Log.e("back pressed", e.getStackTrace().toString());
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    new ImageSetter(id).execute();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

/**
 * class for getting the image drawable in the background and then setting it
 */
private class ImageSetter extends AsyncTask<Integer, Void, Drawable> {

    int id = //image1;

    public ImageSetter() {
    }

    public ImageSetter(int id) {
        this.id = id;
    }

    /**
     * Get drawable in background
     * Precondition: id has already been set
     * @param params
     * @return drawable of the picture to set
     */
    @Override
    protected Drawable doInBackground(Integer... params) {
        int pic = R.drawable.b1;

        switch (id) {
           //set pic
        }

        return getResources().getDrawable(pic);
    }

    // Once complete, see if ImageView is still around and set drawable
    @Override
    protected void onPostExecute(Drawable drawable) {
        if (pic != null) {
            pic.setImageDrawable(drawable);
        }
    }
}

}
Comment: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Comment: I would say for setting drawables you shouldn't need to use a separate thread, unless you need to do some image processing first. If you're getting frames skipped then its most likely the drawable itself.
Comment: @MarkKleen I think he meant he made an AsyncTask for fetching images from url, which is definitely a good practice. As you said, a separate thread for only setting images in the layout is pretty unnecessary.
Answer: The code looks fine to me. using setImageDrawable() shouldn't be lagging too bad and does need to be run in the UI thread. You have offloaded the task to another thread, which is good.
How big is the source image that you are fetching? Android is notoriously bad at handling large images...
If your source image is too big, I would look at Loading Large Bitmaps Efficiently from the Android developer site. This will give you some tips on handling Bitmaps.

Android UI lag from setting image