Jquery - detect the click outside of input

Question: <input id="ok" />

$('.hor-minimalist-a').on('blur','#ok',function(){

});

with this code above, i can handle events which fire If i leave the input field.
How can I detect if someone clicks outside of inputfield without coming to input. I mean the user never came to this input field before, so there was no focus at all.
$('.hor-minimalist-a').on('?','#ok',function(){
  ?
});

Answer: $(document).on('click', function(e) {
    if ( e.target.id != 'ok' ) {
        // you clicked something else
    }
});

That would capture any click except on the input, but why would you need it ?
To capture only clicks on .hor-minimalist-a and not the entire document, just replace document with that selector in the code above.
Comment: Then you should set up an example, and ask for that specifically, as that would probably require setting a flag wnen the edit icon is clicked, and then check for the next click etc. The best thing would probably be to just focus the input when the edit icon is clicked, and capture the blur event and then check the value.
Comment: i need it, because i have an edit icon where if user clicks a new input field shows up. on blur, the input fields shuts down, but i suspect also, that after hitting edit-icon, the user can decide not to edit. so in this case, on any click outside, the inputfield should shut down
Comment: oh man, this is the best option (setting the input to focus). i will go for it :)
Answer: How about:
$('.hor-minimalist-a').on('click',':not(#ok)',function(){

That'll register click events within .hor-minimalist-a but outside the input #ok
Answer: There is a jquery plugin for that:
http://benalman.com/code/projects/jquery-outside-events/examples/clickoutside/


Stationary dependent variable, integrated regressor: what to do?

Question: Im running a univariate regression and the Y variable doesnt have a unit root, but the X does. The regression is:
ExcessReturn_t = alpha + beta * (Dividend yield)_t-1 + e
After running ADF on both of them, the DY has an unit root, but the excess return does not. How do I proceed to transform them? Do I need to take the Delta of Y too, or only of the X?
For my regression I am using the lagged DY. Can I continue to cointegration, error correction model and forecasting by using the lagged DY?
Im a beginner in this so can someone explain this to me? Thank you in advance!
Answer: Let us write your model in a parsimonious notation,
$$
y_t = \beta_0 + \beta_1 x_{t-1} + \varepsilon_t,
$$
where $y_t$ is the excess return and $x_t$ is the dividend yield. Since $y_t$ is stationary while $x_t$ is integrated, the two diverge, and the model does not make sense. To fix the problem, you may use $\Delta x_{t-1}$ in place of $x_{t-1}$. There is no point in differencing a stationary variable (and it is not innocuous, hence the notion of overdifferencing), so $y_t$ should remain as is. There is no room for considering cointegration as only one of the original variables is integrated while the other is stationary. You could investigate cointegration if you took the cumulative sum of $y_t$ in place of the raw $y_t$, though.
Comment: Thank you for the answer Richard! Much appreciated!
One last detail. R is supposed to be regressed on log(DY). Do I run the ADF test on DY or log(DY)?
When I do the Delta(X_t-1), do I do Delta(logDY) or log(Delta(DY))?
Comment: You run the ADF test on the variable that will be in the regression, so $\log(\Delta y)$. You do $\Delta\log(y)$ since this approximates the percentage change in $y$. (You cannot do $\log(\Delta y)$ for a purely technical reason as well -- because you cannot take logs of negative values.)


Naming convention for bidirectional relationships in Neo4j (using Spring Data)

Question: I need some advice to give name to relationships. Plus, I'm not sure on how I have to annotate my domain entities with spring data. Most of examples that I've seen are unidirectional and the name chosen are pretty straightforward.
Supose the following example:
<code>@NodeEntity
public class Person {
    @Indexed
    private String name;

    @RelatedTo(type="OWNS", direction=Direction.OUTGOING)
    private Set<Car> cars;
}
</code>
The relationship name seems ok, no problem.
Now suppose that I want to make this relationship bidirectional. What are the differences (and the pros/cons) of the following approaches.
1) Make both sides of the relationship direction=Direction.BOTH and call the relationship type="OWNERSHIP"?
<code>@NodeEntity
public class Person {
    @Indexed
    private String name;

    @RelatedTo(type="OWNERSHIP", direction=Direction.BOTH)
    private Set<Car> cars;
}

@NodeEntity
public class Car {
    @Indexed
    private String description;

    @RelatedTo(type="OWNERSHIP", direction=Direction.BOTH)
    private Person person;
}
</code>
2) Use direction on both sides?
<code>@NodeEntity
public class Person {
    @Indexed
    private String name;

    @RelatedTo(type="OWNS", direction=Direction.OUTGOING)
    private Set<Car> cars;
}

@NodeEntity
public class Car {
    @Indexed
    private String description;

    @RelatedTo(type="OWNED_BY", direction=Direction.INCOMING)
    private Person person;
}
</code>
Answer: There is no such thing as bidirectional relationships in Neo4j. Each relationship has a start node and an end node. That said, you can choose to ignore that direction when writing traversals, effectively using the relationship as a bidirectional one.
What you're trying to model is people owning cars. (person) -[:OWNS]-> (car) means two things: from the person's point of view, this outgoing relationship shows the person owns the car. From the car's point of view, the very same (but incoming) relationship means it is owned by the person.
The @RelatedTo annotation in SDN uses Direction.OUTGOING by default, if no direction is specified. This is why you might have thought these relationships are bidirectional, but they are not; they are OUTGOING by default.
So I would model your domain like this:
<code>@NodeEntity
public class Person {
   @Indexed
   private String name;

   @RelatedTo(type="OWNS", direction=Direction.OUTGOING) //or no direction, same thing
   private Set<Car> cars;
}

@NodeEntity
public class Car {
   @Indexed
   private String description;

   @RelatedTo(type="OWNS", direction=Direction.INCOMING)
   private Person person;
}
</code>
Comment: Ok, read the Direction enum JavaDoc again and with the help of your answer I've got the semantics. Just for those with the same question here are the semantics for Direction.Both: "The {@link #BOTH} direction is used when direction is of no importance, such as "give me all" or "traverse all" relationships that are either {@link #OUTGOING} or {@link #INCOMING}"
Comment: Thanks Michal! I understood what you have said specially regarding the absence of bidirectional relationships in Neo4j, I was not aware about that. The question that remains is why Spring Data defines Direction (OUTCOMING, INCOMING and BOTH). Is it only to orient how the queries are going to be generated by the framework? Plus, in what situation Direction.BOTH is useful?


"from pyoptsparse import Optimization" not a valid reference in pyoptsparse_driver.py

Question: This is line 18 in pyoptsparse_driver.py
from pyoptsparse import Optimization

I don't think this is a valid reference to anything. Just trying to work through a simple optimization example from test_pyoptsparse_driver.py See LINE 1575
I tried changing the optimizer from NSGA2 to SLSQP
I don't know why you need this function
_, local_opt = set_pyoptsparse_opt('NSGA2')

Line 330 of set_pyoptsparse_opt calls
from pyoptsparse import OPT

Where is pyoptsparse coming from?
Answer: Pyoptsparse is coming from the MDOLab at UMich and the repo can be found here. To run that example you will need to clone and install the repo using the steps below. OpenMDAO is currently using v1.2 but if you want the latest, simply skip that step.
git clone https://github.com/mdolab/pyoptsparse.git
cd pyoptsparse
git checkout tags/v1.2
pip install -r requirements.txt
pip install .


Should I use react-loadable or loadable-components for code splitting?

Question: I want to split my react code with server side rendering. To do that I have two options.

loadable-components
react-loadable

loadable-components
React documentation suggested to use loadable-components for server rendered apps. But it has very few NPM weekly downloads.
react-loadable
NPM weekly downloads of this package is very high compared to the previous one but according to loadable-components documentation this package is not maintained any more.

react-loadable was the recommended way for React code splitting for a long time. However, today it is not maintained any more and it is not compatible with Webpack v4+ and Babel v7+. Documentation Link

Please guild me with proper package.
Answer: Even though documentation of react-loadable says that react-loadable is not  compatible with Webpack v4+ and Babel v7+, I used  react-loadable and it worked. I did not face any issue in both server and client side rendering applications.
Comment: I always get a warning when using react-loadable. how did you do about that?
Answer: you can use React.lazy.
This will automatically load the bundle containing the OtherComponent when this component gets rendered.
React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.
const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (

      <OtherComponent />

  );
}

Comment: react lazy doesn't support server side rendering. [LINK](https://reactjs.org/docs/code-splitting.html#reactlazy)
Comment: try using `import()`, for more detail see this [post](https://medium.com/airbnb-engineering/server-rendering-code-splitting-and-lazy-loading-with-react-router-v4-bfe596a6af70)
Answer: FWIW loadable-components is recommended by the React team
Also, React.lazy does not currently support SSR (as of May 2020)
Comment: Thanks for reminding me why I chose it in the first place :D


How to identify Bloomberg bond tickers in Excel?

Question: In order to get Bloomberg bond tickers in Excel, for use with the API, I have been copying these from the Terminal. (Specifically, I am looking at US Treasury Notes.)
However, I would like to find a way to automatically or programmatically select / identify bond tickers in Excel, without having to manually copy from Bloomberg terminal every time.
Is there any way to do this using the Excel API or other API scripts?
Comment: This isn't a programming question, but a question about using (or the functionality of) the Bloomberg add-in in Excel...
Answer: There are two approaches to this:
1) The old / pure Excel approach is to use the BOND_CHAIN field - in Excel, that is:
=BDS("ticker Corp", "BOND_CHAIN")

If you look in the Terminal, FLDS BOND_CHAIN (ensure Filter = 'ALL') will show you a number of additional overrides that you can use to set a maturity range etc.
However, the bad news about this approach is that it doesn't support non Corp tickers. That is fine for, say, Gilts, because you can use UKT Corp to get the gilts. But it doesn't work for US Treasuries, because there are both T Corp (AT&T) and T Govt (Treasuries).
2) The newer approach, which interacts with your terminal settings, is to use SRCH / BSRCH. You need to set up / save a search via SRCH in the terminal. You can then call the selection from this SRCH in Excel using:
=BSRCH("FI:search name")

Comment: It may be helpful to someone else to add that the second approach is available through the D-API (either Excel or programmatic APIs), but not through the server APIs (e.g. B-PIPE) - this is because it requires settings from a user's Terminal.


Convert 2D array to single array

Question: suppose i have a two D array.
<code>#define ROWS 3
#define COLS 3

char a[ROWS][COLS]= {
                        {'1','2','3'},
                        {'4','5','6'},
                        {'7','8','9'}
                      };
</code>
How can I copy values of that to a single array. I want only COLS values.
Comment: what do you mean by you only want COLS values? Do you mean you want to do a column-wise vectorization?
Answer: 1) If you need to copy the array in row wise order
you could use :
-first have a 1D array that could hold all the elements of 2D array, then use
    memcpy(new1Darr, org2Darr, total size in bytes);
like for above example,
    memcpy(new1Darray, a, sizeof(char)*ROWS*COLS)
