How can I understand where locate backbone file that extends from plugins?

Question: I'm new of Backbone and I wonder:
How I can understand where I must locate a file that extends from a plugin ?
Example, I want use Backbone.Modal that is a plugin for create easily modals:
https://github.com/awkward/backbone.modal
In their example they simply do:
var Modal = Backbone.Modal.extend({...})

But if I want have this file in a directory for have more controls on it, where I should place ? inside views ?
Right now I have 3 folders...
 - Collections
 - Models
 - Views
And in my backbone init file I have:
window.myApp =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}

And I can easily create a new instance of a view with new myApp.Views.myView()
I tried to add:
Modals: {}

But I can't access to my modal files anyway...how I should do ?
Answer: This library should be stored in your vendor folder, or the equivalent folder you use for storing third-party libraries - the same place where you keep libraries like backbone, underscore, jquery etc.
This library attaches Modal directly on the Backbone object and returns it which you can see right at the end of the script
Backbone.Modal = Modal;
return Backbone.Modal;

But if I want have this file in a directory for have more controls on
  it, where I should place ?

You shouldn't really be altering the code in any third-party library, but you can create an extended base version of it if you like and store it in your Views object. Something like...
myApp.Views.BaseModal = Backbone.Modal.extend({

    someCustomProperty: 123,

    someCustomMethod: function(){
        return this.someCustomProperty;
    }

});

Then any further modals you want can extend from your new base modal view...
myApp.Views.LoginModal = myApp.Views.BaseModal.extend({

    // your code for the login modal

});

Comment: Yes, I think  base modal / login modal should go in your views directory but keep the backbone.modal in your third-party libraries folder
Comment: so BaseModal or LoginModal file should be under views directory, correct ? (this was the question...where I should place my files that extends from Backbone.Modal).
Thank you for the reply.
PS: I have already my third-party libraries in rails vendor directory.


Qual o comando do Java que me retorna os caracteres maiusculos?

Question: Por exemplo, "Jorge Aragão Silva" ai me retorna "J A S"
Comment: Ainda estou em dúvida. Se é para retornar caracteres maiúsculos, então para "JOSÉ DA SILVA", teria que retornar todas as letras? Mas parece que vc quer só as iniciais do nome, então deveria ser "J D S"? Ou ainda "J S", pois geralmente o "DA" não conta como iniciais do nome. E vc manteve os espaços, então não é para retornar **somente** os caracteres maiúsculos, certo? Se puder **[edit]** a pergunta deixando mais claro o que você precisa, com mais alguns exemplos etc. Aproveite para conhecer melhor o site e como devem ser feitas as perguntas, lendo o **[tour]** e a página **[ask]**.
Comment: Dá uma olhada nesse link [aqui](http://www.guj.com.br/t/mostrar-iniciais-donome/94021)
Comment: Essas respostas [aqui](https://stackoverflow.com/a/5725949/6754506) e [aqui](https://pt.stackoverflow.com/a/193241/54152)
Comment: Agora se você quer tirar somente as iniciais de cada palavra tem esse [aqui](https://stackoverflow.com/a/28461995/6754506) e esse [aqui](https://stackoverflow.com/a/26181091/6754506)
Comment: Mas os espaços são para retirar ou incluir ?
Answer: No título da pergunta está para pegar apenas as letras maiúsculas das palavras. No exemplo no corpo do texto tem espaçamentos, mas estou com o @André Filipe.
Você pode usar expressões regulares para remover as letras não maiúsulas:
String nomeCompleto = "Jorge Aragão Silva";
return nomeCompleto.replaceAll("\\P{Lu}", "");

O método replaceAll da string no Java vai fazer a substituição de toda parte que casar com o padrão (primeiro argumento) pelo substituto. O padrão que eu passei foi \P{Lu}.

Leia mais sobre padrões

Ele consiste no padrão negado da propriedade Lu. O que isso quer dizer? Basicamente, se uma letra estiver dentro do padrão Lu, ela será ignorada; caso contrário, caso esteja em Lu, ela casará com o padrão e, portanto, sofrerá substituição.
O padrão Lu são as letras Unicode maiúsculas. Portanto, tudo que não for Unicode maiúsculo será removido.
Se eu desejasse um padrão que satisfizesse a propriedade Lu, eu usaria \p{Lu} com p minúsculo mesmo. O P maiúsculo indica que a propriedade descrita {entre chaves} será negada.
Na substituição, coloquei dois contra barras \\ por questão de como o Java trata a contra barra em strings. Então, se eu escrever \\n, o Java entenderá que eu quis digitar a string \n. Já \n o Java interpreta como quebra de linha. Para dizer explicitamente ao Java que eu desejo uma contra barra \ e um P maiúsculo, usei \\P.
Fontes que me auxiliaram:

https://stackoverflow.com/a/20661766/4438007
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-
https://stackoverflow.com/a/36312533/4438007
https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
Comment: Boa Jefferson, ótima resposta mestre!
Answer: String nomeCompleto = "Jorge Aragão Silva";

StringBuilder iniciaisEmMaiusculo = new StringBuilder();
for (char letra : nomeCompleto.toCharArray()) {
    if (Character.isUpperCase(letra)) {
        iniciaisEmMaiusculo.append(letra);
    }
}
return iniciaisEmMaiusculo.toString(); //Retornará a String "JAS"

Bons estudos!
Comment: @Ruan, esse `for` aí é conhecido como `foreach`. Esse laço do André Filipe é lido desse jeito: _"para cada caracter `letra` dentro de `nomeCompleto.toCharArray()`, faça..."_
Comment: Se não me engano, `StringBuilder` tem o método `append`, e não `add`
Comment: @hkotsubo [verdade](https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
Comment: para que serve esse char letra?
Comment: Exato @JeffersonQuesado, valeu grande!
Comment: Nesse contexto o tipo de variável char serve para pegar cada caractede do nomeCompleto.
Answer: Usando o for após o split você consegue
Dá uma olhada
 String x = "Shojibur rahman";
 String[] myName = x.split(" ");
 String saida = "";
 for (int i = 0; i < myName.length; i++) {
    String s = myName[i].toUpperCase();
    saida += s.charAt(0)+" ";
 }
 System.out.println(saida);

Espero ter ajudado
Teste rápido aqui
Answer: Exemplo simples
       String nome = "Jorge Aragão Silva".toUpperCase();
       String iniciais = "";

       for (int i = 0; i < nome.length(); i++){
            char caractere = nome.charAt(i);

            if(i == 0)
                iniciais+=caractere;

            if(caractere == ' ')
                iniciais+=nome.charAt(i+1);
        }


diagonalising (I-X(X^TX)^-1X^T where X is rank n-k, a square matrix dimension nxn, into a matrix with n-k 1 along the diagonal, and then zeros.

Question: For context, this query relates to the derivation of the distribution of the variance estimator in a linear regression. I'm doing this in a 3rd-year econometrics unit, and which takes a very matrix algebra heavy approach to all things linear regression, but given it is a unit ran by the economics department, they don't really get into the linear algebra weeds. Seeking more clarity on this particular derivation, I've gone to the textbook the course is based on, and I understand the fully rigorous (or at least I think fully rigorous) argument presented there apart from one key bit. Let $I_n$ be the n-dimensional identity matrix and $X$ be an nxk dimensional matrix with rank k. $I_n-X(X^TX)^{-1}X^T$ is seen to be asymmetric and idempotent, and it has rank n-k. Thus, I understand by the spectral theorem there exists an orthogonal matrix $P$ such that $$P^T(I_n-X(X^TX)^{-1}X^T)P=\begin{pmatrix}
    \lambda_1 & 0 & ... & ...  & ... & 0\\
    0 & ... & ... & ... & ... & ...\\
    ... & ... & \lambda_{n-k} & ... & ... & ...\\
    ... & ... & ... & 0 & ... & ... \\
    ... & ... & ... & ... & ... & ... \\
    0 & ... & ... & ... & ... & 0
    \end{pmatrix}$$
However, the book additionally asserts that there exists an orthogonal matrix $P$ such that $$P^T(I_n-X(X^TX)^{-1}X^T)P=\begin{pmatrix}
    1 & 0 & ... & ...  & ... & 0\\
    0 & ... & ... & ... & ... & ...\\
    ... & ... & 1 & ... & ... & ...\\
    ... & ... & ... & 0 & ... & ... \\
    ... & ... & ... & ... & ... & ... \\
    0 & ... & ... & ... & ... & 0
    \end{pmatrix}$$ where there are n-k 1's along the diagonal. I can only imagine it has something to do with the eigenstructure $I_n-X(X^TX)^{-1}X^T$, but I can't figure out why $I_n-X(X^TX)^{-1}X^T$ would only have 1 repeated eigenvalue which would permit this I think. Additionally, whilst trying to fill out the gaps of the derivation my econometrics lecturer gave, I came to a different result, and I can't understand what wrong with me logic, which if true would mean the distribution that is ultimately being sought would be different then if the above result holds. We know that for some n-dimensional vectors $\underline{\hat{u}}$ and $\underline{u}$ $$\underline{\hat{u}}^T\underline{\hat{u}}=\underline{u}^T(I_n-X(X^TX)^{-1}X^T)\underline{u}$$. TheN I argue given that we know this is a scalar quantity $$\underline{\hat{u}}^T\underline{\hat{u}}=\text{trace}(\underline{\hat{u}}^T\underline{\hat{u}})=\text{tr}(\underline{u}^T(I_n-X(X^TX)^{-1}X^T)\underline{u})=\text{tr}(\underline{u}\underline{u}^T)(\text{tr}(I_n)-\text{tr}((X^TX)^{-1}X^TX))=\text{tr}(\underline{u}\underline{u}^T)(\text{tr}(I_n)-\text{tr}((I_k))=(n-k)\sum_{i=1}^n u_i^2$$
what's wrong with this manipulation of the trace?
Comment: Orthogonal projectors like or $X(X^TX)^{-1}X^T$ and $I_n-X(X^TX)^{-1}X^T$ have only two different eigenvalues: 0 and 1. This is for instance proved in the Gouriéroux and Monfort textbooks (and not difficult to redo using the characteristic equation and the definition of an orthogonal projector).
Answer: Regarding the eigenvalues: note that $A = I_n - X(X^TX)^{-1}X$ is not only symmetric but also, as you've said, idempotent (i.e. $A^2 = A$). With that in mind: if $\lambda$ is an eigenvalue of $A$, then there must be an associated eigenvector $x$ (so that $x \neq 0$ and $Ax = \lambda x$), which means that
$$
\lambda x = Ax = A^2x = A(Ax) = A(\lambda x) = \lambda Ax = \lambda^2 x.
$$
So, we have $\lambda x = \lambda^2 x$. Because $x\neq 0$, it must be that $\lambda = \lambda^2$. This means that we must have $\lambda = 0$ or $\lambda = 1$.
The more general result is that if there is a polynomial $p(x)$ such that the matrix $A$ satisfies $p(A) = 0$, then it must hold that all eigenvalues of $A$ satisfy $p(\lambda) = 0$. In the case of an idempotent $A$, this holds with the polynomial $p(x) = x^2 - x$.
Regarding your manipulation of trace: it is correct to say that
$$
\text{tr}(\underline{u}^T(I_n-X(X^TX)^{-1}X^T)\underline{u})=\text{tr}[(\underline{u}\underline{u}^T)(I_n-((X^TX)^{-1}X^TX))].
$$
From there, you seem to assume that $\operatorname{tr}(\underline{u}\underline{u}^T A) = \operatorname{tr}(\underline{u}\underline{u}^T) \operatorname{tr}(A)$ (where $A$ has its earlier definition), but this does not necessarily hold.
Comment: @Bertrand It is not true that $\operatorname{tr}(u^TMu) = \operatorname{tr}(u^TuM)$. As an example, take
$$
u = \pmatrix{1\\0}, \quad M = \pmatrix{0&0\\0&1}.
$$
The statement $\operatorname{tr}(u^TMu) = \operatorname{tr}(uu^TM)$ can be proved, for instance, using the [cyclic property](https://en.wikipedia.org/wiki/Trace_%28linear_algebra%29#Cyclic_property) of trace.
Comment: If the dimensions of the matrices allow it, which is the case here, one can use the property that $tr(u^TMu)=tr(u^TuM)$ and $tr(cM)=ctr(M)$ for any constant $c$.


c variables scope

Question: if a variable is defined in a block is it present in the block only or throughout the program?
for example
main()
{
    int j=5;
    {
        int i=10
        printf("%d",i);
    }
    printf("%d , %d ",i,j);
}

is it valid
main()
{
    int j=5, *k;
    {
        int i=10
        printf("%d",i);
    }
     k=&i
    printf("%d , %d ",*k,j);
}

as variable remains in memory from the point of its declaration to the point wen function exits?
Comment: I think you'll find neither of the above fragments compiles, which will give you your answer.
Answer: A non-global variable's scope is limited to the block it's defined in.  Furthermore, for an automatic variable, once the block ends the variable's lifetime is over.
Consider this silly example:
void doit()
{
    int *ps;
    int *pa;

    {
        static int s = 1;
        int a = 2;

        ps = &s;
        pa = &a;
    }

    // cannot access a or s here because they are out of scope
    // *ps is okay because s is static so it's lifetime is not over
    // *pa is not okay because a's lifetime ends at the end of the block
}

Your second printf line will not compile because i is not in scope.
Comment: +1 because I like your wording better than @sharptooth's answer ;)
Answer: It's only accessible within the block, so in your example the second printf() is illegal and will not compile.
Answer: Yes its scope is then limited to the block where it is located.
Answer: This question also relates to your question about local scope or an auto variable.
Scope can be defined as the module within which this variable is defined.
And a module may be a function or a file.
So you can declare an auto variable in a file - which would mean it can be accessed by every function in that file, or put another way - its scope is defined to be the file in this case.
If you declare the same variable as auto, but within a function, it would mean that it can only be accessed within that function - or its scope is defined to be the function in this case.
Think of auto as 'local' within a module (where module may be a function or a file).
In the example above, you have defined the scope by adding the braces, and therefore the scope of variable i is localised to within the braces, which is why you have limited access outside the braces.
Answer: The scope of i is limited within the block where it is declared. In your case it is
{
    int i=10
    printf("%d",i);
}

Hence i is not accessible outside this scope

c variables scope


How to Implement multiple loaders in ListFragment

Question: I currently have a list fragment that loads a list of contacts from the ContactsContract.Data.CONTENT_URI using the LoaderManager.LoaderCallbacks.  I also have a sqlite table that has contacts that have been added manually into my app by the user, I am using a ContentProvider for my other table.
I would like to load both the sqlite table as well as the ContactsContract.Data.CONTENT_URI using LoaderManager callbacks but I have not been able to find any examples as to how this can be done.
Is this even possible, can some one point me to an example of how to implement this behavior?
Answer: you supply a different id for each loader you want so that you can decipher between what loader is called
getLoaderManager().initLoader(0,null,this);
getLoaderManager().initLoader(1,null,this);

then in your onLoadFinished just get the if of the loader that was called
public void onLoadFinished(Loader<Cursor> loader, Cursor arg1) {
    loader.getId()
    ....
}


What are the optimizations or goals to consider when using stratified sampling?

Question: In stratified sampling, what are the optimization considerations? For example, the sample size per stratum could be defined with proportional allocation as $n_h=n\frac{N_h}{N}$, where $N_h$ is the population size for stratum $h$, $N$ is the total population size, $n$ is the total sample size, and $n_h$ is the sample size for stratum $h$.
For a binary variable, I can choose $n$ so that my margin of error $e$ is 1%, 5% or 10%.
$$e=z_{1-\frac{\alpha}{2}} \sqrt{\frac{pq}{n}}$$
I could also choose my $n = \sum_{h=1}^H n_h$ such that the margin of error for each stratum $e_h$ is 1%, 5% or 10%.
$$e_h=z_{1-\frac{\alpha}{2}} \sqrt{\frac{pq}{n_h}}$$
But my question/concern is, how many different considerations are there and which ones are the most important ones in the context of stratified sampling?
Comment: Depends what is your goal and what constrains do you have. For example, if you have fixed sample size Neyman Allocation will allow to estimate population total with minimum variance.
Comment: Is this a duplicate account: http://stats.stackexchange.com/users/11832/jane-wayne?
Answer: There could be many optimisation goals considered, for example:

Minimise the variance for the estimator of population total under fixed sample size
Minimise the variance for the estimator of population domain total under fixed sample size
Minimise the variance for the estimator of population total under fixed survey cost
Minimise the cost of survey under fixed variance for the estimator of population total

Good reference could be Kish, L. (1965). Survey sampling. New-York: John Wiley & Sons


How to rearrange formula - Error correction models

Question: I am studying a time series subject but I am really struggling with the maths. Could someone please help me get from the first equation to the second equation? Apparently it has been reparameterised but I dont know where to start.
Thanks
Comment: Maybe it's easier to go from the bottom one to the top one
Comment: What do you think about my answer? Do you need any further clarification?
Answer: These equations are the same except for $(b_1+b_2)x_{t-1}$ vs. $-\lambda\beta_1 x_{t-1}$.
Since both equations have the same $\Delta y_t$ on the left hand side, $(b_1+b_2)x_{t-1}=-\lambda\beta_1 x_{t-1}$.
$x_{t-1}$ is a common multiplier, so you can divide both sides by it.
Then you get $(b_1+b_2)=-\lambda\beta_1$, which then immediately yields what you need.


Whatever item in a table is clicked, put that value on a hidden input

Question: I need whatever item clicked on a table to be captured and putted in a hidden input.
This is as far as I got:

var $rows = $('#table tbody tr');
$('#search').keyup(function() {
    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});
$('td').click(function() {
    var txt = $('td:first-child').text();
    $('#tipo').val(txt);
});

    Filtrar:
    <input type="text" class="form-control" placeholder="" aria-describedby="rotulo" id="search">

        1st Value

        2nd Value

        3rd Value

<input type="text" id="tipo" value="">

The problem is, whatever value I click, many items in the table are selected, even when this first item is hidden.
Jquery is being used.
Comment: Thanks stackErr, I have editted my question. Now some selection is being made
Answer: td:first-child is selecting the first child td, that's why you are always getting the first element.
The clicked element text can be retrieved by using $(this).text()
Comment: Thanks! I was so close... urgently got to take a Js course.
Answer: You can also do the following:
$('td').click(function() {
  var txt = $('.table').find('td:visible:first').text();
  $('#tipo').val(txt);
});

It will find the first visible element in the table and outputs its text.
Working fiddle here.


linq `from` clauses between generic and non-generic collections?

Question: I've these linq from clauses in a sentence:
IEnumerable<T> collection = //...;
IEnumerable<PropertyInfo> propertiesToFlat = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FlattenAttribute)));

var accessorFieldsbyLevel = from element in collection
                            from property in propertiesToFlat
                            from internalField in (IEnumerable<object>)(typeof(T).GetProperty(property.Name).GetValue(element))
                            //...

This sentence compiles. However I need to substitute the next from clause:
from internalField in (IEnumerable<object>)(typeof(T).GetProperty(property.Name).GetValue(element))

by this one:
from internalField in (IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))

So, I'm only changing (IEnumerable<object>) cast by this other one (IEnumerable).
Then the compiler tells me:

Error 1   An expression of type 'System.Collections.IEnumerable' is not allowed in a subsequent from clause in a query expression with source type 'System.Collections.Generic.IEnumerable'.  Type inference failed in the call to 'SelectMany'.

I've absolutly no idea what's happening.
What's wrong here?
[EDIT]
I suppose the problem is because collection and propertiesToFlat are a generic collections, I'm trying to set a from clause with a non-generic IEnumerable.
How could I solve that?
Comment: Can you explain why do you need to substitute?
Comment: Sometimes the collection is of `enum`-like types. So, when I try to cast it crashes.
Answer: Basically, LINQ contains very few operations which work on non-generic collections. There's no Enumerable.Where(IEnumerable, ...) for example - only Enumerable.Where<T>(IEnumerable<T>, ...).
The simplest way to fix this is to use an explicitly typed range variable in your query, which will insert a call to Enumerable.Cast<T>(IEnumerable):
from object internalField in (IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))

That's equivalent to:
from internalField in
    ((IEnumerable)(typeof(T).GetProperty(property.Name).GetValue(element))
    .Cast<object>()

Comment: Even if the "`object` types" are `enum` types?
Comment: @Jordi: Well that will end up boxing them - if you've got a better type to use as the range variable type, then yes, you should use that.


Machine Learning SVM

Question: If one trains a model using a SVM from kernel data, the resultant trained model contains support vectors. Now consider the case of training a new model using the old data already present plus a small amount of new data as well. SO:

Should the new data just be combined with the support vectors from the previously formed model to form the new training set? (If yes, then how to combine the support vectors with new graph data? I am working on libsvm.)
Or:

Should the new data and the complete old data be combined together and form the new training set and not just the support vectors of the old one?

Which approach is better for retraining, and/or is more doable and efficient in terms of accuracy and memory?
Answer: 1 and 2 both describe techniques that would be valid in various circumstances.
In (1), you're basically using a partially stacked model (holding out the "new data", by which I assume you mean additional variables not considered by the initial SVM model).
In (2), you would be applying the SVM model to the entire dataset including the new variables.
It's very difficult to say with no other contextual knowledge which of these approaches would produce "better" results for your model- it would, as always, be best to try both approaches (with proper cross-validation) to determine the "better" approach in terms of your goals.
Assuming you already have the support vectors for the initial training of the model, (1) will be much cheaper (proportionally so to the number of independent variables in the initial model) in terms of memory than (2), as the number of dimensions (variables) passed to the algorithm is comparatively lower in (1).
Comment: Consider any retraining scenario.
How will it be possible to concatenate new data with old support vectors to form a new training set? I am not clear with how to merge the two types of data here.

The other approach is simpler to do.
Comment: Correct, you wouldn't be so much combining the support vectors themselves with the new data as combining the predicted class membership $$p$$ with the new data in a stacked approach.
Comment: So, class labels from the previous prediction model and the new data form the combined data? The support vectors will be indirectly involved then, right?
Comment: Correct, though I would use the raw score rather than the labels themselves in that approach, as information is lost in the simplification.

Machine Learning SVM


Do I get charged for Azure Managed Disk if the VM is not running?

Question: The default storage when creating a new VM in Azure is managed disks. In my case I would like to create a failover VM that will be off all the time except when I need it if I need it. Do I pay for the managed disk for the time the VM is not running?
Answer: Yes, you will be charged for Azure Managed Disks. It does not matter if the VM or other resources are accessing the storage. You are paying for disk space and the service.
Managed Disks pricing
Comment: Thanks. I would have thought that they would move the data to a blob or something similar when the machine was off.
Comment: Think thru what you are suggesting. Why would they migrate your data? That is your job. Image you are a customer with a 1 TB disk and find out that it will take 30 minutes to move the data back and you are charged $0.10 per GB data transfer. Plus you will still be charged for blob storage.


Saving float changes to a float or to a varchar2 column?

Question: I need to save before and after value changes of certain fields of an items table to an items_log table. Changes are saved by an after change trigger on the items table.
Some of the items table columns are varchar2 type and some are number(*) type.
What is the better approach? Saving to separate two before and after number fields and two before and after varchar2 fields? Or conserving space by saving everything to two before and after varchar2 fields?
The purpose of this log table is to record which user changed a field and the before and after values.
Could saving a float value to a string field lead to an unexpected diversion from the original value?
Thanks in advance
Comment: The most pragmatic approach is to maintain a separate table which logs the whole  old (pre-change) record. Logging before and after values for individual columns seems attractive, but it becomes a problem when we want to reconstruct the prior state of a changed record.
Comment: What is your purpose in recording the changes? What are you going to do with them?
Answer: "What is the better approach?"
There is no "better" approach. There is only an approach that's good enough for your application. If your table will have a few thousand rows in it, it doesn't really matter. If your table will have a few million rows, then space may be more of a concern.
If your goal is to display to a user what changes occurred to your item and it's not going to see a lot of activity, storing everything as a varchar may be good enough. You probably don't want to store rows for fields that did not change.
I use APC's approach often. The items_log table is the same as the item table, and includes a history id, timestamp, action (I, U, or D), and user along with all the columns of the item row. Everything is maintained by a trigger. There are also built-in Oracle auditing features to do auditing for you.


Autenticação do Facebook

Question: Estou criando uma API e estou tentando implementar a autenticação com o Faceboook. Eis o cenário, existe 2 ambientes o front-end e o back-end, ambos estão em domínios diferentes. Ex:
Front:
http://meuappfront.com

Back:
http://minhaapiback.com

O Front vai autenticar com a SDK Javascript e enviar para o Back apenas o Token de acesso do Facebook, que por sua vez vai validar esse Token com o SDK PHP.
A minha dúvida é a seguinte:
Preciso registrar uma APP no Facebook para cada dominio? E se vai funcionar autenticar o Token de acesso em APPs diferentes?
Answer: Você pode utilizar apenas um APP e nas configurações informar os domínios em que o seu APP vai executar.
E respondendo a segunda pergunta, O Token não autentica em APPs diferentes.
Comment: Olá Thiago, sua resposta está correta. Mas será que poderia adicionar mais alguns detalhes? Da forma que a resposta esta, pode causar dúvidas ao tentar fazer o que você diz.
Comment: Claro, one sec.
Comment: Já havia resolvido com apenas uma APP, mas obrigado por responder mesmo assim.

Autenticação do Facebook


Is the space $Y=\{(a,b)\in\mathbb{R}^2:a+b\in \mathbb{Z}\}$ a connected space?

Question:
Is the space $Y=\{(a,b)\in\mathbb{R}^2:a+b\in \mathbb{Z}\}$ a connected space?

I believe the space is connected because I think the relation that $(a,b)\sim(x,y)$ if and only if $a+b \text{ and } x+y$ are not in $\mathbb{Z}$, is an equivalence relation.
So the quotient map would preserve connectedness from $\mathbb{R}^2$, But I would need to show that $\mathbb{R}^2/ \sim$ is homeomorphic to $Y$.
Answer: Your idea doesn't work in this specific case, as I'll show below. But it is a good idea. Hope you'll have a chance to make it useful elsewhere.

We prove by contradiction that $Y$ is not connected.
Let $f:Y\rightarrow\mathbb{R}$ be the function that sends $(x,y)$ to $(x+y)$. $f$ is continuous, hence if $Y$ is connected, $f(Y)=\mathbb{Z}$ would be connected, which is a contradiction.
In fact $Y$ has countably many connected components, namely the lines $x+y=n$.

The (set) quotient $A$ of $\mathbb{R}^2$ by your relation is the set $Y\sqcup\{*\}$, where $*$ is the equivalence class of all points not contained in $Y$. A non empty open set of $A$ necessarily contains $*$ (for otherwise its preimage is contained in $Y$ of $\mathbb{R}^2$, which cannot be open, except for empty set). Hence $A$ is indeed connected. $Y$, as a subspace of $A$, is also connected (there aren't many open sets to divide $Y$, you killed them all with your enormous equivalence class).

By connectedness, now we know that neither the quotient $A$ nor its subspace $Y$ is homeomorphic to $Y$.
Comment: So the set I would get in the quotient topology I proposed was $Y^c$?
Answer: Consider $f:\mathbb{R}^2\rightarrow\mathbb{R}$ defined by $f(a+b)=a+b$ it is continuous, $Y=\cup_{n\in\mathbb{Z}}U_n$ where $U_n=f^{-1}(n)$, $U_n$ are closed non empty and disjoint and $Y$ is not connected.
Comment: Dont the $U_n$ need to be open to be a separation of $Y$?
Comment: If $X$ is the disjoint union of two closed sets $A$ and $B$, $A$ is open since it is the complementary space of $B$.
Comment: My idea for using equivalence relation doesnt work, is the space I get not homeomorphic to Y?


How to split a string at every n characters or to nearest previous space

Question: I want to insert a newline character at every 15 characters including spaces.
I'm currently using the regex below which is working to some extent but it is taking me the nearest space after the word and I want the nearest previous space. Any ideas?
const split = str.replace(/([\s\S]{15}[^ ]*)/g, '$1\n');

Any ideas anyone?
Comment: Try `replace(/[\s\S]{1,15}(?!\S)/g, '$&\n')`
Comment: That works perfectly thanks! Would you mind just running me through the last group and the replace term at the end?
Comment: Also can you post it as an answer so I can mark it as done?
Comment: Your explanation was great thanks. no need for more clarification
Answer: You may use
s.replace(/[\s\S]{1,15}(?!\S)/g, '$&\n')

See the regex demo
Details

[\s\S]{1,15} - any 1 to 15 chars, as many as possible (that is, all 15 are grabbed at once and then backtracking occurs to find...)
(?!\S) - a position not immediately followed with a non-whitespace (so a whitespace or end of string).

Note that there is no need to wrap the whole pattern with (...) since you may refer to the whole match with a $& placeholder from the replacement pattern.
Comment: @ux.engineer Of course it does not work for you, because you have different requirements.
Comment: Doesn't work on, say, 20 characters long word without any spaces.
Comment: Wiktor...right, the defined requirements in this question's description are somewhat different - however the question's current title "How to split a string at every n characters or to nearest previous space" is exactly what I'm looking for. Care to update the title so I can make a new question with that title?


How to reconcile z-scores into a number from -1 to 1?

Question: I'm looking at time-series data of the GDP of the economy. I'm comparing the difference in the percent change of the GDP over the past 1 months, with the past 2 months — doing this over the course of 10 years, once for each month in the 10 years. I'm going to calculate the z-score of this difference. I want to convert the z-score that I obtain for each month in those 10 years, into a number from -1 to 1. How should I go about doing this?
Here's my thought process:

I could calculate the z-score of these z-scores. I'm not completely sure how I would be able to use this though, I feel like I'd have the same issue again.
I can just use the z-score as the value between -1 and 1. Whenever the z-score is >1, I set it =1. Whenever it's <-1, I set it equal to -1.
Comment: What properties would you like the measure to have? There are an infinite number of ways to map scores to [-1, 1], and you probably don't want to stake a fortune on making one up.
Comment: Soooooo... why?
Comment: I want to make a stock trading decision. If the value is, say 1, i will buy stocks with 100% of my portfolio. If it's -1, I'll sell 100% of my potfolio. If it's .5, I'll buy stocks with 50% of my portfolio... etc. Almost like a measure of confidence
Comment: The idea was, that if the percent change deviates strongly from the mean, then I'll make a bet one way or the other. So, I'm just trying to figure out how to use the z-score (measure of how many SD it is from that mean) to find an exact value for the bet - in this case, convert the z-score to a number between -1 and 1.
Comment: Not clear what is accomplished by transforming z score to fit into $[-1,1].$ Maybe better than your (2) is to set values below -3 to -3 and values above 3 to 3. Then divide by 3. If your data are anywhere near normal, then you'll have to "adjust" at boundaries $\pm 3$ very rarely. I did this with ten randomly simulated z-scores and rounded to 2 places, obtaining: $-0.602, -0.194,$$ -0.370, 0.338,$$ -0.054,  0.188,$$  0.549, -0.258,$$  0.535, -0.386.$ About 95\% of z scores will lie in $\pm 2/3.$
Comment: Does this answer your question? [How to reconcile z-scores into a number from -1 to 1?](https://stats.stackexchange.com/questions/482442/how-to-reconcile-z-scores-into-a-number-from-1-to-1)
Answer: Here is another, perhaps more sophisticated approach. in R, using round(2*(pnorm(z)-.5), 2) artificially adjusts nothing and spreads transformed z-scores (rounded to 2 places) uniformly in $(-1.1).$
Results from ten z-scores:  $0.49,  0.99,$$ -0.03, -0.50,$$ -0.01,  0.92,$ $-0.75,  0.83.$ $0.82,  0.26.$
z = rnorm(100)
round(2*(pnorm(z)-.5), 2)
[1]  0.49  0.99 -0.03 -0.50 -0.01  0.92 -0.75  0.83  0.82  0.26

In R, pnorm is normal CDF $\Phi.$
Before rounding $\pm 3$ gets transformed to $\pm 0.997.$ Also, $\pm2$ becomes $\pm.95.$ And $\pm 1$ become $\pm .68.$
Graph of results for 10,000 z scores.

par(mfrow=c(2,1))
set.seed(2020)
z = rnorm(10000)
 hist(z, prob=T, col="skyblue2", main="Z ~ NORM(0,1)")
  curve(dnorm(x), add=T, lwd=2, col="red")
  abline(v=-3:3, lwd=2, lty="dotted")
u = 2*(pnorm(z)-.5)
 hist(u, prob=T, col="skyblue2", main="Transformed to (-1,1)")
  curve(dunif(x,-1,1), add=T, lwd=2, col="red")
   abline(v=c(-.997,-.95,-.68,0,.68,.95,.997), lwd=2, lty="dotted")
par(mfrow=c(1,1))

Comment: If anyone is wondering why this works, it's because the CDF of a random variable is uniformly distributed. https://stats.stackexchange.com/questions/161635/why-is-the-cdf-of-a-sample-uniformly-distributed


Redirecionar para uma outra URL baseado na URL digitada

Question: O meu problema é o seguinte,
Quero adicionar /email a url que foi digitada no browser e redirecionar para essa nova url.
estou usando o IIS do windows server 2012. O site aceita mais de um Host.
Por exemplo no mesmo site eu aceito o host webmail.joao.com.br, webmail.kaina.com.br, webmail.vicor.com.br.
Queria que esse redirecionamento fosse feito adicionando-se "/emailx" ao host que foi digitado e que no endereço nao mostrace o caminho, apenas o que foi digitado originalmente.
Atualmete uso o seguinte codigo, porem só consigo redirecionar para uma unica URL:

<frame src="http://webmail.velmo.com.br/MEWebmail" frameborder="0" scrolling="no">

Comment: Seja bem-vindo ao SOpt! Por favor, considere especificar mais a sua pergunta e ter cuidado ao atribuir tags para a mesma. Pela falta de clareza na sua dúvida, fica difícil que alguém consiga lhe ajudar da melhor maneira possível.
Comment: Olá João, bem-vindo ao [pt.so]! Por favor, procure fornecer mais detalhes para podermos lhe ajudar melhor. Você falou sobre o servidor ser IIS e a linguagem Java (tag). Você tem certeza que é isso mesmo? Quais tecnologias você tem nesse servidor?
Answer: Uma forma de mostrar uma outra página dentro do mesmo domínio num frame é alterar o endereço dinamicamente via JavaScript:
Primeiro, defina um endereço em branco e um id no frame:
<frame id="webmail" src="#" frameborder="0" scrolling="no">

Depois, você pode usar uma função mais ou menos como a seguir para modificar a URL e mudar o src do frame:
function defineFrameUrl(originalUrl) {
  var frame = document.getElementById('webmail');
  if (frame) frame.src = originalUrl + "/emailx";
}

E, finalmente, você chama a função passando o endereço atual:
defineFrameUrl(window.location.href);

Comment: Grato pela atenção, testarei para ver se funciona, porem resolvi apenas com o frame mesmo e sem precisar de script java.
ao invés de colocar a URL completa
src="http://webmail.velmo.com.br/MEWebmail"

substitui pelo caminho relativo
src="./MEWebmail"

isso resolveu, uma vez que o destino esta no mesmo diretório virtual.
desculpe a confusão na minha pergunta original..


Explain Proof on Banach-Mazur distance

Question: There are two (Why?) in the proof, i think they are trivial but, I don't see why they are true.

If anyone can show me some proof of these it would be very helpful.
Definition: Let $X,Y$ two normed vector spaces, and we define the Banach-Mazur distance between $X,Y$ as $$ d(X,Y)= \begin{cases} \inf \{ \|T\|\|T^{-1}\|:T\in GL(X,Y) \}, \quad X \sim Y\\
+\infty, \quad X \not\sim Y \end{cases} ,$$
where $GL(X,Y)$ is the space of all linear isomorphisms and $X \sim Y$ means $X$ isomorphic to $Y$ .

An equivalent definition is given by the following proposition:

**Proposition:**Let $X,Y$ two isomorphic normed vector spaces, the Banach-Mazur distance between $X,Y$ is given by:
$$ d(X,Y)=\inf\{d>0,|\exists T \in GL(X,Y) : \quad B_Y \subset T(B_X) \subset d B_Y \}$$
Where
$$ B_X = \{ x \in X : \|x\| \leq1 \} \quad \text{and} \quad B_Y = \{ y \in Y : \|y\| \leq1 \} $$
Proof: Suppose $d(X,Y)<d<+\infty$. From the definition there exists a linear isomorphism  $T:X \rightarrow Y$ s.t.
$$ \|T\|\|T^{-1}\|<d$$
From the definition of a norm of an operator we have:

$a)$ For every $x \in B_X$ we have $\|Tx\|_Y\leq \|T\|\|x\|_X \leq \|T\|$ so,
$$T(B_X) \subset\|T\|B_Y \quad \text{(Why?)}$$
$b)$ For every $y \in B_X$ we have $\|T^{-1}y\|_X \leq \|T^{-1}\|\|y\|_Y \leq \|T^{-1}\|$ so,
$$T^{-1}(B_Y) \subset\|T^{-1}\|B_X \quad \text{(Why?)}$$
Or equivalently,
$$B_Y \subset \|T^{-1}\|T(B_X).$$
Lets set $S=\|T^{-1}\|T$, then, from $(a)$ we have
$$S(B_X) \subset \|T\|\|T^{-1}\|B_Y $$
and from $(b)$ we have
$$ B_Y \subset S(B_X)$$
So, there exist a $S:X \rightarrow Y$ s.t.
$$ B_Y \subset S(B_X)\subset d B_Y.$$
From the other hand, if $ B_Y \subset S(B_X)\subset d B_Y$ for a $S:X \rightarrow Y$, Then $$\|S\| \leq d \quad \text{and} \quad \|S^{-1}\| \leq 1$$
So $$d(X,Y) \leq \|S\|\|S^{-1}\| \leq 1 $$
Answer: If $y\in T(B_X)$, then there exists an $x\in B_X$ for which $y=Tx$. By the previous line, we know that $\lVert Tx\rVert_Y\leqslant\lVert T\rVert$ hence $y$ belongs to $\lVert T\rVert B_Y=\{\lVert T\rVert z,z\in B_X\}$.
For the second question, this is exactly the same argument with $X$ replaced by $Y$, $Y$ by $X$ and $T$ by $T^{-1}$.
Comment: We know that $\lVert y\rVert_Y\leqslant\lVert T\rVert$. You can check that $\lVert T\rVert B_Y=\{z\in Y,\lVert z\rVert_Y\leqslant \lVert T\rVert   \}$.
Comment: I'm sorry I can't see how from $y=Tx$ and $\|Tx\| \leq \|T\|$ you take $ y \in \|T\|B_Y$

Explain Proof on Banach-Mazur distance


PDO Exception error

Question: I am not sure why this started to show last few days.
It only happens when i try to edit content type (admin/structure/types/content_type_name) or when i want to add new content type.
Going back in browser and clearing cache moves the error away and i am able to edit or create content but the error still shows on the bottom of the page.
I can work for few minutes without interuption but then again it starts showing.
Website is live, but i have not noticed that it happens to users (anonymous or loged in), or that it breaks any part the website except adding/editing content type. (manage fields, manage display always work without errors, its just the edit content page).

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 148926721856f8ef83caa1a9.09501995 ) in lock_release_all() (line 269 of /var/www/html/includes/lock.inc).
Comment: In which server you site is host?
Comment: CentOS Linux release 7.2.1511
Answer: All you need to increase to max allowed packet. You are using CentOS, which need to configure as below within command line.
<code>nano /etc/my.cnf
max_allowed_packet = 32M
service mysqld restart
</code>
Comment: Ok, i will tell my admin to do that. Can i increase to more then 32M to skip some possible future errors ? I have 4GB total.
Comment: When a MySQL client or the mysqld server receives a packet bigger than max_allowed_packet will through this error.The largest possible packet that can be transmitted to or from a MySQL 5.5 server or client is 1GB.
Answer: Drupal doesn't connect to MySQL until the first query is sent. A request almost never takes more than a second, and usually less than half a second. If your MySQL server is timing out in that amount of time it means MySQL is misconfigured.
Please verify that you have a reasonable wait_timeout. I suspect simply increasing that will solve the problem.
This has to do with maximum allowed packet size in MySQL. To solve, this edit my.cnf: max_allowed_packet=100M and restart MySQL.

PDO Exception error


Not able to run iOS Appium tests when using node

Question: I've been running my iOS appium tests using the Appium.app without issue.
I want to try using node + appium package instead but I'm running into the error displayed below.
I've tried reinstalling node and the appium and wd packages but the issue still persists. I've allowed OSX to accept incoming connections from node as well.
No issues found with my environment using: appium-doctor --ios
Appium log:
<code>[Appium] Welcome to Appium v1.5.1 (REV c330ee9862bbc0db7d604e3b395cd1226417a9b9)
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"platformName":"iOS","platformVersion":"9.3","deviceName":"iPhone 6s","app":"/Users/User/Downloads/AppToTestSimulator.app (5).zip","autoAcceptAlerts":"false","appium_version":"1.5.1"}}
[MJSONWP] Calling AppiumDriver.createSession() with args: [{"platformName":"iOS","platformVersion":"9.3","deviceName":"iPhone 6s","app":"/Users/User/Downloads/AppToTestSimulator.app (5).zip","aut...
[Appium] Creating new IosDriver session
[Appium] Capabilities:
[Appium]   platformName: 'iOS'
[Appium]   platformVersion: '9.3'
[Appium]   deviceName: 'iPhone 6s'
[Appium]   app: '/Users/User/Downloads/AppToTestSimulator.app (5).zip'
[Appium]   autoAcceptAlerts: 'false'
[Appium]   appium_version: '1.5.1'
[BaseDriver] Capability 'autoAcceptAlerts' changed from string to boolean. This may cause unexpected behavior
[BaseDriver] The following capabilities were provided, but are not recognized by appium: appium_version.
[BaseDriver] Session created with session id: bc760657-425f-4b2a-a6a7-b0e96b3f7c01
[debug] [iOS] Not auto-detecting udid.
[BaseDriver] Using local app '/Users/User/Downloads/AppToTestSimulator.app (5).zip'
[debug] [BaseDriver] Copying local zip to tmp dir
[debug] [BaseDriver] Unzipping /var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/2016312-21862-1sug2zc/appium-app.zip
[debug] [BaseDriver] Testing zip archive: /var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/2016312-21862-1sug2zc/appium-app.zip
[BaseDriver] Unzipped local app to '/var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/2016312-21862-1sug2zc/AppToTest.app'
[debug] [iOS] Removing any remaining instruments sockets
[debug] [iOS] Cleaned up instruments socket /var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/instruments_sock
[debug] [iOS] Setting Xcode version
[debug] [iOS] Xcode version set to 7.3
[debug] [iOS] Setting iOS SDK Version
[debug] [iOS] iOS SDK Version set to 9.3
[debug] [iOS] Checking whether instruments supports our device string
[debug] [Instruments] Getting list of devices instruments supports
[debug] [Instruments] Instruments is at: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments
[debug] [Instruments] Available devices: Apple TV 1080p (9.2) [A350CABB-DB34-4933-8C8D-94BE4E695BD9] (Simulator),iPad 2 (8.4) [8FF96C8F-5BAB-4863-945C-62C92F9F7C91] (Simulator),iPad 2 (9.3) [74017AF7-1E44-4708-BA84-3BD09E5A50AD] (Simulator),iPad Air (8.4) [018AD91A-560B-475B-8E59-4633D4E4F70F] (Simulator),iPad Air (9.3) [441357FB-6D52-41E4-8AA3-682BE3A1CA03] (Simulator),iPad Air 2 (9.3) [5D925D0C-7FA2-4CEE-BE47-85E0DACFA67A] (Simulator),iPad Pro (9.3) [BADE2306-4190-44F8-A88A-21BC19137589] (Simulator),iPad Retina (8.4) [6436FE08-5493-4E95-9AB0-8CDB5EB14FC9] (Simulator),iPad Retina (9.3) [EDDB468C-EA62-443F-B273-FEC00F96FA6B] (Simulator),iPhone 4s (8.4) [DA7DF90E-7EB9-4199-ABE8-1DF2B89C593B] (Simulator),iPhone 4s (9.3) [64305631-8F8E-4DFF-BF10-6254B30C885A] (Simulator),iPhone 5 (8.4) [A2E02B24-E960-4182-8B1D-5EE633E64E4D] (Simulator),iPhone 5 (9.3) [3610DBC3-1F8E-48F3-8E86-93E2DCD28B3C] (Simulator),iPhone 5s (8.4) [385EBC18-FBEE-43D3-8A9F-ED6FB9E17D99] (Simulator),iPhone 5s (9.3) [1177F60B-F9A5-4D6E-B9E7-00F172ECB09C] (Simulator),iPhone 6 (8.4) [1CB02197-3B62-444F-B745-11884344D226] (Simulator),iPhone 6 (9.3) [F05E7BCD-1A83-4F64-8C43-9D6320116780] (Simulator),iPhone 6 Plus (8.4) [4683EB66-6644-4D3B-997B-6A417C9C7C5C] (Simulator),iPhone 6 Plus (9.3) [72630DFB-B5B1-4D79-B7C3-DAF39E1EE0F6] (Simulator),iPhone 6s (9.3) [4116EA28-E0C2-45F2-A201-22C3B1CAFBE3] (Simulator),iPhone 6s (9.3) + Apple Watch - 38mm (2.2) [D8DD477B-D5C4-4575-A83B-C5D95D40A1E1] (Simulator),iPhone 6s Plus (9.3) [7716603A-2DAE-439D-A59A-AA561C90D888] (Simulator),iPhone 6s Plus (9.3) + Apple Watch - 42mm (2.2) [A4FE07E7-4CC4-4507-AE70-E07B7EC0DE21] (Simulator)
[iOSSim] Retrieving device name string for Xcode version 7.3
[debug] [iOSSim] Getting device string from options: {"deviceName":"iPhone 6s","platformVersion":"9.3","forceIphone":false,"forceIpad":false}
[debug] [iOSSim] Fixing device. Changed from 'iPhone 6s' to 'iPhone 6s (9.3) ['
[debug] [iOSSim] Final device string is 'iPhone 6s (9.3) ['
[debug] [iOS] iOS sim UDID is 4116EA28-E0C2-45F2-A201-22C3B1CAFBE3
[iOSSim] Constructing iOS simulator for Xcode version 7.3
[debug] [iOS] No language specified. Using default strings
[debug] [iOS] Strings file not found. Looking in 'en.lproj' directory
[iOS] Could not file localizable strings file 'Localizable.strings'!
[debug] [ios-app-utils] Getting bundle ID from app
[iOS] Extracted bundleID: us.AppToTest.AppToTestPreprod from app: /var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/2016312-21862-1sug2zc/AppToTest.app
[debug] [iOS] Creating instruments
[debug] [UIAuto] Preparing bootstrap code
[debug] [UIAuto] Dynamic bootstrap dir: /Users/User/Library/Application Support/appium/bootstrap
[debug] [UIAuto] Dynamic env: {"nodePath":"/usr/local/bin/node","commandProxyClientPath":"/usr/local/lib/node_modules/appium/node_modules/appium-ios-driver/node_modules/appium-uiauto/build/lib/bin/command-proxy-client.js","instrumentsSock":"/var/folders/6v/w_s4j0fj27b1lnk8rnj0k4thvgjb4k/T/instruments_sock","interKeyDelay":null,"justLoopInfinitely":false,"autoAcceptAlerts":false,"autoDismissAlerts":false,"sendKeyStrategy":"oneByOne"}
...bug] [UIAuto] Dynamic bootstrap code: // This file is automatically generated. Do not manually modify!
[debug] [UIAuto] Dynamic bootstrap path: /Users/User/Library/Application Support/appium/bootstrap/bootstrap-f8e8ef362019f9d8.js
[debug] [UIAuto] Reusing dynamic bootstrap: /Users/User/Library/Application Support/appium/bootstrap/bootstrap-f8e8ef362019f9d8.js
[debug] [iOS] User specified default device, letting instruments launch it
[debug] [iOS] Running ios sim reset flow
[debug] [iOS] Killing the simulator
[debug] [iOSSim] Killing all iOS Simulators
[MJSONWP] Encountered internal error running command: Error: Condition unmet after 60011 ms. Timing out.
    at spin$ (lib/asyncbox.js:118:13)
    at tryCatch (/usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/regenerator/runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/regenerator/runtime.js:294:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/regenerator/runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/regenerator/runtime.js:136:37)
    at run (/usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/node_modules/core-js/library/modules/es6.promise.js:89:39)
    at /usr/local/lib/node_modules/appium/node_modules/asyncbox/node_modules/babel-runtime/node_modules/core-js/library/modules/es6.promise.js:100:28
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickCallback (node.js:349:13)
[HTTP] <-- POST /wd/hub/session 500 62780 ms - 180
</code>
Answer: I resolved the issue by reinstalling x-code and performing the 'sudo authorize-ios' command. The latter was probably the only thing that was required.
Comment: I'm having the same issue, and tried the same - I removed Xcode entirely (including command line tools, library files, etc) and reinstalled, but still have the exact same issue.

I would describe the same as you - we've been running appium tests for a year with no issues like this, but as soon as we switched to npm for appium 1.5 rather than just downloading the repo and running reset.sh for previous appium versions, suddenly i have exactly your stacktrace at exactly that point in the log

and like you, `appium-doctor` shows no issues

and like you, I've already performed `sudo authorize-ios`
Comment: I ran into this issue again after installing the iOS 9.2 simulator and trying to use it. I resolved the issue by restarting my machine and running sudo authorize-ios again. You might want to try keeping xcode closed if you still have issues.


Jenkins can not execute docker login via ssh-agent

Question: I create the Jenkins pipeline to deploy my app. I built and push docker image to AWS ECR. The final step is executing ssh to deployment server (EC2) and run docker container based on last built image.
This is my script:
stage('Deploy') {
            steps {
                script {
                    sshagent(['ssh-cridentials']) {
                        sh "ssh -o StrictHostKeyChecking=no jenkins@host sudo docker rm -f myapp"
                        sh "ssh -o StrictHostKeyChecking=no jenkins@host sudo docker image prune -a -f"
                        sh "ssh -o StrictHostKeyChecking=no jenkins@host \"cat /opt/aws/password.txt | sudo docker login --username AWS --password-stdin $ecrURI & sudo docker run -p 80:80 -d --name=myapp $imageURI\""
                    }
                }
            }
        }

However, Jenkins built fail and I got the error:
docker: Error response from daemon: Get https://xxx: no basic auth credentials.

This command couldn't login to ECR.
But it works successfully if I execute the same command on deployment server.
Comment: Does your password has special characters?
Answer: Looks like something wrong with your escape character, try without using that (I believe you have valid ecr url in variable $ecrURI)
sh "ssh -o StrictHostKeyChecking=no jenkins@host cat /opt/aws/password.txt | sudo docker login --username AWS --password-stdin $ecrURI & sudo docker run -p 80:80 -d --name=myapp $imageURI"


jQuery ajax not reaching root file

Question: I am using jQuery ajax. But everytime I make the request from page ~/profile to the page ~/send_request the request is captured at ~/profile/send_request.
here is the code
function sendRequest() {
            var id = document.getElementById("button-request").value;
            $.ajax({
                url: "send_request.cshtml",
                data: "id=" + id,
                success: function (result) {
                    $("#button-request").html(result);
                }
            })
        }

I am not able to get to the desired page. I have checked IE developer tools. From there I came to know about this issue!
Comment: Try with `"/send_request.cshtml"` instead of `"send_request.cshtml"` in `get()`
Comment: You're probably calling the profile page with a trailing slash (`/profile/`) or you have a `` tag pointing there. Try to have one canonical version and then redirect users requesting the wrong version to that. You can then adjust the path to `send_request.cshtml` accordingly (either with or without the leading `../` as in @Amith's answer.
Answer: You need to call /send_request.cshtml instead.
Comment: are you using a testing server? It should work when deployed onto a server or an environment like MAMP.
Comment: Yes, I am using my testing server, my computer! Well in case I will mark it after 5 minutes the server isn't allowing my to mark as answers!
Answer: If your .cshtml file is in the root directory use ../send_request.cshtml

jQuery ajax not reaching root file


function to return the position of a value in an array (C++, Splashkit)

Question: So I have designed an array where the user enters in five names, and the terminal will print those names and identify the longest name. I'm now trying to introduce a function where the user enters a name, and if that name is in the array, to print the position of that name (if the name is not there, print -1). I'm using the Splashkit library which is a little different. I've tried a few different variations but no luck so far. This is what I have...
int index_of(string value, string names[], int size)
{
    value = read_string("Enter name to find index: ");

   for(int i = 0; i < size; i++)
   {
       if ((names[i]) == string(value))
       {
           return i;
           write_line("The index is: ");
           write(i);
       }
   }
   return -1;
}

It compiles fine but just won't work, even when I call it in main. Does anyone have any ideas? Thanks :)
int main()
{
    #define SIZE 5
    string names[SIZE];
    int i;

    i = 0;
    while( i < SIZE )
    {
        names[i] = read_string("Enter a name:");
        i++;
    }

    for(i = 0; i < SIZE; i++)
    {
        write_line(names[i]);
    }

    int total;
    total = total_length(names, SIZE);

    write("Total length: ");
    write_line(total);

    bool has_connor;
    has_connor = contains(names, SIZE, "connor");

    if ( has_connor ) write_line("contains Connor");

    write("The longest name is: ");
    write_line(longest_name(names, SIZE));

    int index_of(int value, string names[], int size);

    return 0;
}

Comment: You are returning from the function before `write_line()` and `write()`. I think that is wrong. Also can you provide the code snippet from where `index_of()` is called?
Comment: Hi Kuro, so it's down the end of my main, I just have "  int index_of(int value, string names[], int size);  "
Comment: then can you paste the `main()` as well?
Comment: Have updated in description :)
Comment: In your code you are not calling the function `index_of()`. You may want to change the  line before return of `main()` to `int index = index_of({}, names, SIZE)`. Also I don't think you need the `value` in `index_of()` as parameter.
Comment: You can just declare `value` as local variable of `index_of()` instead of a function parameter
Comment: Inside of `main` you are declaring another version of `index_of` that takes an `int` rather than a `string` as its first parameter. I don't see where either of these are being called.
Answer: I think that these lines write_line("The index is: "); write(i); are useless because return comes before them. try
write_line("The index is: ");
write(i);
return i;