2) Instead of (1) or if you want to change the order in which the data must be stored then just traverse through the 2D array the way you want(column major) and copy the elements one by one. Like (considering you define all the variables first)
This will copy the elements in the new array in column wise order
<code>k=0;
for(j=0;j<COLS;j++)
{
    for(i=0;i<ROWS;i++)
    {
        new1Darray[k] = a[i][j];
        k++;
    }
}
</code>
Answer: Its very simple. Lets see 'how?'-
<code>    #define ROWS 3
    #define COLS 3

    #include<stdio.h>
    #include<conio.h>

    char a[ROWS*COLS]={'1','2','3','4','5','6','7','8','9'};

    void main()
    {
     for(int i=0; i<ROWS*COLS;i=i+COLS)
     {
      for(int j=0; j<COLS; j++)
      {
       printf("%c\t",a[i+j]); //access array
      }
      printf("\n");
     }
     getch();
    }
</code>

Convert 2D array to single array


Menu Lateral do Bootstrap desconfigurado na versão mobile

Question: Estou na luta pra fazer um site e apresentá-lo no meu TCC. Separei as seções do site (body, head, cabeçalho, rodapé...) em arquivos isolados para poder mexer com mais facilidade. Tomei o maior cuidado de separar todos os elementos certos em cada arquivo. Eles aparecem no site porque minha página index.php tem include_once() dessas páginas.
O problema começa aqui: Meu arquivo menu-lateral.php está ficando desconfigurado na sua versão mobile. Ele contém os botões de curtir página do Facebook, seguir perfil do Twitter, link para o Flickr e botão de inscrição na página do YouTube.
Aparentemente, o problema está com o botão curtir do Facebook. Sempre que o site está na sua versão desktop, não há problema, fica tudo certo:

Agora, na versão mobile, ela fica assim (segue foto). O botão está maior do que devia e passando da div do menu E acrescentando um espaço enorme para o corpo da página.

Como deveria ficar:

Os outros botões vão ser substituídos por imagens, porém, quero continuar com o botão curtir do Facebook. Quero saber se é possível: 1) arrumar o problema de espaço na versão mobile; 2) deixar o tamanho do botão responsivo.
Segue o código do menu-lateral.php:

                        IBNM - Igreja Batista Novo Mundo

            Siga @ibnovomundo no Twitter

Comment: Veja se ajuda http://www.dummies.com/how-to/content/add-a-facebook-like-button-to-your-mobile-site.html
Comment: Resumindo a resposta do @AloisoGomes, você só precisa remover a classe `col-xs-6` da `#sidebar`.
Comment: Apenas observando que a solução do @AloisoGomes não é exatamente o que você quer, mas acredito que deva segui-la visto que exibir um menu ao lado do conteúdo em um mobile é extremamente desagradável.
Comment: http://getbootstrap.com/css/#responsive-utilities
Answer: Vamos lá vou tentar te ajudar....
o Bootstrap 3 é rigoroso com o uso correto das classes que determinam o tamanho da coluna da grade, Posso esclarecer dúvidas sobre isso em outra oportunidade, mas a principio faz diferença usar col-xs-*, col-sm-*, col-md-* e col-lg-*. Elas se comportarão de maneira diferentes dependendo do tamanho da tela do dispositivo. Vamos a dúvida!
veja só seu código

como o padrão de colunas do bootstrap é 12 e você usou .col-xs-6
isso significa que para mobile .col-xs- com o valor 6 vc está dizendo que
METADE da largura total da página será reservado para esse menu... um tamanho desnecessário por isso essa distância grande
normalmente em mobile isso deveria ser exibido abaixo do conteudo como se estivesse sozinho em uma linha para mobile vc consegue esse efeito assim

Isso fará o menu aparecer abaixo da coluna anterior que deve ser a de conteúdo. Isso é melhor, pois ficará ruim se você tentar deixar lado a lado dificulta a experiencia do usuário e fica esteticamente ruim pois gera rolagem horizontal, algo que vai na contramão de uma pagina que deveria se adaptar a um dispositivo móvel (Responsividade).
Se isso não der certo provavelmente deve ser a estrutura do html que você desenvolveu, os aninhamentos de linhas e colunas contido no seu código. Ficarei contente em ajudar e ensinar o pouco que sei.
Abraço!
Comment: Obrigado amigo, resolveu o problema do espaço ;)
Comment: Por nada cara, adoro ver aqui uma solução para algum problema que tenho, chega uma hora que preciso retribuir. Abraço


Views date filter yesterday

Question: I want to show yesterday's posts on a block with views. So I added two date filters. They should be:
<today midnight

>yesterday midnight

(-1 day is not ok for me because it spans exactly 24 hours back)
According to the manual: http://php.net/manual/en/datetime.formats.relative.php
I added the two filters as:
Less than "today" (I also tried less than "midnight" or "today 00:00")
Greater than "yesterday" (I also tried greater than "yesterday 00:00")
But they are all showing the items from yesterday and today together.
Is there a way to show items from yesterday 00:00 to yesterday 23:59 ?
Answer: I ended up using contextual filter instead of filters. I added:
Content: Created date
Provide default value - php code
return date("d", strtotime("-1 day"));

Answer: I had the same problem, but unfortunately for me, the field didn't appear in contextual filters, so I still had to use the normal date filter. This worked perfectly for me:
Answer: I always end up forgetting I need to have "two filters" in order to accomplish this...  At least that's what works for me.
I just got done messing with it trying to show some posts from yesterday and came up with:
Content: Authored on (>= yesterday)
Content: Authored on (<= today)

I think the OP had the filters reversed and that's why they weren't working.  Since the filters work top to bottom, "today" was filtered first so there was no real end time to capture.
Love the "is between" method suggested tho.  That's boss.
Update: On a side note to get the same result as the "is between" suggestion, this should also work:
Is Between:
Min = yesterday
Max = today -1 second

Keep in mind, yesterday is the exact same thing as yesterday midnight
https://www.php.net/manual/en/datetime.formats.relative.php
Here's a great way to test the strototime:
https://strtotime.co.uk/
And on a final note, Drupal 8 as of 8.7.7 has a bug where the datetime does not properly execute the right strtotime, resulting in "yesterday" actually being "now -24 hours" instead of "yesterday 00:00".  See the following issue for a patch:
https://www.drupal.org/project/drupal/issues/2647292

Views date filter yesterday


What is the PCA representation of an image?

Question: I've read a lot about how PCA is used to reduce the dimensionality of data, including this great answer and this mathy post. But I'm unclear what this does when applied to image data?
For example, given a set of vectors from images of faces, I could reduce the dimensions:
pca = PCA(n_components=100, svd_solver='randomized', whiten=True)
pca.fit(faces)
compressed = pca.transform(faces)

But when I look at the results, I see nothing like an image:
example = compressed[0]
example *= 255.0
example = example.astype('uint8')
example = example.reshape((10,10))
output = Image.fromarray(example)
output = output.resize((200,200))
output.save('ExamplePCA.jpg')

Can someone describe for me (someone with limited matrix math/linear algebra knowledge) what is being represented here?
Comment: have you seen this answer? https://stats.stackexchange.com/questions/177102/what-is-the-intuition-behind-svd/179042#179042
Comment: ah I misread your question, never mind
Comment: @JeffThompson Look into ZCA ("Zero-phase component analysis"), there's a good question on it that also helps to understand PCA on image collections.
Comment: @Chaconne – is PCA similar? From the answer here below, it sounds like there is no visual correlation between the PCA space and the original image.
Answer: The transformed coordinates are not supposed to look anything like a natural image, even if you keep them all (number of components = number of pixels). In particular, all the different elements ("pixels") are uncorrelated.
When compressing an image this way, you are saying that each image in your dataset has many pixels, but that the images are different from each other in only 100 ways. You find 100 basis images that represent a typical image well, and then each reconstructed image is a linear combination of these 100 basis images, and the 100 numbers in the compressed vector are the coefficients multiplying each basis image. In order to understand what each "pixel" in the compressed vector means you must plot these basis images. To do this in python, try reshaping the rows of pca.components_
When dealing with face images, these basis images are sometimes called eigenfaces.
If you want to see your images projected on the low-dimensional principal subspace, then after applying:
compressed = pca.transform(faces)

you need to apply
decompressed = pca.inverse_transform(compressed)

and plot the decompressed images.
Comment: @JeffThompson The reduced vector is not supposed to have any resemblance to the original images. The grey levels in the reduced vector are not supposed to look anything like adges or contrast or any grey levels in the original images. The order of the "pixels" in the reduced vectors is in decreasing variance of projections of the images onto smaller dimensional vectors, and the different "pixels" are uncorrelated, so their appearance resembles noise.
Comment: @JeffThompson When compressing an image using PCA, you are saying that each image in your dataset has many pixels, but the images are different from each other in only 100 ways. You find 100 "basis images" that represent a typical image well. The reconstructed image is a linear combination of 100 "basis images", and the 100 numbers in the compressed vector are the coefficients multiplying each "basis image". You really can't understand what each "pixel" in the compressed vector means without also plotting the "basis images". To do this in python, try reshaping the rows of pca.components_
Comment: This doesn't quite answer my question. There must be some correlation between the original images and the reduced vector – does it have to do with areas of contrast or edges like in haar detection? Or is it purely mathematical?
Comment: Got it. Can you tell me in simple or metaphorical terms what they represent? You mention "variance of projections" but I'm not familiar with those terms and am trying to get my head around what has been pulled out of the image :)
Comment: Thanks, super helpful. If you update your answer with this info, happy to accept it.
Comment: @JeffThompson Updated. Also, you may want to search for the term "eigenface" for more information on using PCA specifically for face images.


C++ Linker Error Undefined reference in Singleton class

Question: I'm trying to port this java singleton class to c++:
public class Singleton {
private static Singleton uniqueInstance;

private Singleton() {}
public static Singleton getInstance() {
    if (uniqueInstance == null) {
        uniqueInstance = new Singleton();
    }
        return uniqueInstance;
    }
}