Comment: Hey I tried that and it didn't make a difference :/
Comment: then Please send me the exact output and error you are facing.


Console Access -- how does this work?

Question: My dedicated provider did the following:
wget S03HvTechAccess > /dev/null 2>&1
mv S03HvTechAccess /etc/rc3.d/ > /dev/null 2>&1
chmod 755 /etc/rc3.d/S03HvTechAccess > /dev/null 2>&1

and it shows:
/usr/bin/openvt -c 8 /bin/bash

What is openvt? It mentions you can login without a password. How does that work in terms of how do you connect to it?
Answer: openvt starts a command on a new virtual console. The command will use the STDIN, STDOUT and STDERR from the new virtual console.
Comment: A virtual console isn't a pty, is it?
Comment: Yes, Linux virtual console has is mapped to a pty device. It is the one that you can see on the physical server by pressing ALT+F1... or CTRL+ALT+F1... when in X.
Comment: Have a look at /dev/pts. There are no mapped ptys for /dev/vcs[1-6]. There are technical differences. Thus AFAIK vcs are not called ptys.
Answer: This command starts a root shell on the physical console of the server. There can be multiple virtual console sessions on the physical console - this uses virtual console number 8 (that's the "-c 8").
Because this is just a shell, rather than a login process, if someone has physical access to the console they get root access without needing a password.

Console Access -- how does this work?


Displaying a list of users with information on the number of votes in Laravel

Question: I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code:
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->char('enable', 1)->default(0);
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
....
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });
    }

Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('commentable_type');
        $table->bigInteger('commentable_id');
        $table->char('enable', 1)->default(0);
        $table->char('to_stats', 1)->default(0);
        $table->tinyInteger('rating')->default(0);
        $table->text('content');
        $table->dateTime('date_time');
        $table->ipAddress('ip');
        $table->engine = "InnoDB";
        $table->charset = 'utf8mb4';
        $table->collation = 'utf8mb4_unicode_ci';

    });

User.php:
public function userCommentsCount()
    {
        return $this->hasMany('App\Comment', 'commentable_id', 'id')->where('enable', '=', '1')->where('to_stats', '=', '0');
    }

I get my user list from this code:
    $users = User::ofRoleType($role)->withCount('commentsReceived')->paginate(50);

@foreach ($users as $user)
User id: $user->id

@endif

I need to display a list of users with the number of votes (total summary comments.rating per user) they have received.
In result I need:
@foreach ($users as $user)
    User id: $user->id has total votes: ......

@endif

I want sort my result DESC (from max to min rating votes).
How can I make it?
Answer: Try this query:
$users = User::ofRoleType($role)->withCount('commentsReceived')->orderBy('commentsReceived_count', 'desc')->paginate(50);


Vector with elements from a uniform distribution, to be made unit

Question: I have a two dimensional constant vector $\mathbf{A} = \left < 2,1 \right>$. Also, I have a vector $\mathbf{e} = \left < \epsilon_x, \epsilon_y\right >$. Both $\epsilon_x$ and $\epsilon_y$ are drawn from a uniform distribution $U(0,1)$.
There the resulting vector $\mathbf{A} + \mathbf{e}$ would be uniform too, with the $x$ component be uniform in $[2,3]$ and the $y$ component be uniform in $[1,2]$.
I want to make this vector unit. So what will happen to the distribution?
Solving for the magnitude of the vector $\left< A_x, A_y\right > + \left <e_x, e_y \right> = \left < A_x +e_x, A_y + e_y \right >$.
$M^2 = |\mathbf{A}|^2 + |\mathbf{e}|^2 + 2\mathbf{A}\cdot\mathbf{e}$
What will happen to unit vector after this?
Thanks for any help.
Answer: Call your new RVs as $X \sim U[2,3], Y \sim [1,2]$. The new vector will have elements $\frac{X}{\sqrt{X^2+Y^2}}$ and $\frac{Y}{\sqrt{X^2+Y^2}}$; call these as $Z, W$. We might be interested in marginals, but also in joint PDF, which can also be reduced down to marginals if necessary. For this, first we write the joint CDF: $$\begin{align}F_{Z,W}(z,w)&=P(Z\leq z, W \leq w)=P(\sqrt{\frac{1-z^2}{z^2}} X\leq Y, Y \leq \sqrt{\frac{w^2}{1-w^2}} X)\\ &= P(\alpha \leq \frac{Y}{X} \leq \beta) = P(\alpha\leq T\leq\beta)=F_T(\beta)-F_T(\alpha)\end{align}$$
It'll be easier if we could find CDF of $T=\frac{Y}{X}$, which is distributed in $[\frac{1}{3},1]$. Here, we need to draw a unit area square in $[2,3]$ and $[1,2]$ and examine different cases for $\frac{Y}{X}$, (It's better that you a draw while reading here).
We're going to sweep a line $Y=tX$ from x-axis to y-axis. Every time it touches a tip of the square, we have a new region to think of. There are three important cases to consider in out range: At $t=\frac{1}{3}$, line touches lower right corner of the square; at $t = \frac{1}{2}$, line touches lower left corner; at $t = \frac{2}{3}$, line touches upper right corner; and at $t = 1$, it gets out of the square. So, we have three cases: $[\frac{1}{3},\frac{1}{2}], [\frac{1}{2},\frac{2}{3}], [\frac{2}{3},1]$.
The integration of joint PDF is easy, since it is constant and $1$. We just have to find the area of the intersection of the region under the line and the square. A careful (hope so:)) analysis would lead us to:
$$F_T(t)= \begin{cases}
      0 & t < \frac{1}{3} \\
      \frac{(3t-1)^2}{2t} & \frac{1}{3} \leq t < \frac{1}{2} \\
      \frac{5t-2}{2} & \frac{1}{2}\leq t < \frac{2}{3} \\
      1-\frac{2(1-t)^2}{t} & \frac{2}{3} < t \leq 1 \\
      1 & t > 1
   \end{cases}