I ported to this C++ code:
class Singleton {
private:
  Singleton() {
    cout << "new Singleton is called" << endl;
  }
  static Singleton* uniqueInstance;
public:
   static Singleton* getInstance() {
    if (!uniqueInstance) {
      uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
};

But I can't compile this! and gcc linker error occurred.
Comment: Please show exactly what the linker error was.
Answer: Make sure you define the static member outside the declaration:
Singleton* Singleton::uniqueInstance = nullptr;

Comment: You should initialise to nullptr too.
Comment: @Khajavi Also without high optimisation? Pointers are not guarenteed to be zero on initialisation.
Comment: @AlexChamberlain Why? My program was complied without error without using nullptr!
Comment: In C++11 you should not use pointers. New standard ensures initialization of static member variables is thread safe.
Answer: Your cpp file probably does not reserve space for the static instance, you need to add
 Singelton* Singleton::uniqueInstance = NULL; to your cpp file and then allocate it in the first call


.htaccess 301 redirect for https and www

Question: I'm struggeling with the apache rewrite engine and need help to transform these address-variations:
http://www.site.de/index.php
www.site.de/index.php
http://site.de/index.php
site.de/index.php

to this form with www and https:
https://www.site.de/index.php

How would the statement look like and how does it work?
Currently it works from non-www to www:
Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^site.de [nc]
rewriterule ^(.*)$ https://www.site.de/$1 [r=301,nc]

But it ignores the https.
Answer: Okay, I found the solution:
There must be a second rule like this:
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


How prove this determinant is $0?$

Question: find the value
$$A_{n}=\begin{vmatrix}
1-\dfrac{1}{(n+1)^2}&\dfrac{1}{2}&\dfrac{1}{3}&\cdots&\dfrac{1}{n+1}\\
\dfrac{1}{2}&\dfrac{1}{3}&\dfrac{1}{4}&\cdots&\dfrac{1}{n+2}\\
\dfrac{1}{3}&\dfrac{1}{4}&\dfrac{1}{5}&\cdots&\dfrac{1}{n+3}\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
\dfrac{1}{n+1}&\dfrac{1}{n+2}&\dfrac{1}{n+3}&\cdots&\dfrac{1}{2n+1}
\end{vmatrix}$$
show that $\det(A_{n})=0$
I have prove
$$\det(A_{1})=\begin{vmatrix}
\dfrac{3}{4}&\dfrac{1}{2}\\
\dfrac{1}{2}&\dfrac{1}{3}
\end{vmatrix}=0$$
and
$$\det(A_{2})=\begin{vmatrix}
\dfrac{8}{9}&\dfrac{1}{2}&\dfrac{1}{3}\\
\dfrac{1}{2}&\dfrac{1}{3}&\dfrac{1}{4}\\
\dfrac{1}{3}&\dfrac{1}{4}&\dfrac{1}{5}
\end{vmatrix}=0$$
$$\det(A_{3})=\begin{vmatrix}
\dfrac{15}{16}&\dfrac{1}{2}&\dfrac{1}{3}&\dfrac{1}{4}\\
\dfrac{1}{2}&\dfrac{1}{3}&\dfrac{1}{4}&\dfrac{1}{5}\\
\dfrac{1}{3}&\dfrac{1}{4}&\dfrac{1}{5}&\dfrac{1}{6}\\
\dfrac{1}{4}&\dfrac{1}{5}&\dfrac{1}{6}&\dfrac{!}{7}
\end{vmatrix}=0$$
Comment: It suffices to find explicitly a vector in the kernel of the matrix. With the aid of WA, it seems that the matrix has nullity $1$ and there is an eigenvector with integer coordinates, the first of which is $n$.
Answer: Shifting the index, we have
$$A_n = H_n -(1/n^2) e_1 e_1^T$$
where $H_n$ is the Hilbert matrix and $e_1$ is the column vector $[1,0,0,\dots,0]^T$.
By the matrix determinant lemma,
$$
\det(A_n)=(1-(1/n^2)e_1^T H_n^{-1} e_1) \det(H_n)
=(1-(1/n^2) (H_n^{-1})_{11}) \det(H_n) = 0
$$
because the $1,1$ entry of $H_n^{-1}$ is $n^2$.

How prove this determinant is $0?$


if, else if statement not working correctly

Question: Everything works fine until I get to the second else if when both divs are activated. For some reason, only #project-wrapper gets the class removed. Did I write the second else if wrong?
$('.site-title a').click(function(e) {
    e.preventDefault();

    if($('#project-wrapper').hasClass('activated')){
        $('#project-wrapper').removeClass('activated').css('max-height', '');
    }
    else if($('#contact-me').hasClass('activated')){
        $('#contact-me').removeClass('activated');
    }
    else if( ($('#project-wrapper').hasClass('activated')) && ($('#contact-me').hasClass('activated')) ){
        $('#contact-me').removeClass('activated');
        $('#project-wrapper').removeClass('activated');
    }
    else {
    }

});

Comment: If "project-wrapper" has the class "activated", then the first `if` test would succeed. Once that's happened, the whole list of `else` clauses will be skipped. The test you've got in the last `else if` should be the **first** test you do.
Comment: When you are doing various checks like this, always try to go from the most specific scenario to the most general. In other words, in this case do the test for both being activated first.
Comment: @Rhumborl Thank you. I'm learning day by day! :)
Answer: Check the "both" condition first, else that condition will never be checked:
if( $('#project-wrapper').hasClass('activated') && $('#contact-me').hasClass('activated') ) {
  $('#contact-me, #project-wrapper').removeClass('activated');
}
else if($('#project-wrapper').hasClass('activated')){
  $('#project-wrapper').removeClass('activated').css('max-height', '');
}
else if($('#contact-me').hasClass('activated')){
  $('#contact-me').removeClass('activated');
}
else {
}

Answer: you need to switch the if staments around because the 2nd else if will never get hit
$('.site-title a').click(function(e) {
    e.preventDefault();

    if( ($('#project-wrapper').hasClass('activated')) && ($('#contact-me').hasClass('activated')) ){
        $('#project-wrapper').removeClass('activated').css('max-height', '');
    }
    else if($('#contact-me').hasClass('activated')){
        $('#contact-me').removeClass('activated');
    }
    else if($('#project-wrapper').hasClass('activated')){
        $('#contact-me').removeClass('activated');
        $('#project-wrapper').removeClass('activated');
    }
    else {
    }

});

Answer: Just remove the 'else' parts and keep all conditions in seperate 'if'. That should work
Comment: but this implementation requires the compiler to check each if statement and waste resources (yes this would work, but its not efficient)
Comment: This wouldn't work, since the third 'if' would never be true. ever. After the first two 'if's, the two elements are no longer 'activated'...
Answer: $('.site-title a').click(function(e) {
    e.preventDefault();
    if( ($('#project-wrapper').hasClass('activated')) && ($('#contact-me').hasClass('activated')) ){
        $('#contact-me').removeClass('activated');
        $('#project-wrapper').removeClass('activated');
    }
    if($('#project-wrapper').hasClass('activated')){
        $('#project-wrapper').removeClass('activated').css('max-height', '');
    }
    if($('#contact-me').hasClass('activated')){
        $('#contact-me').removeClass('activated');
    }
});

Comment: This wouldn't work. The third 'if' would never happen because if any of the elements is 'activated', the first two 'if's would remove the 'activated' class, and then the third 'if' would never be 'true'.
Answer: In your code, the second 'else-if' statement will NEVER be reached since it requires that BOTH elements will have the class 'activated', and if that's the case, then the FIRST 'if' will kick in, and nothing else will happen.... (all of the 'else if' statements...)


hide all child elements on multiple divs

Question: I have four divs and want to hide all child elements on each of them.
<code>$('#col1').children().hide();
$('#col2').children().hide();
$('#col3').children().hide();
$('#col4').children().hide();
</code>
I believe there is a better way.
Answer: Yes, you can do all with only one line:
<code>$('#col1, #col2, #col3, #col4').children().hide();
</code>
If you have only these divs you may reduce all to:
<code>$('[id^="col"]').children().hide();
</code>
In this way all divs having an id starting with col will be selected.


Kraken API Request-sent exception

Question: After a simple query
k.query_public('Ticker', {'pair' : 'GNOETH'})['result']['GNOETH']['b'][0])

if I'm getting a time-out or other exception like 504, the
next query and all next queries in my cycle are getting this exception:
http.client.CannotSendRequest: Request-sent

How can I prevent this?
Comment: I have the same issue, no answer ?
Comment: I have opened an issue here https://github.com/veox/python3-krakenex/issues/32
Answer: I've got an answer - you have to close a connection with k.conn.close() in exception:
 while True:
  try:
   trades = k.query_public('Trades', {'pair' : 'ETHUSD'})
   return trades
   break
  except Exception as ex:
   k.conn.close()

Answer: Try also to ensure that the value of "nonce" is set to 0 at the api-key creation.

Kraken API Request-sent exception


How to delete a node or a list of nodes with Drush?

Question: I discovered the Delete all module which gives you the ability to delete all the nodes of a given content type. However, with this module you can't delete a single node or a list of nodes.
In the question "Can I delete nodes of a given content type with Drush?" I found 2 answers talking about the command drush node_delete <nid> but I can't find this command.
I found in a discussion about node_delete() some code using eval to accomplish this task, but it is using eval:
drush php-eval "global \$user; \$user = user_load(1); node_delete(nid);"

In case that there doesn't exist a functionality implemented to accomplish this, what is the better way to implement this functionality: in the Drush module or create a new module?
Answer: Finally I create my own module named drush_delete
Inside the drush_delete.drush.inc file put this code:
<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

Install the module, run drush cc drush to clear the drush cache and use the command like this:
To delete a node use:
drush node-delete 1
drush nd 1

To delete multiple nodes use:
drush node-delete 1 2 3
drush nd 1 2 3

You can found the command in this module:
https://github.com/adrian-cid/drush_commands
Answer: IMHO the easiest way is with php-eval:
drush php-eval "node_delete_multiple(array(NODE_ID));"

...
drush php-eval "node_delete_multiple(array(34));"     // for node/34

drush php-eval "node_delete_multiple(array(34, 35));" // for node ids 34 and 35

Comment: Thanks, but I think that if you have a drush command you can add arguments and option that maybe are needed. And you can add validations in a easy way.
Comment: I love this answer.  No custom drush command needed.
Answer: If you use the Drush Entity module, then you may run drush entity-delete node 123 to delete nid 123 from your site.
EDIT: If somebody need to use the drush entity-delete command, should use the dev version of the module: https://www.drupal.org/project/drush_entity/releases/7.x-5.x-dev
Comment: You can found the issue and the patch in https://www.drupal.org/node/2756071#comment-11339679
Comment: thanks greg, you always helping with the drush stuffs ;-)
Comment: I found a bug inside the drush entity module who don't allow the deletion of nodes, I will commit the patch later.
Comment: The patch was submitted, if somebody need to use the `drush entity-delete` command should use at this moment the dev version of the Drush Entity module https://www.drupal.org/project/drush_entity/releases/7.x-5.x-dev
Answer: If you want to delete all nodes use the range() function as

drush php-eval "node_delete_multiple(range(1,3000));"


Determinantal formula for reproducing integral kernel

Question: How do I prove the following?
$$\int\det\left(K(x_{i},x_{j})\right)_{1\leq i,j\leq n}dx_{1} \cdots dx_{N}=\underset{i=1}{\overset{n}{\prod}}\left(\int K(x_{i},x_{i})\;dx_{i}-(i-1)\right)$$
where
$$K(x,y)=\sum_{l=1}^n \psi_l(x)\overline{\psi_l}(y)$$
and
$$\{\psi_l(x)\}_{l=1}^n$$
is an ON-sequence in $L^2$.
One may note that $$\int K(x_i,x_j)K(x_j,x_i) \; d\mu(x_i)=K(x_j,x_j)$$
and also that $$\int K(x_a,x_b)K(x_b,x_c)d\mu(x_b)=K(x_a,x_c).$$
Comment: Is there a link between $n$ and $N$?
Comment: yes, my bad. n=N
Answer: (This is too long to fit into a comment.)