$$
Recall that we want to find $F_T(\beta)-F_T(\alpha)$. Of course, we need $\alpha \leq \beta$, o/w the probability was 0. So, there are $15$ legitimate cases here. It's upto you to expand this formulation into those cases, and put $\alpha = \sqrt{\frac{1-z^2}{z^2}}$ and $\beta = \sqrt{\frac{w^2}{1-w^2}}$, which is very straightforward although cumbersome. And, from here, if you really need the joint PDF, what you need to do is differentiate each of these cases with respect to $w$ and $z$, irrespective of the order.
Comment: oh my, i didn't realise it would get this much involved and contrived. Thanks for your time. Let me follow your solution first. Question: Why is $T = Y/X$ distributed in $[1/3,1]$? I do not follow the bounds.
Comment: max value of y/x is achieved ben y is max, x is min; and vice versa.


Nonclustered index functionality relative to clustered index seek

Question: the question is quite simple, but we've had so many issues with index/statistics updates not always resulting in the proper new execution plans in low-load environments that I need to check this with you guys here to be sure.
Say that you have the following tables:
<code>/*
TABLES:
TABLE_A (PK_ID INT, [random columns], B_ID INT (INDEXED, and references TABLE_B.PK_ID))
TABLE_B (PK_ID INT, [random columns], C_ID INT (INDEXED, and references TABLE_C.PK_ID))
TABLE_C (PK_ID INT, [random columns])
*/