Note that the product in the integrand of the right side foils out as
$$\sum_{A\subseteq [n]} (-1)^{n-|A|}\left(\prod_{i\not\in A} (i-1)\right)\prod_{j\in A}K(x_j,x_j).$$
(Here $[n]=\{1,2,\dots,n\}$.) On the other hand, we can use Leibniz formula to expand the determinant in the left hand side to obtain
$$\iint\cdots\int \sum_{\sigma\in S_n} (-1)^{\sigma}\left(\prod_{i=1}^nK(x_i,x_{\sigma(i)}) \right)dx_1\cdots dx_n$$
Interchange the order of summation and integration. Observe that $K(x_1,x_{\sigma(1)})\cdots K(x_n,x_{\sigma(n)})$ can be reordered into a product of factors of the form $K(x_a,x_b)K(x_b,x_c)\cdots K(x_d,x_a)$ (this follows from the cycle decomposition of the permutation $\sigma$), and the integration of this over $x_b,x_c,\dots,x_d$ is, by induction on the two properties at the bottom of the OP, smply $K(x_a,x_a)$. From here we can once again switch the order of summation and integration.
I think the last ingredient needed is something from the representation theory of the symmetric group. In other words, we need to know that the number of ways a permutation $\sigma$ can be decomposed into cycles with representatives $i_1,i_2,\dots\in A\subseteq [n]$, weighed by sign, is the coefficient of $\prod_{j\in A}K(x_j,x_j)$ in the integrand's polynomial on the right hand side (or something roughly to this effect).
Comment: $$\int\det\left(K(x_{i},x_{j})\right)_{1\leq i,j\leq n}dx_{1}....dx_{N}=\underset{i=1}{\overset{n}{\prod}}\left(\int K(x_{i},x_{i})dx_{i}-(i-1)\right)$$ was actually the identity i must proove. But i guess it also boils down to decomposing the permutations into different cycles
Answer: Iterated use of Lemma 5.27 (p. 103) in Orthogonal polynomials and random matrices: a Riemann-Hilbert approach by Percy Deift. (Google Books link.)
Answer: A proof can be found in this blog post by Terence Tao.
It is also possible to use integration over Grassmann variables to obtain the formula: first express the determinant as a Gaussian integral over Grassmann variables and then perform some easy manipulations. I have written down more details here.


Cálculo de soma de moeda

Question: Preciso de uma ajuda para fazer um calculo na verdade uma soma por moeda, como mostro na imagem abaixo:

segue meu código.
private void ListaGrid()
    {
        conex.Open();
        string strSQL = @"SELECT DISTINCT
                        SY.YF_DESC_SI                               AS [TIPO MOEDA],
                        RTRIM(SC.C7_PRODUTO) + ' - ' + SC.C7_DESCRI AS PRODUTO,
                   SUM(SC.C7_QUANT)                            AS QTDA,
                   SUM(SC.C7_TOTAL * SC.C7_TXMOEDA)            AS TOTAL,
                   SUM(SC.C7_TOTAL)                            AS [TOTAL MOEDA]
               FROM  SC7010 AS SC
          INNER JOIN SM2010 AS SM WITH (NOLOCK) ON SM.M2_DATA = SC.C7_EMISSAO
          INNER JOIN SA2010 AS SA WITH (NOLOCK) ON SA.A2_COD = SC.C7_FORNECE
               INNER JOIN SYF010 AS SY WITH (NOLOCK) ON SY.YF_MOEFAT = SC.C7_MOEDA
               WHERE SC.D_E_L_E_T_ <> '*'
               AND SC.C7_EMISSAO BETWEEN CONVERT(datetime, '" + txtDtInicial.Text + "', 103) AND CONVERT(datetime,'" + txtDtFinal.Text + "', 103) AND SA.A2_COD = '" + txtCodFornec.Text + "' GROUP BY SC.C7_PRODUTO, SC.C7_DESCRI, SY.YF_DESC_SI ORDER BY RTRIM(SC.C7_PRODUTO) + ' - ' + SC.C7_DESCRI";

        comando = new SqlCommand(strSQL, conex);

        try
        {
            SqlDataAdapter dados = new SqlDataAdapter(comando);
            DataTable dtLista = new DataTable();
            dados.Fill(dtLista);

            DGW_PedComprasPic.DataSource = dtLista;
        }
        catch
        {
            MessageBox.Show("Não existem dados a serem encontrados");
        }

        double QTDA = 0;
        foreach (DataGridViewRow rowKG in DGW_PedComprasPic.Rows)
        {
            QTDA += Convert.ToDouble(rowKG.Cells["QTDA"].Value);
        }
        txtProdkg.Text = Convert.ToString(QTDA);
        txtProdkg.Text = QTDA.ToString("N2");

        double TotalReal = 0;
        foreach (DataGridViewRow rowR in DGW_PedComprasPic.Rows)
        {
            TotalReal += Convert.ToDouble(rowR.Cells["TOTAL"].Value);
        }
        txtReal.Text = Convert.ToString(TotalReal);
        txtReal.Text = TotalReal.ToString("C");

        //    double TotalDolar = 0;
        //    foreach (DataGridViewRow rowD in DGW_PedComprasPic.Rows)
        //    {
        //        TotalDolar += Convert.ToDouble(rowD.Cells["TOTAL MOEDA"].Value);
        //    }
        //    txtDolar.Text = Convert.ToString(TotalDolar);
        //    txtDolar.Text = "$ " + TotalDolar.ToString("N2");
        //    double TotalEuro = 0;
        //    foreach (DataGridViewRow rowE in DGW_PedComprasPic.Rows)
        //    {
        //        TotalEuro += Convert.ToDouble(rowE.Cells["TOTAL MOEDA"].Value);
        //    }
        //    txtEuro.Text = Convert.ToString(TotalEuro);
        //    txtEuro.Text = "€ " + TotalEuro.ToString("N2");

        //conex.Close();
    }