SELECT *
FROM TABLE_A A
JOIN TABLE_B B ON B.PK_ID = A.B_ID
JOIN TABLE_C C ON C.PK_ID = B.C_ID
WHERE A.randcolumn1 = 'asd' AND B.randcolumn2 <> 5
</code>
Now, since B is joined to A with its clustered PK column, shouldn't that mean that the index on B.C_ID will not be used as the information is already returned through the B.PK_ID clustered index? In fact, is it not true that the index on B.C_ID will never be used unless the query specifically targets the ID values on that index?
This may seem like a simple and even stupid question, but I want to make absolutely sure I'm getting this right. I'm thinking of making adjustments on our indexing, since we have a lot of unused indexes which have been inherited from an old datamodel and they're taking up quite a bit of space in a DB this size. And experience has shown that we cannot fully trust the execution plans on any environment apart from the production thanks to its extreme load compared to testing environments, which makes it difficult to test this out reliably.
Thanks!
Comment: Whether an index is used depends on the queries you run.  Could you add some example queries?
Comment: That query there is an example query. And the idea that B.C_ID index will not be used is a part of the question. Since the index on that column only contains the FK_ID referencing from B to C, and that value will *never* be queried (it's just an ID value with no business / programming use aside from serving as an ID to store the relational connections), then the index should not be used either.
Answer: The query optimizer is free to do as it pleases.  It could execute the second join by scanning the C table, and for each row, looking up the matching row in B.  The index you describe would help with that lookup.
SQL Server provides statistics to tell you if an index is actually used:
<code>select  db_name(ius.database_id) as Db
,       object_name(ius.object_id) as [Table]
,       max(ius.last_user_lookup) as LastLookup
,       max(ius.last_user_scan) as LastScan
,       max(ius.last_user_seek) as LastSeek
,       max(ius.last_user_update) as LastUpdate
from    sys.dm_db_index_usage_stats as ius
where   ius.[database_id] = db_id()
        and ius.[object_id] = object_id('YourTableName')
group by
        ius.database_id
,       ius.object_id
</code>
If the index isn't used for more than 2 months, it is usually safe to drop it.
Comment: Thanks! This is great, but using the same site here: http://www.mssqltips.com/sqlservertip/1239/how-to-get-index-usage-information-in-sql-server/ shouldn't I be more interested in results from sys.dm_db_index_usage_stats ? Checking that out right now. :)
Comment: Agree that `dm_db_index_usage_stats` is better.  It shows if an index is used for reading, which is what you're looking for.  I'll update the answer.
Comment: And thanks again, this has already revealed a whole plethora of interesting things even outside of the original question. :D


BottomNavigationView não funciona no primeiro clique

Question: Estou com um problema no meu menu de avançar, ele não funciona quando clico na primeira vez, é necessário clicar duas vezes para executar a ação
bottomNavigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
@Override
public void onNavigationItemReselected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuAvancar:
            if (camposObrigatoriosWS()) {

                DatabaseHelper db = new DatabaseHelper(getApplicationContext());
                ClienteDao clienteDao = new ClienteDao();
                clienteDao.buscarUltimoID(db);
                //Verifica se quer continuar cadasto de pacote ou somente cliente
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(CadastrarClienteActivity.this);
                LayoutInflater inflater = getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.item_dialog_cadastro_cliente, null);
                dialogBuilder.setView(dialogView);

                iniciarComponentesDialog(dialogView);

                dialogBuilder.create().show();

                btnContinuar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inserirCliente("N");
                        Intent intent = new Intent(CadastrarClienteActivity.this, EscolherPacoteActivity.class);
                        startActivity(intent);
                    }
                });

                btnCadastrar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inserirCliente("S");
                        Intent intent = new Intent(CadastrarClienteActivity.this, CaixaDeEntradaActivity.class);
                        startActivity(intent);
                    }
                });
            } else {
                toastUtil.exibirToastCurtoPrazo(CadastrarClienteActivity.this, "Campos obrigatorios não informado");
            }
            break;

Answer: Isso é porque tu está usando o setOnNavigationItemReselectedListener.
Como o nome já diz, Reselect, é apenas chamado quando o item já está selecionado e é novamente clicado.
Para o seu caso, use o setOnNavigationItemSelectedListener.


docker commands not found

Question: I installed docker in Mac and it is installed successfully.
Also it is running.
And tried to execute the below command in terminal
docker -v

See the below error:
-bash: docker: command not found