Comment: E qual é a ajuda que você precisa?
Comment: Preciso verificar na coluna TIPO DE MOEDA no datagrid, e somar. EX. tenho 4 linhad com moeda EURO, preciso somar o valor que esta na coluna TOTAL MOEDA de tudo que for EURO e mostra a coma o txtbox acima que esta com o nome Total €€
Comment: você tem 2 caminhos, fazer via SQL e retornar os dados já agrupados..utilizando computer by, ou sub-consultas, ou stored procedures ou escutar o GridView1_RowDataBound assim que os valores forem preenchidos na coluna vc vá somando.
Comment: Sim mas preciso somar por tipo de moeda, como faço isso direto no datagridview
Comment: if (e.Row.RowType == DataControlRowType.DataRow)
{
var dr = ((DataRowView)e.Row.DataItem).Row;
if dr[0].Tostring() =="euro"{ //soma
Comment: coloquei um exemplo básico pra asp.net e pra windows.form
Comment: Ainda não deu certo aqui. não sei se estou conseguindo me explicar direto, preciso verificar a coluna TIPO DE MOEDA, nessa coluna tenho linhas com dois TIPOS DE MOEDAS "EURO" e "DOLAR DOS EUA" agora preciso verificar o valor de cada linha na coluna TOTAL MOEDA, feito isso preciso somar a moeda EURO, e também somar o valora da moeda DOLAR DOS EUA, mas separadamente mostrando em um txtbox o total em valor da moeda EURO eo total em valora da moeda DOLAR DOS EUA.
Answer: Você tem 2 caminhos.

Fazer através do SQL (Stored procedure, ou computer by, etc) e já retornar os dados prontos.
Ou através da propriedade GridView1_RowDataBound (ASP.NET) se for Windows.Form dataGridView1_CellFormatting ou dataGridView1_RowsAdded

Exemplo de como manipular o RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {//tem dados

     var dr = ((DataRowView)e.Row.DataItem).Row;
     if(dr[0].ToString()=="Euro")
     {
        //somaEuro += Convert.ToDecimal(dr[3]);
     }
    }
}

exemplo de dataGridView1_CellFormatting
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {

}

https://stackoverflow.com/questions/25192961/cell-formatting-in-datagridview-on-databindingcomplete

Mais informações:
https://msdn.microsoft.com/pt-br/library/system.web.ui.webcontrols.gridview.rowdatabound(v=vs.110).aspx

Cálculo de soma de moeda


Unwanted number calculation result

Question: Ok so I'm writing a program that gives a user a set of equations depending on how many they wish to do. After it runs and the user answers all the questions a report is generated. My code for the report is simple:
public void report(){
    percent = (totalCorrect / numberOfQuestions) * 100;
    totalTime = (endTime - startTime) / 1000;
    System.out.println("Report:");
    System.out.println("Questions Answered: " + numberOfQuestions);
    System.out.println("Total Correct: " + totalCorrect);
    System.out.println("Total Incorrect: " + totalIncorrect);
    System.out.println("Percent: " + percent + "%");
    System.out.println("Time taken: " + totalTime + " seconds");
}

However the result is:
Report:
Questions Answered: 2
Total Correct: 1
Total Incorrect: 1
Percent: 0.0%
Time taken: 2 seconds

This is correct, I purposely answered one correct and one incorrect. My question is the percentage is always 0.0% unless I get them all right in which case it is 100%. I don't understand what I'm doing wrong. It's recording the correct number of answers that are correct (based on the "Total Correct: " output) and the number of questions. And obviously my equation for percentage is correct. Any help would be much appreciated!
Comment: Well that's the same old school issue of Integer Division - `5 / 100 == 0`.
Answer: You most likely have performed integer division, if totalCorrect and numberOfQuestions are int in your program.  In integer division in Java, the result must also be an int so the result is truncated.
Cast one of the variables to double before performing the division, so Java will perform floating-point division first.
percent = ((double) totalCorrect / numberOfQuestions) * 100;

Comment: I had a feeling it was something very basic that slipped my mind. Thank you!
Answer: As others have pointed out, you're probably doing integer division.
One or both of your variables totalCorrect and numberOfQuestions needs to be a double, at least at the time of calculation.
Try this:
percent = ((double)totalCorrect / numberOfQuestions) * 100;

Maulzey gives another good alternative that doesn't cast from int to double.

Unwanted number calculation result


Method of characteristics for a system of PDEs when equations are dependent on both variables

Question: I have been trying to use the method of characteristics to solve a system of two partial differential equations. The equations I am trying to solve are:
$$\frac{\partial a}{\partial x}+g\frac{\partial a}{\partial y}=ab-a$$
$$\frac{\partial b}{\partial x}+g\frac{\partial b}{\partial y}=ab-b$$
Solving for $a$ and $b$, where $g$ is a constant.
The problem I have been having is with the right side of the equation. I have tried using the general matrix method to decouple the equations and solve them independently, but I have not been able to do so. I have not seen any examples where the right hand side has a dependency on both variables in the equation.
Any help would be greatly appreciated.
Edit: I should have mentioned the boundary conditions. At $x=0$, $a=\alpha$ and $b=\beta$ where $\alpha$ and $\beta$ are real, positive numbers.
Comment: Well, you have a nicer equation for $a-b$, which you can solve first.  However, it is still going to be ugly when you eliminated $b$.
Answer: $$\frac{\partial a}{\partial x}+g\frac{\partial a}{\partial y}=ab-a \tag 1$$
$$\frac{\partial b}{\partial x}+g\frac{\partial b}{\partial y}=ab-b \tag 2$$
Let $u(x,y)=a-b$
$$\frac{\partial u}{\partial x}+g\frac{\partial u}{\partial y}=-u$$
This is a first order linear PDE easy to solve. You get the general solution :
$$u=e^{-x}F(y-gx) \tag 3$$
with arbitrary function $F$.
The condition $u(0,y)=\alpha-\beta$ implies $\alpha-\beta=e^0F(y-0)=F(y)$
Thus the function $F$ is constant and is known now : $F=\alpha-\beta$
$$u=(\alpha-\beta)e^{-x}$$
$$b=a-(\alpha-\beta)e^{-x}$$
Putting it into Eq.$(2)$ :
$$\frac{\partial b}{\partial x}+g\frac{\partial b}{\partial y}=(a-1)\big(a-(\alpha-\beta)e^{-x}\big) \tag 4$$
This is a first order linear PDE. The Charpit-Lagrange characteristic equations are :
$$\frac{dx}{1}=\frac{dy}{g}=\frac{da}{(a-1)\big(a-(\alpha-\beta)e^{-x}\big)}$$
A first characteristic equation comes from $\frac{dx}{1}=\frac{dy}{g}$
$$y-gx=c_1$$
A second characteristic equation comes from $\frac{dx}{1}=\frac{da}{(a-1)\big(a-(\alpha-\beta)e^{-x}\big)}$. solving thir Riccati ODE leads to :
$$a=1+\frac{x+(\alpha-\beta)e^{-x}}{(\alpha-\beta)\text{Ei}\big((\alpha-\beta)e^{-x}-\exp\big(x+(\alpha-\beta)e^{-x}\big)\big)+c_2}$$
Ei is the special function called "Exponential Integral" : https://mathworld.wolfram.com/ExponentialIntegral.html
The general solution of the PDE $(4)$ is :
$$a=1+\frac{x+(\alpha-\beta)e^{-x}}{(\alpha-\beta)\text{Ei}\big((\alpha-\beta)e^{-x}-\exp\big(x+(\alpha-\beta)e^{-x}\big)\big)+\Phi\big(y-gx \big)} \tag 5$$
with arbitrary function $\Phi$.
The condition $a(0,y)=\alpha$ gives :
$\alpha=1+\frac{0+(\alpha-\beta)e^{0}}{(\alpha-\beta)\text{Ei}\big((\alpha-\beta)e^{0}-\exp\big(0+(\alpha-\beta)e^{0}\big)\big)+\Phi\big(y-0 \big)} =1+\frac{(\alpha-\beta)}{(\alpha-\beta)\text{Ei}\big((\alpha-\beta)-\exp\big((\alpha-\beta)\big)\big)+\Phi\big(y\big)}$
This implies $\Phi(y)=$constant.
$\Phi=\frac{(\alpha-\beta)}{\alpha-1}-(\alpha-\beta)\text{Ei}\big((\alpha-\beta)-\exp\big((\alpha-\beta)\big)\big)$
The constant $\Phi$ is known now. We put it into $(5)$ which gives the solution :
$$a=1+\frac{x+(\alpha-\beta)e^{-x}}{(\alpha-\beta)\text{Ei}\big((\alpha-\beta)e^{-x}-\exp\big(x+(\alpha-\beta)e^{-x}\big)\big)+\frac{(\alpha-\beta)}{\alpha-1}-(\alpha-\beta)\text{Ei}\big((\alpha-\beta)-\exp\big((\alpha-\beta)\big)\big)}$$
Then one found $b$ with :
$$b=a-(\alpha-\beta)e^{-x}$$
Note that the specified condition leads to a solution which is function of $x$ only. If this was known from the very start the calculus would had been much simpler with a system reduced into ODEs instead of PDEs :
$$\frac{d a}{d x}=ab-a$$
$$\frac{d b}{d x}=ab-b$$


Balanced repeated measures design

Question: Okay this is my problem:

I have 12 participants.
Each participant spent 3 nights in my lab doing a reaction time task at four timepoints during the night(12, 1, 2 and 3 oclock), with one week between each of those nights.
Each night, each participants was exposed to one of three experimental conditions, such that each participant completed each condition at the end of the three weeks, but with the order of conditions fully balanced over subjects.

So in the end I have for each participant, for each condition, four mean reaction times.
I wanted to use a linear mixed model with condition and timepoint during the night, and the interaction of condition*timepoint as fixed effects(since I expect reaction time to decrease less in one of the three conditions during the night). As a random effect I wanted to include subject, but I'm not confident of how I would be doing this in SPSS and whether a mixed model is the right way to go.
Can someone give me a few hints on how to proceed? I'd really appreciate it!
Thanks in advance
Answer: You don't need to specify a covariance structure and it is highly discouraged: If you choose the wrong structure, you might miss the targeted type-I-error. Instead, use the procedure described here. It is a generalization of ANOVA for unknown covariance matrices and even applicable if there are more repeated measures than independent subjects.
Unfortunately, it is not (yet) implemented in SPSS. But there are SAS macros. See how hld-f2.sas is used.
Comment: Are you aware of an `R` implementation of this idea?
Answer: If you want to model the covariance structure simply as compound symmetric, the results from-mixed effect modeling and repeated-measures ANOVA should match if the data are balanced and not missing. If you want to model the covariance structure as something else (e.g., unstructured or autoregressive), then you need to use mixed-effects modeling.
How do you know which covariance structure to use? First, plot the data and see is the variance/correlation noticeably changes over nights. Second, compute a covariance matrix to see whether the (co)variance remains constant over nights. Third, check the journal you are thinking of submitting your article to. Does it prefer advanced or conventional techniques? If the journal publishes only articles using ANOVAs, then you may want to stick with ANOVA as well (unless you feel comfortable justifying the use of an alternative covariance structure based on mixed-effects modeling).

Balanced repeated measures design


Proportion/Ratio response variable

Question: I need some advice to understand the following code. We are working with lung data and usually we use LMS technique to calculate the reference curves. In order to calcualte the curves with LMS method from gamlss package we use the following code (forexample)
library(gamlss)
A<-lungFunction

m1 <- gamlss(slf ~ log(height) + pb(log(age)), sigma.fo =~pb(log(age)), nu.fo =~pb(log(age)), family = BCCGo(mu.link = "log"), data=A)

the link for µ needs to be the log.

It seems that LMS method is not appropriate method when the response variable is a ratio or proportion, So inflated logitSST distributions is proposed instead. In an article, the following code was used to calculate the centile curves for slf which is a proportion (0,1]. I could not understand why ga function and s function were used to define the µ. So any advice regarding that would be highly appreciated. I am also wondering how I can Implement the prediction equation and and the contribution of the splines (Mu,Sigma,nu) varies with age. In LMS method when the link function for Mu is log function then we take exp function for back transformation but I have no idea how we can do it when we define mu.formula = ~ ga(~s(log(height), log(age)))
library(gamlss.inf)
library(gamlss.add)

 gen.Family("SST", "logit")

mf1 <- gamlssInf0to1(y=slf,
                     mu.formula = ~ ga(~s(log(height), log(age))),
                     sigma.formula = ~pb(log(age)),
                     nu.formula = ~pb(log(age)),
                     tau.formula = ~pb(log(age)),
                     xi1.formula = ~pb(log(age))+ pb(log(height)),
                     family = logitSST,
                     data = A,
                     n.cyc = 100,
                     trace = TRUE)

Comment: What is the full name of "LMS"?
Comment: @Zhanxiong [apparently](http://materiais.dbio.uevora.pt/BD/Crescimento/Smoothing_Reference_Centile_Curves_(LMS_Method).pdf) "the
distribution at each covariate value is summarized by three parameters, the Box-Cox power $\lambda$, the mean $\mu$ and the coefficient of variation $\sigma$, and the initials of the parameters give the name to the LMS method" so *Lambda-Mu-Sigma*
Comment: `ga` is an interface to `gam` from the `mgcv` package. To generate the reference curves, you'd normally use the `predict` function. You don't need to backtransform anything by hand.
Comment: @ thanks for the reply. We need to present the equations. Forexample, when we use LMS method with long link function for Mu, the formula for mu would be: (forexample: mu = exp(-10.56310 + 2.27937·log(height) + 0.04112·log(age) + mu-spline). However, I have no idea how we can present the equation for mu when we use logitSST.
Comment: @
Henry, thanks for the reply, You are right, The LMS method is equivalent to Box-Cox Cole and Green distribution (BCCG), and BCCG parameters (μ, σ, υ) are the approximate median, coefficient of variation and skewness.
Answer: Yes, ga is an interface to gam in the mgcv package.
This is needed to include a bivariate smoother s(log(height), log(age)).
If y~logitSST(mu,sigma,nu,tau),
then logit(y) = log(y/(1-y)) ~ SST(mu, sigma,nu,tau).
The default link functions for SST are:
identity for mu
log(sigma) for sigma
log(nu) for nu
log(tau-2) for tau
The reason for log(tau-2) is to ensure tau>2, so that the mean and variance of SST are finite. In fact mu=mean and sigma=standard deviation for SST.
Comment: Did you really mean  tau>2 ?

Proportion/Ratio response variable


why can't access the site when ping the ip it can get through?

Question: When I used the ping command to test my site, it shows OK.

When I access the site with ip or domain(sexylingerietop.com), it shows Unable to connect. I put the site on a vps yesterday. The site sometimes can access, sometimes can't. what's the reason it maybe cause this?
When i use ftp to access the site, it works.
Comment: sexylingerietop.com … seriously?
Comment: Well, there's nothing wrong with the domain if he's selling sexy lingerie...
Comment: Can't be selling too much if the web server is down. ;)
Comment: You say that you can't connect to it by pointing a web browser to the IP, but yet two other domains hosted on the same VPS work fine? Could there be something like connection rate limiting or some such in place somewhere? Do the domains point at the exact same IP address? No round robin or the likes to mess things up?
Answer: Pinging is not the same as visiting in a browser. For pinging the server only needs to accept ICMP requests, when visiting the site you do an HTTP request to the webserver at that ip. Much more happens.
So there are many things that could be wrong, including for example:

No webserver is installed or it is not accepting request for some
reason
The server has a firewall which is preventing connections on
port 80

Edit:
If you are having intermittent problems, the above will probably not be the case. Then I really suggest you contact your VPS hoster about the problems you are having.
Comment: ping uses ICMP, not TCP. http://en.wikipedia.org/wiki/Ping
Comment: thank you, but sometimes i can access the site, sometimes don't. there are three sites on my vps. the rest two works ok
Comment: @Farhan True, although I think my idea was clear. I have modified my answer to comply though.
Comment: Servers don't 'accept ICMP connections', they process ICMP requests. ICMP is a connectionless protocol.
Comment: And modified again.. Although I really think everyone knows what I meant.
Answer: Ironically I have just dealt with this problem twice in one day on Linux and Windows. On Windows problem ended up being Anti-virus(Avast) Internet Scanner blocking port 80 traffic. One Linux box after clearing DNS cache in browser, and restarting network interface with no luck. I restart the networking service /etc/init.d/networking restart and it worked.
Answer: If you can hit the site via ping and get access via FTP, the HTTP daemon is probably down. You should contact your provider and ask them about it.
Comment: thank you, but sometimes i can access the site, sometimes don't. there are three sites on my vps. the rest two works ok
Comment: Odd. Perhaps it's a firewall or NIC issue.


Wrong format for index: invalid literal for int() with base 10

Question: I use an api interface to send dates from a google sheet to a html form.
When you select a date then should send a PATCH method to this google sheet.
But I get this error message in the console: Wrong format for index: invalid literal for int() with base 10: 'vEmWzLMH3R89ZMQF4URHK'
This is my javascript code:
const data = {
Datum: "Jack Doe",
  Anzahl: "10",
};

// Add one line to the sheet
fetch('https://sheet.best/api/sheets/d3abdb1d-1bdc-48e3-9096-ea050256b49a/vEmWzLMH3R89ZMQF4URHK#TGinDJ#fGi%qc29AZv5ZwcZId71STqpABWTa6I5_bf/Datum/*12.12.2020 13:00 Uhr', {
    method: "PATCH",
    mode: "cors",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(
      data
    ),
  })
  .then((r) => r.json())
  .then(console.log)
  .catch(console.error);

Comment: It looks like you're sending the value `vEmWzLMH3R89ZMQF4URHK` where a number is expected.
Answer: According to the the documents the index is a number i.e.

PATCH https://sheet.best/api/sheets/cf969697-682a-40e3-bad4-d54803eeeacf/2

However, you're sending vEmWzLMH3R89ZMQF4URHK string instead of it


get CORS problem when ty to get a token in keycloak with vuejs and axios

Question: I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
 const params = new URLSearchParams();
  params.append("grant_type", "password");
  params.append("client_id", "notas-front");
  params.append("username", usuario.value);
  params.append("password", password.value);
  console.log(params);
  const config = {
    //  withCredentials: true,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  };
  axios.defaults.headers.common["Access-Control-Allow-Origin"] =
    "http://localhost:8080";
  axios
    .post(
      "http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
      params,
      config
    )
    .then((response) => {
      console.log(response);
    });

and get this error:

but when I look the request I can't find the error:
the OPTIONS returns 200

but the POST dont
Answer: Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Answer: Configure Web Origins properly in the Keycloak notas-front client config.
Answer: We ran into the same problem after migrating from Vue 2.7 to Vue 3.1 which meant that we also had to make changes to sentry.ts and keycloak.ts.
But in sentry.ts we used tracingOrigins: ["localhost", /^\//, /^https?:\/\//], which also applied to keycloak requests, hence came the CORS error.
We fixed it by using tracingOrigins: [window.location.origin].


Split a column into two, using parenthesis as separator in R

Question: I have a weird data format and I need to split a column to two.
col=c("142343-2344343(+)", "546354-4775458(-)", "374637463")

I want to split col to col1 and col2, using the first parenthesis as separator.
I want something like this
     col1                 col2
142343-2344343            +
546354-4775458            _
374637463                  NA

I d love your help!
Answer: Try separate:
library(tidyverse)
data.frame(col) %>%
  separate(col,
          into = c("col1", "col2"),
          sep = "\\(|\\)")
            col1 col2
1 142343-2344343    +
2 546354-4775458    -
3      374637463 <NA>

Answer: We may use base R with read.csv
read.csv(text = sub("(.*)([+-])$", "\\1,\\2",
gsub("\\(|\\)", "", col)), header = FALSE, na.strings= "",
col.names = c("col1", "col2"))

-output
             col1 col2
1 142343-2344343    +
2 546354-4775458    -
3      374637463 <NA>

With tidyr, an option is
library(tidyr)
library(dplyr)
library(tibble)
tibble(col) %>%
 separate_wider_regex(col, c(col1 = ".*", "\\(", var2 = "[^)]",
    "\\)"), too_few = "align_start")

-output
# A tibble: 3 × 2
  col1           var2
  <chr>          <chr>
1 142343-2344343 +
2 546354-4775458 -
3 374637463      <NA>

Comment: @Corrector you can use the iupdate
Comment: wow! This is more than cool!
Comment: thats looks beatiful. I am such a newbie though. What if I want to use the separate function from tidyr. What would it be sep="", equal to?


How to place button inside of EditText

Question: I want to place an image button inside of EditText, but I don't have Idea please tell me how to do so as shown in the figure . Thanks
Comment: use EditText's android:drawableRight="@drawable/ic_search"
Comment: I have mentioned that this is an image button
Comment: are you want click on this image?
Answer: If You dont want click on that Image, Then you can use drawableRight property for EditText..
android:drawableRight="@drawable/icon"

If you want click then use below code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter search key" />

    <ImageButton
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@drawable/search"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:text="Button"/>

</RelativeLayout>

Comment: @CapDroid ...If I use your way of designing xml, the user text hides behind the imageview placed on the top. Do you have any idea, how to achieve this with restricting the text to go beyond the limit.
Comment: @ArshadAliSoomro use transperant image as background
Comment: thanks for this reply but I want to the image be like clickable Button
Comment: this works but does not meet to my need because it shows the background color of button and border as well, I only want the transparent image..
Comment: No, This layout is wrong. what if we took EditText at the bottom or any random place?
Comment: this donot align the image to right of the EditText.
Answer: If you want such layout and also image as clickable then you can do something like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" >

    </EditText>
     <ImageView
        android:id="@+id/imageView1"
        android:padding="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/editText1"
        android:layout_alignBottom="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

Output:
Comment: In your XML for edittext, use `android:singleLine="true"` and `android:paddingRight="50dp"` to prevent your text from going behind the image button on the right
Comment: how to add click event on this Image, please
Comment: Map imageview by id in your Activity class and set Listener to it [See clickListener](http://start-jandroid.blogspot.in/2011/01/android-multiple-screen-example.html)
Comment: how to keep my text from going behind the `ImageView`?
Answer: In Material, there is that underline under EditText. In most applications the icons appear inside that underlining.

For that purpose, just use padding
android:paddingEnd = "@dimen/my_button_size"

Don't forget paddingRight for sub 4.2 versions.
<RelativeLayout ....>
   ...
   <EditText
   ...
   android:id="@+id/my_text_edit"
   android:textAlignment = "viewStart"
   android:paddingEnd = "@dimen/my_button_size"
   android:paddingRight = "@dimen/my_button_size"
   .../>

   <ImageButton
   ....
   android:layout_width="@dimen/my_button_size"
   android:layout_height="@dimen/my_button_size"
   android:layout_alignEnd="@id/my_text_edit"
   android:layout_alignRight="@id/my_text_edit"/>
   ...
</RelativeLayout>

It will limit the text to the image and the image will not overlap the text, however long the text may be.
Answer: My solution will fit all screen sizes without the editText going "behind" the imageButton. This also uses android resources, so you do not need to provide your own icon or string resource. Copy and paste this snippet wherever you would like a search bar:
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">

   <EditText
        android:layout_margin="8dp"
        android:id="@+id/etSearch"
        android:hint="@android:string/search_go"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/ivSearch"
        android:background="@color/transparent_black"
        android:padding="2dp"
        android:layout_width="wrap_content"
        android:layout_margin="8dp"
        android:src="@android:drawable/ic_menu_search"
        android:layout_height="wrap_content"
        tools:ignore="contentDescription" />

</LinearLayout>

Restult:
Comment: A bunch of thanks for your typical answer, hope in future it will help some newbies and me as well...! But I recommend to use [SearchView](https://developer.android.com/reference/android/support/v7/widget/SearchView.html)
Comment: @ArshadAli Ah yeah. That one is better.
Comment: i wasted much time in doing this. thank you. how comes android makes our life difficult in doing this kind of simple thing?
Answer: you can Use the Below Code :
android:drawableRight="@android:drawable/ic_menu_search"
Answer: How about placing it in a RelativeLayout like this ?:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText android:id="@+id/inputSearch"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Search whatever..."
            android:textSize="14dp"
            android:textStyle="italic"
            android:drawableLeft="@drawable/magnifyingglass"
            android:inputType="textVisiblePassword"
            android:theme="@style/EditTextColorCustom"/>

         <Button
            android:id="@+id/btn_clear"
            android:layout_width="14dp"
            android:layout_height="14dp"
            android:layout_marginTop="10dp"
            android:layout_alignRight="@+id/inputSearch"
            android:layout_marginRight="5dp"
            android:background="@drawable/xbutton"
            android:visibility="gone"/>
    </RelativeLayout>

Also this way you´ll be able to handle the visibility of the Button (GONE / VISIBLE) in code.
Hope it helps.
Comment: what is the style for @style/EditTextColorCustom?
Comment: Hi, it´s just a custom style for the EditText (styles.xml) and the code I use in this particular case is:
Answer: Place your EditText inside a linear layout (horizontal) and add a Image Button next to it (0 padding). Setting the background color of EditText and ImageButton will blend in.
Answer: There's solution with clickable compound drawable. It's working very well - I have tested it
SOLUTION
Answer: This is pretty simple I feel. Use relative layout as your parent layout.
Place the editText to left and ImageButton to the right using either,

alignRight property for the ImageButton
by specifying the layout weight for each of the fields
Answer: In the accepted answer the ripple effect doesn't work, it stays behind the button in the back.
This example has 2 buttons in the textbox.
The ripple effect works because the parent layout has
   android:background="@android:color/transparent"

To make sure the ripple works and doesn't stay on the back, set the imagebutton's parent background to transparent.
 <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:focusableInTouchMode="true"
            android:layout_margin="4dp">

            <EditText
                android:id="@+id/editText"
                style="@android:style/TextAppearance.Medium"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dp"
                android:layout_marginTop="2dp"
                android:layout_marginRight="2dp"
                android:background="@drawable/shape_textbox"
                android:hint="text"
                android:imeOptions="actionDone"
                android:importantForAutofill="no"
                android:inputType="text" />

            <ImageButton
                android:id="@+id/btn1"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:layout_toStartOf="@+id/btn2"
                android:background="?android:selectableItemBackgroundBorderless"
                android:src="@drawable/ic_btn1" />

            <ImageButton
                android:id="@+id/btn2"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="?android:selectableItemBackgroundBorderless"
                android:contentDescription="@string/clear"
                android:src="@drawable/ic_btn2" />

        </RelativeLayout>

Or you can also wrap your button in a frame layout:
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    >
<ImageButton ... />
</FrameLayout>

Answer: I don't know why you want to place ImageButton to achieve, which can be done with simple property of EditText

android:drawableRight="your drawable"

Can't it be work for you?
Comment: OK that may work but my need was to click on the image button and get some action done on it as well!
Answer: Use the android:drawableLeft property on the EditText.
<EditText
    ...
    android:drawableLeft="@drawable/my_icon" />

How to place button inside of EditText


NDK - Loop with JObjectArray

Question: I have a big problem.
I have a method where I catch a JObjectArray strings and populate a vector of strings, because the vector will be used in a piece of code that is reused in version for application PC.
string linha("");
for (int i = 0; i < tamanhoArray; i++) {
    jstring jLinha = (jstring)env->GetObjectArrayElement(objArray, i);
    const char * charArray = env->GetStringUTFChars(jLinha, NULL );
    if (charArray != NULL)
        linha = string(charArray);
    env->ReleaseStringUTFChars(jLinha, charArray);
    pLista.push_back(linha);
}

The method is performed several times during the execution of the application, but always at a certain point on line 13 (I got debug with "log") for the application and displays logcat "(bug app): Local reference table overflow".
Has anyone experienced this problem?
Comment: possible duplicate of [Android NDK overflows dalvik JNI local reference table](http://stackoverflow.com/questions/11079912/android-ndk-overflows-dalvik-jni-local-reference-table)
Answer: Because you do not delete local references obtained from the array:
env->DeleteLocalRef(jLinha);

Comment: damn, that was it !!
is now working!
Thank you, friend.

NDK - Loop with JObjectArray


Removing an item from a list of String and StringBuilder during for loop doesn't give the same output

Question: Can anyone explain to me the cause of these two different console outputs :
public class Test {
     public static void main(String[] args) {
         List<StringBuilder> dryFruits = new ArrayList<>();
         dryFruits.add(new StringBuilder("Walnut"));
         dryFruits.add(new StringBuilder("Apricot"));
         dryFruits.add(new StringBuilder("Almond"));
         dryFruits.add(new StringBuilder("Date"));

         for(int i = 0; i < dryFruits.size(); i++)
         {
             if(i == 0) {
                 dryFruits.remove(new StringBuilder("Almond"));
             }
          }
         System.out.println(dryFruits);
     }
}

Output => [Walnut, Apricot, Almond, Date]

public class Test {
    public static void main(String[] args) {
        List<String> dryFruits = new ArrayList<>();
        dryFruits.add(new String("Walnut"));
        dryFruits.add(new String("Apricot"));
        dryFruits.add(new String("Almond"));
        dryFruits.add(new String("Date"));

        for(int i = 0; i < dryFruits.size(); i++)
        {
            if(i == 0) {
                dryFruits.remove(new String("Almond"));
            }
        }
        System.out.println(dryFruits);
    }
}

Output => [Walnut, Apricot, Date]
Answer: StringBuilder doesn't override Object's equals. Therefore dryFruits.remove(new StringBuilder("Almond")) doesn't remove the previously added new StringBuilder("Almond") instance (which is not the same instance).
String does override equals, and therefore dryFruits.remove(new String("Almond")) removes the String instance that contains the same value.


How to change the uitextview font size

Question: can any one help to change the font size in UITextView.
[textView setFont:[UIFont fontWithName:@"ArialMT" size:30]];

I use this one but it doesn't work.
Comment: possible duplicate of [how can i set the fontSize in UITextView](http://stackoverflow.com/questions/3054600/how-can-i-set-the-fontsize-in-uitextview)
Comment: Provide more information about your textView
Answer: Have you bind textView with xib or allocated textView?
If yes,
You can use following code to check whether this works
[textView setFont:[UIFont boldSystemFontOfSize:15]];

or
 [textView setFont:[UIFont systemFontOfSize:15]];

Comment: This works, but it is really strange that font changing in storyboard has no effect.
Comment: @iMOBDEV I'd add the swift case also, it helped to me ;): textView.font = UIFont.systemFontOfSize(16.0)
Answer: Check, if "Selectable" is checked in the xib/Storyboard attribute inspector. If it's not selectable, the size wont be changed
Comment: Please fix this Apple. Making something selectable shouldn't make the font and text justification propagate.
Comment: You are the hero that we deserve.
Comment: This seems to be fixed in iOS 10. I had such a hard time figuring out why this was different in iOS 9. Thanks!
Comment: Well.. if you use the answer above (@iMOBDEV), then you can leave the Selectable unchecked and it will change the font size while not allowing the user to select the text.
Answer: Swift 4.0
textField.font = UIFont.systemFont(ofSize: 17.0)

Answer:    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
   [textView  setFont: [UIFont fontWithName:@"ArialMT" size:30]];
   textView.text = @"test my font size";
   [self.view addSubview:textView];
   [textView release];

Your code is correct. The problem is from other part of your code. Provide more details about your textView
Set custom font and size in Swift:
textView.font = UIFont(name: "ArialMT", size: 20)

Answer: Use this:
UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
myTextView.font = [UIFont fontWithName:@"arial" size:14];

Comment: Can you give some eplanation with this?
Answer: Here is for swift 3.0
textview.font = UIFont(name: textview.font.fontName, size: 18)

Answer: I tried it the same way like you with
[textView setFont:[UIFont fontWithName:kFontName size:kFontSize]];

I set the UITextView inside ViewDidLoad. My problem was, I transformed my view:
[_viewEnd setTransform:CGAffineTransformMakeScale(0.0, 0.0)];

My problem was solved with setting the properties of the UITextView after transforming my UIView which includes the UITextView.

How to change the uitextview font size


Validating a Varimax implementation?

Question: I'm writing an implementation of factor analysis and I'm having trouble convincing myself (or even better, proving) that my varimax implementation is correct. What's the best way to prove that a Varimax implementation is working properly? I can imagine two different ways; does anyone know where I can find the following:

Known good data sets. A few "known good" data sets would be a great way to prove that my implementation is working right.
Reference implementation. A reference implementation (in any language is fine, but ideally Python or Java) would be useful because then I could just generate "known good" data sets myself. I have access to SPSS, but I can't figure out how to get SPSS to just give me a Varimax rotation of a certain data set, and I'd like to isolate the Varimax transformation from other computations.

All of this is more complicated if the Varimax mapping is not one-to-one. (That is, if each unique input to Varimax has only one correct output.) If Varimax is one-to-one, then if the output of my implementation differs from the output specified by one of the methods above, then I know it's wrong. If Varimax is not one-to-one, then I can conclude that my implementation is not the same, but I can't necessarily conclude that it's wrong. Does anyone know if Varimax has only one correct output for each unique, valid input?
Thanks for your help, guys!
Answer: I got my Varimax implementation whipped into shape. Here's what I did:

I found the discussion of SPSS' implementation of Varimax in the v19 algorithms guide very useful (linked from the v19 documentation page)
I validated my unrotated solution against SPSS's unrotated solution, and then fiddled with my implementation until my rotated solution matches SPSS's rotated solution. This worked well because by checking the unrotated solution first, I was able to prove that any difference in the rotated solution was due to the Varimax implementation and no other part of the implementation. This would have been very hard to do without SPSS's documentation of the Varimax implementation, but with it the process only took about an hour.
Comment: Very willing, but unfortunately not able. The implementation belongs to my employer.
Comment: Would you be willing to share the implementation?
Comment: Gotcha. Did you ever come across other reference implementations or cleanly TeX'd up algorithms for fitting varimax besides the SPSS one?
Comment: I did not, unfortunately. However, I did find the SPSS docs very useful, for whatever that's worth!

Validating a Varimax implementation?


Countdown timer for schedule unpublish date

Question: I am using Scheduler module in order to enable unpublish date for a content type.
Now I want to create countdown timer for the nodes that unpublish date is set for them.
I checked jQuery Countdown and Countdown Timer Field modules but it seems they can't help in this issue.
What is your suggestion? Is there any way to create a relation between node unpublish date and countdown_timer modules or I must edit source of themes?
Thanks a lot for your help
Comment: Hello. Have you tried anything already? `jquery_countdown_add` of [jQuery Countdown](https://drupal.org/project/jquery_countdown) module you named in your question should be enough. What's wrong with it?
Comment: Thanks for you reply. I know that I can do this with editing html codes of tpl files. To do this I can add js files and javascript codes to the tpl file of selected node. But if I use this solution, I have to edit all theme files and this is not good. So I want to do a basic solution.
Tell me please is jquery_countdown_add is a module or it is a function?
Thanks a lot for your help.
Comment: You only need to edit tpl file of your content type and make `jquery_countdown_add` use a date from a field. For unpublished, allow everyone to see, but in tpl hide anything but timer for those who shouldn't see it yet.
Answer: You could add the snippet below as a new module scheduler_unpublish_countdown. It defines a block which you can shown on the node page of any content type you choose and allow it to countdown to the scheduled unpublish time for that node. As the block that comes with the jquery_countdown module counts down to a global event; this might be better for your use case.
<?php

/**
 * Implements hook_block_info().
 */
function scheduler_unpublish_countdown_block_info() {
  return array(
    'unpublish_countdown' => array(
      'info' => t('Scheduler Unpublish Countdown'),
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

/**
 * Implements hook_block_view().
 */
function scheduler_unpublish_countdown_block_view($delta) {
  if ($delta == 'unpublish_countdown') {
    $node = menu_get_object();
    // Ignore non-node pages, already unpublished nodes, nodes that don't have a
    // date/time set for unpublishing and nodes whose unpublishing date-time is in the past.
    if (!$node ||
      empty($node->status) ||
      empty($node->scheduler['unpublish_on']) ||
      ($node->scheduler['unpublish_on'] <= REQUEST_TIME)) {
      return;
    }
    $variables = array(
      'id' => drupal_html_id('jquery_countdown-' . $delta),
      'options' => array(
        'until' => date("F d, Y g:i a", $node->scheduler['unpublish_on']),
        'description' => ' ', // So that the CSS doesn't get screwed
        // Reload the page when the countdown is done
        'onExpiry' => '(function() { location.reload(); })',
      )
    );
    return array(
      'subject' => t('Scheduled unpublish in..'),
      'content' => theme('jquery_countdown', $variables)
    );
  }
}

Once the countdown is complete, the page will simply reload (see onExpiry option above). As unpublishing happens only either during the normal Drupal cron run or through the Scheduler's own light-weight variant, it may not happen exactly at the time of unpublishing meaning the page would reload and nothing would happen (except for the timer not showing up anymore) which might be slightly awkward.
I'd recommend, therefore, to redirect to a custom page once the countdown expires where you explicitly call _scheduler_unpublish() and then redirect back to the node page. You might want to send a one-time-only token along for security.
Remember to add scheduler and jquery_countdown as dependencies for your new module.
Comment: thanks a lot fro your solution. I will try your code as soon as possible. But I have a question. in "onExpiry" event, are we able to run cron? because after run cron, the expired node (base on unpublish date) will be hidden.
Comment: `onExpiry` is a Javascript callback - so, no, you probably won't be able to run cron but you can redirect to a custom page with a token from which you can then call `scheduler_cron()` or more specifically `_scheduler_unpublish()`.

Alternatively, you can make an AJAX request once the countdown expires to the same page (as above) and respond as you see fit.
Comment: Dear Amarnath Ravikumar.
Thanks a lot for your solution. It works fine but this block only works on node page. if you have multiple nodes (that each of them has different unpublish date) in a single page that are collected via a view this blocks can't work. Also my plan is inject the counter into view field. I created a view that collect all nodes that have unpublish date (and status is published) and there is field named "unpublish countdown" that shows seconds till timer finish date/time. Do you have any solution for this scenario? Thanks a lot in advance for your help.
Answer: Is the provided solution still operational? I've enabled it as submodule, but I don't seem to see any difference (config / display) after enabling it. Am I overlooking something that should be done before it should work?


Excel to SQL upload operations?

Question: I can fetch the data from Excel sheet to SQL Database, using File upload tool in c#.
My excel sheet & datatable have only 3 columns like name, address, phone number.
I can upload more than 5 times with same excel sheet. After this operation I am gonna open my SQL database, its shows the 3 fields are continuously adding the same table repeatedly.
my question is..

How to avoid this adding same data in same table.
How to check insert data is already exists in table or not?
Update only particular field in table, when I upload the excel sheet have any one field change.
Answer: Excel is doing this.
If you upload your data by vba function it wil refresh after row [added, deleted, filtred].
Had same issue. Make a CSV file and use SQL Coursor to add data line by line.
Answer: First upload the data to temptable , then use
the below insert ststement
INSERT INTO ActualTAble (Col1,Col2,Col3)
SELECT Col1,Col2,Col3
FROM TempTable INNER JOIN ActualTable
ON ActualTable.Col1 = TempTable.Col1
WHERE 'Give your condition if necessary'

Excel to SQL upload operations?


Q&A answers not publishing

Question: We are using Commons modules and among other parts of it a Q&A module. We noticed that when a user question is answered ,, answers do not get published. Not even when admin answers the question. Instead, we have to go in and set publishing options for all answers, one at a time.
The content type used for answers is called "Answers" and a default setting for publishing options is set to "published".
When the answer form is submitted the publishing option is not checked..
Does anyone know why this is getting overridden and how to make this work?
Thanks!
Answer: Recently I had a slightly different but similar issue with answers in commons. When a user answers a question it was by default visible to trusted contacts of that user but not visible to group members and there was no way to change that even as an admin.
After spending quite some time, I tried disabling the commons feature "Commons Trusted Contacts" which solved the problem.
So, one thing is clear it is this feature/module which is overriding. If you don't need trusted contacts functionality, you can just disable this. Otherwise, Commons trusted contacts is the right place to look into to solve the actual cause.
Answer: I think the answer you want is the patch in this issue: https://www.drupal.org/node/2399695
Comment: This looks like a link-only answer. Please explain what this link is about, and how it answers the question ...
Answer: You could look to see if there is a custom module implementing hook_from_alter or hook_form_FORM_ID_alter and overriding the default behavior. Search the code base for _form_alter in custom module directory to get started. If you could not find the what is actually overriding the default behaviors then you could implement hook_form_alter or hook_form_FORM_ID_alter and override the behavior yourself. Do something along these lines:
<yourmodule>_form_node_form_alter(&$form, $form_state) {
   // Do some checks to verify this is the content type you are targeting.
  $form['options']['status']['#default_value'] = TRUE;
}

Q&A answers not publishing


Efficiently Computing a Non-negative Solution for an Underdetermined System of Linear Equations with 0-1 Coefficient Matrix

Question: I have a system of linear diophantine equations having $m$ constraints and $n$ variables, where $n>>m$. The coefficient matrix has all entries either 0 or 1. I am interested in finding a non-negative solution to this system very efficiently. An approximate solution that satisfies the constraints with bounded error will also do. Any pointers to this problem would be really helpful.
Answer: Suppose the linear system is $Ax=b$.  You can solve the problem via mixed integer linear programming, as follows.  For each constraint $i$, introduce nonnegative surplus and slack variables $s_i$ and $t_i$, respectively.  The problem is to minimize $\sum_i (s_i+t_i)$ subject to
\begin{align}
Ax-s+t&=b \\
x &\ge 0 \text{ integer}\\
s &\ge 0\\
t &\ge 0
\end{align}
As usual with mixed integer linear programming, the linear programming relaxation provides a lower bound.  This formulation does not depend on the entries $A$ being 0-1.
Comment: Are most variables nonzero in a feasible solution? If not, you might consider *column generation*, which works with a small subset of them at a time and introduces new ones dynamically as needed.
Comment: I am not sure if this can scale to very large number of variables (say in billions). What I am interested in is that algorithm is scalable to large number of variables although a bounded error on accuracy wrt satisfiability of each constraint is tolerable.
Comment: Since number of variables is much more than the number of constraints, a basic feasible solution would have most of the variables being zero. However, in general, there can be other feasible solutions that have many nonzero variables. I am not familiar with column generation algorithm, I'd look into it. Thanks!
Comment: Sorry if my doubt is trivial, but I was wondering that to apply techniques like column generation, we do have to start with a basic feasible solution, right? In my case, all I care about is to find a feasible solution and there is no optimization function in particular. We need to find a feasible solution quickly or even a solution with bounded error.
Comment: You can start with $x=0$, $s=\max(-b,0)$, $t=\max(b,0)$.
Comment: I read about column generation using the cutting stock problem. So in that problem the columns have a nice property that needs to be satisfied which makes it easier to generate the column. For a general set of equations, generating the column may not be as obvious right? So basically what I am trying to ask is the column generation is not applicable to all sorts of problems right? The columns need to have a nice property that can be expressed as a system of constraints and also any column that satisfies those constraints, qualifies to be a column, right?
Comment: Column generation is a general technique, but its performance usually relies on exploiting structure, like in the cutting stock problem.  What does your original problem look like?
Comment: Let me explain it using an example. Say I've a large number of buckets. We want to assign certain number of balls to each bucket. Each bucket has a set of properties associated with it like color, bucket number etc. We're given some constraints like - the number of balls assigned to all red colored buckets should sum up to 1000; or the total balls present in all green and even numbered buckets is 500. We want to compute an assignment of balls to the buckets such that all constraints are satisfied.
Comment: So if we create a variable for each bucket indicating its assignment, we need a non negative integral solution to the variables such that all the constraints (always equality) are satisfied and the coefficient matrix has 0s and 1s only (indicating the inclusion or exclusion of a bucket for a given constraint).
Comment: OK, it sounds like you have one column per bucket. To use column generation, you need to be able to describe what defines a bucket: number of balls, bucket color, bucket number, and what else?
Comment: I was just giving an example. You can assume there are several features associated. Number of balls is not a feature but a variable that you have to calculate such that the constraints are satisfied. Constraints would be like sum of number of balls is equal to a given constant for the buckets where one or more features have some condition satisfied. You are right that we associate a column per bucket. For example purposes you can assume bucket features like bucket number, color, size (small, medium, large), price, seller name etc.


Get the Scan Operator when releasing documents

Question: When releasing documents the scan operator should get logged to a file. I know this is a kofax system variable but how do I get it from the ReleaseData object?
Maybe this value is hold by the Values collection? What is the key then? I would try to access it by using
string scanOperator = documentData.Values["?scanOperator?"].Value;
Answer: Kofax's weird naming convention strikes again - during setup, said items are referred to as BatchVariableNames. However, during release they are KFX_REL_VARIABLEs (an enum named KfxLinkSourceType).
Here's how you can add all available items during setup:
foreach (var item in setupData.BatchVariableNames)
{
    setupData.Links.Add(item, KfxLinkSourceType.KFX_REL_VARIABLE, item);
}

The following sample iterates over the DocumentData.Values collection, storing each BatchVariable in a Dictionary<string, string> named BatchVariables.
foreach (Value v in DocumentData.Values)
{
    switch (v.SourceType)
    {
        case KfxLinkSourceType.KFX_REL_VARIABLE:
            BatchVariables.Add(v.SourceName, v.Value);
            break;
    }
}

You can then access any of those variables by key - for example Scan Operator's User ID yields the scan user's domain and name.
Comment: Create a simple batch or index field, hide it, and set its default value to `{Benutzer-ID der Scan-Bedienungsperson}`. Then, instead of using the Kofax value, just use said field.
Comment: thanks. But I have one "problem".Kofax' language is set to german so the source name is german too. Do I really have to take the german key? This key would be `Benutzer-ID der Scan-Bedienungsperson`. So for my if statement I would have to take `if (sourceName == "Scan Operator's User ID" || sourceName == "Benutzer-ID der Scan-Bedienungsperson")` but I think this is really ugly ..
Comment: well, thanks, that's a solution. But I think they should have used english keys only :)
Comment: If you think that's bad, wait until you see their database naming conventions.


Redirect before 404 page

Question: I'm currently migrating a site to Drupal. The old site has thousands of dynamic URLs for which I cannot use a regular expression to handle them. Those URLs exist in a slightly different form in the Drupal site.
Unfortunately the URL structure is too complicated for being processed directly in a .htaccess file.
I want all the old URLs to return a 301 redirect to the new URL.
This is what I tried.

I implemented hook_page_preprocess() and sent a RedirectResponse to the new URL when the incoming URL matches the regular expression for the old URLs
I implemented an event subscriber that does basically the same on the onRequest event

In both the cases, the redirect response is sent with the following code.
$respond = new TrustedRedirectResponse($url,301);
$respond->send();
die();

Both solutions do work when the user is logged-in. In my local developing site, it works also when the user is not logged-in. On the live server, it doesn't work for anonymous users.
The funny thing is that, even when the redirection works for logged-in users, the log shows a Page not found entry for that URL. So it seems that even with the event subscriber solution, Drupal handles the 404 part first, and then executes my code.
What am I doing wrong?
Should I implement this differently?
Comment: Never use `die()` or send responses like that yourself. The event you have has a method to set a response object: Use that; see how the redirect.module does it, for example.
Comment: I tried that too. Didn't change a thing.
Answer: I stumbled upon the same issue with Drupal 8.2.6: A 404 error was recorded even though my custom event subscriber was called.
Following what suggested in comments I read about the Redirect module, I set the event subscriber priority using the following code.
public static function getSubscribedEvents() {
  // This needs to run before RouterListener::onKernelRequest(), which has
  // a priority of 32. Otherwise, that aborts the request if no matching
  // route is found.
  $events[KernelEvents::REQUEST][] = array('onKernelRequest', 34);

  return $events;
}

This fixed the issue I was having.

Redirect before 404 page