How do I solve this issue.
In windows those commands are working fine.
Comment: related: https://stackoverflow.com/questions/64009138/docker-command-not-found-when-running-on-mac
Comment: why are you not accepting the answer given? Please accept it if it worked for you or clarify.
Answer: If you successfully installed docker using the official package, the command should be available under /usr/local/bin/docker.
That directory might not yet be in your $PATH, so you could try adding export PATH="/usr/local/bin:$PATH" to your .bashrc / .bash_profile.
Comment: bash is not the official termianl for mac anymore. What would the zsh version be?
Comment: that does not add it permentantly to my path...
Comment: I added more details to my answer: https://stackoverflow.com/a/71876799/1601580 thanks dorian! :D

docker commands not found


Interaction terms interpretation

Question: How do you interpret an odds ratio of an interaction between two continuous variables $x_1, x_2$? Would you fix $x_2$ and let $x_1 = x$ and $x_1 = x+1$?
Answer: Whether it's an odds ratio, or a survival analysis, or a typical continuous response variable, you don't directly interpret interaction terms.  When all covariates are categorical (i.e., in an ANOVA), you interpret 'simple effects'.  That is, the effect of a factor on the dependent variable at each level of the other factor with which it interacts.  When you have two continuous covariates, as in your case, this is a little more subtle (in that there aren't specific levels of the other covariate that are obviously the 'right' levels to condition on).  You still need to assess the association between the odds ratio and one of your covariates at pre-specified levels of the other covariate, so if there are some specific values that are salient, or particularly meaningful for some reason, you could use those.  More commonly however, you assess the relationship at the mean and +/- 1 SD of the other covariate, and interpret that.
Comment: Fix whichever one makes more sense to you to fix.
Comment: Does it matter what covariate you fix?
Comment: (+1) You've made an important point that you can't interpret the value of the interaction term in isolation - only in the context of the 'main effects'. It's also relevant to point out that one may interpret interactive effects as capturing non-linear effects of the predictors, similar to how, for example, polynomial terms in a regression model act.
Comment: @Macro: For a multiple regression model with higher order terms would it make sense to take the partial derivative to interpret the coefficients?
Comment: The partial derivative of...? It is true that, you think of the regression function as a taylor approximation of the "true" objective function (see my answer to http://stats.stackexchange.com/questions/21271/power-transformation-on-interactions-in-linear-regression/21273#21273), the coefficients of second order terms are estimates of the partial derivative of the true objective function, but I'm not sure what you mean.

Interaction terms interpretation


UISlider setMaximumTrackTintColor doesn't work in IB

Question: I have a UISlider in my window and I can't change its setMaximumTrackTintColor in Interface Builder. I set this color to one that I need, and Interface Builder's preview is ok, but on both the simulator and device this color is always RGB 183,183,183. Also, changing this value in code works good, but that behaviour is like magic for me.
Answer: Seems like this is a bug in interface builder. I'm using Xcode 6.3.1 and was able to reproduce this as well. Min Track Tint and Thumb Tint work, but Max Track Tint has no effect when running on device.


populate NSMutableArray from JSON - Empty =o

Question: I have a problem and I don't understand what is going on. It was working an hour ago and then it stopped working, I don't understand why. :s
Could you please add this JSON in a folder on your localhost and try this piece of code. Then can you tell me if your NSLOG print something better than this :
2012-05-16 11:18:21.996 WonderBox[51241:fb03] JSON : (null)

NSString *urlString = [NSString stringWithFormat:@"http://localhost:8888/WonderBox/json.txt"];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSError *err;
    NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];

    NSLog(@"JSON : %@", json);

MY JSON :
{
    "boxesDetail": [
        {
            "name": "NAME1",
            "number": "12",
            "sexe": "female",
            "topic": "Bien-être",
                   },
        {
          "name": "NAME2",
            "number": "33",
             "sexe": "couple",
             "topic": "Bien-être",
        },
         {
             "name": "NAME3",
            "number": "43",
             "sexe": "female",
             "topic": "Gastronomie",

        },
             {
          "name": "NAM  E4",
            "number": "33",
             "sexe": "couple",
             "topic": "Adventure",
        },
             {
          "name": "NAME5",
            "number": "102",
             "sexe": "group",
             "topic": "Gastronomie",
        },
             {
          "name": "NAME6",
            "number": "40",
             "sexe": "male",
              "topic": "Sport",
        },
             {
          "name": "NAME7",
            "number": "12",
             "sexe": "male",
             "topic": "Sport",
        }

    ]
}

Answer: Your JSON is invalid, use http://jsonlint.com/
there shouldn't be a comma at the end of every topic key.
{
    "boxesDetail": [
        {
            "name": "NAME1",
            "number": "12",
            "sexe": "female",
            "topic": "Bien-être" <-- there should be no comma here
        },
...

Comment: there is a coma, i found the problem :    "name": "NAM  E4", there is a space and it doesnt work.. but it is weird... WHY ? it should work with space...
Comment: found the answer... it was a tab :// sorry men !


$\dim R = n-1$ if and only if $ R\cong k[x_1,\dots,x_n]/(f) $

Question:
Let $k$ be a field and $R$ a $k$-algebra generated by $ n<\infty $ elements. Show that the following are equivalent:
(i) $R$ is a domain of dimension $ n-1 $
(ii) $ R\cong k[x_1,\dots,x_n]/(f) $ where $ k[x_1,\dots,x_n] $  is a polynomial ring and $f$ an irreducible polynomial.

I am at a loss here. Hilbert's Nullstellensatz seems like it should apply, but I'm not sure how.
Answer: Loosely speaking, this says that the dimension drops by $1$ if and only if we cut out a single equation. Note that this is false, if we drop the domain hypothesis. For instance look at $k[x,y]/(x^2,xy)$. This cannot be cut out by one polynomial, since it is not Cohen-Macaulay.

To proof your statement, note that (ii) implies (i) by Krull's principal ideal theorem.
The other direction is a consequence of two things:
(a) dimension theory of affine $k$-algebras, in particular the statement that dimension and co-dimension behave well, i.e. the height and the co-height of a prime ideal add up to the dimension of the ring.
(b) In a UFD, height one prime ideals are principal. Note that this is wrong for arbitrary height one ideals, so the proof fails without the domain assumption.
Using this, we can argue as follows: By assumption, $R \cong k[x_1, \dotsc, x_n]/I$ for some prime ideal $I$. Using (a) and $\dim R=n-1$, we get $\operatorname{height} I = 1$, i.e. $I$ is principal by (b). Hence $R=k[x_1, \dotsc, x_n]/(f)$.

Note that (b) is just a very small lemma which can be prove in two lines, but (a) is a very basic fact and one of the kickstarters of classical algebraic geometry. One has to work for this a bit and it is not trivial. One usually uses Noether normalization to show this. You can find a reference in almost any book on commutative algebra or algebraic geometry.


Difference Between Cubic Clustering Criterion, Silhouette Score, and Calinski Harabasz

Question: I am clustering a mixed geological data set containing numeric (pump pressure, bit speed, mud temperature), nominal (presence or absence of a specific stones), and ordinal data (relative concentration of minerals with 0-absent, to 4-very abundant).
My candidates algorithms are Ward, DBSCAN and BIRCH. I am looking for a good validation criterion to determine the quality of the clustering output. I have read about the Cubic Clustering Criterion, but if you look at how it works it is quite similar to that of Silhouette Score, which measure the within sum-of-squares and between-sum-of squares. It can also be observed that these two have a distinction with that of Calinski-Harabazs.
Any advice on the advantages and disadvantages among these three validation metrics, given that I am clustering a mixed data type composed of numeric, nominal and ordinal data?
Comment: You are not quite correct. CCC and CH are similar to an extent since they both are based on ANOVA idea. Sil. is its own idea. All three are for numeric data. There are criterions such as Ratkowsky-Lance or BIC clustering criterion which accept a mix of numeric and nominal data. I'm not aware of any criterion which would take ordinal type as ordinal.
Comment: Sil. actually has distance matrix as input. So, formally the distance or similarity can be any, including Gower. However, is it correct to sum Gower coefficients (classic Sil. sums them) - it is an open question.
Comment: see comparisons in https://stats.stackexchange.com/a/358937/3277
Answer: First of all, DBSCAN produces noise. And it's unclear how to correctly compute these indexes when there is noise. If you treat every noise point as its own cluster, the points will give you, e.g., a bad Silhouette, even when this is exactly the desire behavior. If you pretend noise is a cluster, the result will even be worse.
Secondly, you will first need to solve the problem of similarity measurement. If your similarity doesn't work (e.g. badly scaled) then the evaluation will prefer a bad result, too. But there is no mathematically "correct" way of scaling!


How can I get diff to show only added and deleted lines? If diff can't do it, what tool can?

Question: How can I get diff to show only added and deleted lines? If diff can't do it, what tool can?
Comment: You need to better define what you mean by added and deleted.  Specifically, can a line change?  If so, how do you want a changed line to be handled?  If you are doing strictly line oriented checking, a line changing is identical to the old line being removed and the new line being added.  For example, how should it handle a line that's split in two?  As two 1 line changed?  2 lines changed?  1 line removed and 2 lines added?  Unless you can guarantee that lines will never change, just be added and deleted, I think this is doomed to fail without better definitions.
Comment: I find the question quite unclear. But at least one interpretation of the question could be answered with `diff A B | grep '^[<>]'`
Comment: You may be looking for `comm`.
Comment: @ChristopherCashell, He means ignore sort order; a typically common problem. Usually this is done by first sorting the segments (lines) on each side before doing a typical diff.
Comment: @Pacerier, Are you sure about that?  Or are you guessing?  Nothing about sorting or search order is mentioned or hinted at in the question.  As it stands, the question isn't clear and could be interpreted many different ways.  Without knowing *for sure* what he is asking, we're making assumptions and offering solutions that may or may not solve the actual problem.  Additionally, the original poster's comment on one of the answers suggests this is *not* related to sorting.  It does have to do with the meaning of "added and deleted" vs. "changed".
Answer: Try comm
Another way to look at it:

Show lines that only exist in file a: (i.e. what was deleted from a)
  comm -23 a b

Show lines that only exist in file b: (i.e. what was added to b)
  comm -13 a b

Show lines that only exist in one file or the other: (but not both)
  comm -3 a b | sed 's/^\t//'

(Warning: If file a has lines that start with TAB, it (the first TAB) will be removed from the output.)
Sorted files only
NOTE: Both files need to be sorted for comm to work properly.  If they aren't already sorted, you should sort them:
sort a.sorted
sort b.sorted
comm -12 a.sorted b.sorted

If the files are extremely long, this may be quite a burden as it requires an extra copy and therefore twice as much disk space.
Or if you use a modern shell:
comm -12 <(sort a) <(sort b)

Comment: just wanted to add that both files needs to be sorted (case sensitive) for this solution to produce correct results
Comment: On modern enough shells, you can sort in-line with something like `comm -12 <(sort a) <(sort b)`
Comment: Wow, a new linux command, thanks. That doesn't happen much anymore.
Comment: comm first appeared in Version 4 AT&T UNIX which was released in 1973.  Other notable features of that version of Unix was that it was written in C instead of assembly language, which made it portable and greatly expanded the potential for Unix to spread.
Answer: To show additions and deletions without context, line numbers, +, -, <, > ! etc, you can use diff like this:
diff --changed-group-format='%<%>' --unchanged-group-format='' a.txt b.txt

For example, given two files:
a.txt
Common
Common
A-ONLY
Common

b.txt
Common
B-ONLY
Common
Common

The following command will show lines either removed from a or added to b:
diff --changed-group-format='%<%>' --unchanged-group-format='' a.txt b.txt

output:
B-ONLY
A-ONLY

This slightly different command will show lines removed from a.txt:
diff --changed-group-format='%<' --unchanged-group-format='' a.txt b.txt

output:
A-ONLY

Finally, this command will show lines added to a.txt
diff --changed-group-format='%>' --unchanged-group-format='' a.txt b.txt

output
B-ONLY

Answer: comm might do what you want. From its man page:

DESCRIPTION
Compare sorted files FILE1 and FILE2 line by line.
With no options, produce three-column output.  Column one
  contains lines unique to FILE1, column
  two contains lines unique to FILE2,
  and column three contains lines common
  to both files.

These columns are suppressable with -1, -2 and -3 respectively.
Example:
[root@dev ~]# cat a
common
shared
unique

[root@dev ~]# cat b
common
individual
shared

[root@dev ~]# comm -3 a b
    individual
unique

And if you just want the unique lines and don't care which file they're in:
[root@dev ~]# comm -3 a b | sed 's/^\t//'
individual
unique

As the man page says, the files must be sorted beforehand.
Answer: Visual comparison tools fit two files together so that a segment with the same number of lines but differing content will be considered a changed segment. Completely new lines between matching segments are considered added segments.
This is also how sdiff command-line tool works, which shows a side-by-side comparison of two files in a terminal. Changed lines are separated by | character. If a line exists only in file A, < is used as the separator character. If a line exists only in file B, > is used as the separator. If you don't have < and > characters in the files, you can use this to show only added lines:
sdiff A B | grep '[<>]'

Comment: `sdiff --suppress-common-lines` may be what people need; it includes `|` as well as `<`/`>` lines but it's exactly what I needed.
Answer: No, diff doesn't actually show the differences between two files in the way one might think. It produces a sequence of editing commands for a tool like patch to use to change one file into another.
The difficulty for any attempt at doing what you're looking for is how to define what constitutes a line that has changed versus a deleted one followed by an added one. Also what to do when lines are added, deleted and changed adjacent to each other.
Comment: It's been a long time since I've looked at the `diff` sources, but I seem to remember all manner of gyrations to keep track of where two files match to stay in synch and I think there's a threshold for giving up based on how far apart the lines are. But I don't remember any intra-line matching except for (optionally) collapsed white space or ignoring case. Or (perhaps) words to that affect. In any case, it's all about `patch` and "vgrep" just comes along for the ride. Maybe. On Tuesday.
Comment: My thoughts exactly. What percentage of characters in a line has to change in order to consider it a new one instead of a modification of the original? Technically even if you have one character in common, you could consider it a "change" instead of a deletion and insertion.
Comment: this is the only useful answer about what diff do, most people use it without even test it. I become crazy with the result of diff, but now I understand what this tool is for.
Answer: That's what diff does by default...  Maybe you need to add some flags to ignore whitespace?
diff -b -B

should ignore blank lines and different numbers of spaces.
Comment: No, it shows CHANGED lines as well (lines that have a character or four different).  I want lines that only exist in left or right.
Comment: You could argue that the differing versions of a CHANGED file each exist only in left or right.
Comment: There's no way for diff (or any other tool) to reliably tell what's a change, and what's a deleted line being replaced by a new line.
Comment: Technically, diff treats a "changed" line as if the original line was deleted and a new line was added...so technically it is showing you only added and deleted lines.
Answer: Thanks senarvi, your solution (not voted for) actually gave me EXACTLY what I wanted after looking for ages on a ton of pages.
Using your answer, here is what I came up with to get the list of things changed/added/deleted. The example uses 2 versions of the /etc/passwd file and prints out the username for the relevant records.
#!/bin/bash
sdiff passwd1 passwd2 | grep '[|]' | awk -F: '{print "changed: " $1}'
sdiff passwd1 passwd2 | grep '[<]' | awk -F: '{print "deleted: " $1}'
sdiff passwd1 passwd2 | grep '[>]' | awk -F\> '{print $2}' | awk -F: '{print "added: " $1}'

Comment: Note that because the difference between "a line has been modified" and "a line has been removed and *another* line has been added below or above it" is semantic. A generic text based diff tool cannot separate those cases. As a result, your sdiff based answer cannot reliably work for all cases.
Answer: I find this particular form often useful:
diff --changed-group-format='-%<+%>' --unchanged-group-format='' f g

Example:
printf 'a\nb\nc\nd\ne\nf\ng\n' > f
printf 'a\nB\nC\nd\nE\nF\ng\n' > g
diff --old-line-format=$'-%l\n' \
     --new-line-format=$'+%l\n' \
     --unchanged-line-format='' \
     f g

Output:
-b
-c
+B
+C
-e
-f
+E
+F

So it shows old lines with - followed immediately by the corresponding new line with +.
If we had a deletion of C:
printf 'a\nb\nd\ne\nf\ng\n' > f
printf 'a\nB\nC\nd\nE\nF\ng\n' > g
diff --old-line-format=$'-%l\n' \
     --new-line-format=$'+%l\n' \
     --unchanged-line-format='' \
     f g

it looks like this:
-b
+B
+C
-e
-f
+E
+F

The format is documented at man diff:
       --line-format=LFMT
              format all input lines with LFMT`

and:
       LTYPE is 'old', 'new', or 'unchanged'.
              GTYPE is LTYPE or 'changed'.

and:
              LFMT (only) may contain:

       %L     contents of line

       %l     contents of line, excluding any trailing newline

       [...]

Related question: https://stackoverflow.com/questions/15384818/how-to-get-the-difference-only-additions-between-two-files-in-linux
Tested in Ubuntu 18.04.
Answer: I find it simplest to use grep:
Added lines:
grep -xvFf filea.txt fileb.txt

Removed lines:
grep -xvFf fileb.txt filea.txt

-x: match whole lines
-v: lines NOT matching the pattern(s)
-F: treat patterns as fixed strings, not regular expressions
-f <otherfile>: read the list of patterns from a file
Answer: We can combine diff and sed to achieve what you want. lets take the same example from  https://serverfault.com/a/68717/947477
[root@dev ~]# cat file1
common
shared
unique

[root@dev ~]# cat file2
common
individual
shared

To show added lines with + and deleted lines with - we can use
root@dev ~]# diff -u file1 file2 |sed -n '/^\(+\|-\)/p'

--- a   2022-03-25 18:30:57.507551352 +0530
+++ b   2022-03-25 18:31:15.087860053 +0530
-shared
-unique
+individual

Here, -u is for printing unified content and sed will filter only outputs with - or + at the beginning.
A more straightforward answer is
diff file1 file2
< shared
< unique
---
> individual

Answer: File1:
text670_1
text067_1
text067_2

File2:
text04_1
text04_2
text05_1
text05_2
text067_1
text067_2
text1000_1

Use:
diff -y file1 file2

This show two columns for repectives files.
Output:
text670_1
                                  > text04_1
                                  > text04_2
                                  > text05_1
                                  > text05_2
text067_1                           text67_1
text067_2                           text67_2
                                  > text1000_1


How to get access to the model in the view - Symfony 2

Question: I have the following model:
class Person
{
    public $name;
    function __Construct( $name )
    {
        $this->name = $name;
    }
}

I have the following controller:
class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', $people);
    }
}

How do I get access to the model array in the view. Is there a way to access the model directly or do I have to assign a property like so:?
class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

View:
<?php
    foreach( $model as $person )
    {
       echo $person->title;
    }
?>

The problem with the above will be that it can be changed by a user to
return $this->render( 'FrameworkBundle:Navigation:index.html.php', array( "marybloomingpoppin" => $people ) );

Answer: With the example view you used, you already had the correct implementation:
class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

You mentioned the concern that somebody could change the assignment in the controller, but this is something you always have if somebody changes the name of a variable only in one place and not in all. So I don't think this is an issue.
Comment: Unfortunately my experience of changing variables extends far past this. I had called some array( "people" => $people ).. And another colleague did this with array( "users" => $peopleRepository ). When it came to the third colleague, he was utterly confused for the 2 weeks I was on holiday because this variable was different in the view (was there a separate model he was missing?) (this had happened across the entire application)... In C#.NET MVC (although you have a viewbag) everything is access by @model in the view and is to the best of its ability, not a confusion!
Comment: This is then not a technical question but a matter of taste and naming convention. I usually give lists of entities the plural name of my entity, so if I have an array of Users I call it array('users' => $whateverVariable) so that at least in the view the acces to a List of users is always the same.
Comment: @moc it's a programming question... I don't know how to do it another way, what's the code. I don't have a care about naming conventions, I didn't ask if it was a better way, I asked how to do it. this is completely a programming question.
Comment: Then I unfortunately don't understand the question. Because the code that should work was already provided by you. And that is what I tried to pointed out. Besides that I don't understand the question :(


When to use what inverse trig?

Question: When do I use $\arcsin$ and when do I need to include all of the outcomes? My gut feeling is if you have an equation like $\sin(x)=0$, then $x=0,\pi,2\pi...$ whilst if you are using it in integration and any other situation you use $\arcsin$.
Is this correct if either way why?? thanks
Comment: elaborate a little more? give an example.
Comment: What do you mean by "using it in integration" and how is it different?
Comment: If were for example using trig substitution e.g. x=sin(u) and in the final answer we got a u by itself we would put u=acrsin(x) in its place would we not? what other situations does this occur in?
Comment: Likewise sometimes we use sin=(+/-)(1-cos^2)^0.5 and others just  sin=(1-cos^2)^0.5 are there any rules of when we use the one-to-one functions and many-to-one (as i think they are called)
Answer: Usually, arcsin(x) is defined as the number y in the range $[-\frac{\pi}{2},\frac{\pi}{2}]$ with the property $sin(y) = x$. With this restriction,
the inverse of sin(x) is well-defined. Solving the equation sin(x) = 0 is
something else, here you do not restrict the range of the possible values,
and you get infinite many solutions.
If arcsin(x) occurs in an integral, the definition I described
should be meant.
Comment: In general do we use the many values version only when solving equations, otherwise we use acrsin etc??
Comment: Yes, I would say so.

When to use what inverse trig?


How to obtain a power curve from a likelihood ratio test for linear regression as a function of varying a coefficient of the more complex model?

Question: I am currently doing a test of model complexities for two linear regression models:
First Model:
$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon$
vs.
Second Model:
$Y = \beta_0 + \beta_1X_1 + \epsilon$
and am using the lrtest function in R to do it. I would like to draw a power curve where the x-axis varies the values of $\beta_2$. The y-axis would report the power of the test at each value of $\beta_2$. Power is defined as the probability of rejecting the null when the null is false with the null being that the two models are the same.
I am wondering how I might be able to do such a test and if it can be done using the lrtest function.
Answer: Maybe you can follow my idea presented here Power Analysis for a mixed two-way ANOVA with unqual sample sizes.
You need to generate the data according to the first model.
Need to specify the following: 1) sample size, 2)$\beta_0$ and $\beta_1$, 3)$Var(\epsilon)$, 4)structure of $X_1$ and $X_2$, especially their correlation, and 5)$\alpha$ level.
Of course, you need the several different values of $β_2$ for x-axis.