Como abrir um arquivo ao ser clicado em uma aplicação java?

Question: Fiz uma aplicação em Java e quero abrir um determinado tipo de arquivo nele, como ocorre com o NetBeans, ou seja quando uma pessoa clica no arquivo ".java " ele abre no NetBeans( ou em outra IDE que aceite esse tipo de arquivo).
Contudo, mesmo que eu configure o arquivo para abrir na minha aplicação, ao ser aberto, não aparece o conteúdo dele na minha aplicação.
Há algum comando em java para fazer isso ?
A+
EDITED :
É bem por ai, mas não estou conseguindo bem fazer isso. Sei como abrir um arquivo ( já tenho um método para isso), mas não consigo chama-lo dentro passando o path pois dá erro.
segue o código:
<code>// essa é uma das minhas classes ,é ela que é chamada e possui todos os componentes visuais
public static void main(  String args[]) {

public void run() {
                new Programa().setVisible(true);
                  if(args.length > 0) {
                        try {
                      MetodoAbir(args[0])

            }catch(Exception erro) {

            }

        }
</code>
Mas da  erro diz que o método não pode ser "refenrenciado por static contex". Isso ocorre até se eu colocar um método sem parâmetro, ou seja não consigo chamar os métodos ali. Também tentei criar uma variável global e jogar o valor args[0] nela para passar para o método em outro local  mas também da o mesmo erro.
Comment: Adicione o código responsável por esta execução, clicando em EDITAR na pergunta.
Comment: Você quer configurar seu programa como padrão no windows, ou quer executar alguma aplicação dentro dele? Não está claro isso na pergunta.
Comment: Eu configurei ele como padrão. Quero executar algo dentro dele, mas quando clico no arquivo a aplicação abre mas não mostra o conteúdo do arquivo.
Comment: Você provavelmente esta recebendo o caminho do arquivo como parâmetro, mas não esta fazendo nada com ele.
Comment: Como assim, no código   eu tenho que fazer uma verificação para saber se alguém clicou externamente em um arquivo quando abrir  a aplicação ? Se sim, como faço isso ?
Comment: @diegofm , é isso que eu estou querendo saber como verificar se algum arquivo foi clicado externamente para abri-lo na aplicação. Só sei fazer  isso usando o jfilechooser .
Comment: O que você já fez até agora? Adicione isso na pergunta, sua duvida já sabemos, agora você precisa mostrar onde quer colocar isso e como está o código atual onde você quer adicionar este recurso.
Answer: Ao abrir a aplicação você tem de checar se não foi passado parâmetros para seu
programa.
<code>import java.io.File;

public class SeuPrograma {
    public static void main(String[] args) {
        if(args.length > 0) {
            File file = new File(args[0]);

            // Abra seu arquivo
        }
    }
}
</code>
Comment: O principal você não disse, que é como abrir o arquivo.
Comment: Penso que o principal é estar ciente de que tem um arquivo chegando via linha de comando. Como abrir depende da logica do programa dele que eu não sei qual é. Pode ser um arquivo de texto, um zip, uma imagem, etc.
Comment: Mas a duvida justamente é *"Como abrir um arquivo ao ser clicado em uma aplicação java"* e a resposta não explicou nada disso. Eis o problema em se responder perguntas cuja a duvida não ficou clara o suficiente.
Comment: Edição feia na pergunta.
Comment: Agora fiz do jeito certo. Quando chama a classe principal passo como parâmetro o args para um construtor que recebe esse parâmetro da outra classe e depois faço o processo para abrir. Tá tudo certo, mas mesmo assim não aparece nada quando clico para abrir um arquivo . É como  se não tivesse passando nada quando clico em um arquivo.
Comment: Exiba uma mensagem com os parâmetros que seu programa esta recebendo e veja o que ocorre.


how to do live update or synchronized in vba

Question: how to do live updates to one cell to another cell?? I don't know, is it call synchronized or live updates, what im trying to do, i want my cell to update to another sheet, if i change something or values in sheet1 cell 1 then sheet2 cell 1 should change it automatically.. any1 have any ideas ????do i have to do live change or live updates or its a synchronizing or how do i code it, i never did anything like that before.....
<code>sub worksheet_change()
    if sheets("sheet1") = sheets("sheet2") then
        do liveupdate
    end if
end sub
</code>
Comment: you mean use a formula? like `=Sheet1!A1`
Answer: DDE
If it's on the same computer, you can do something called DDE and make DDE based functions.
DDE is an old but still very well used technology (especially in the financial industry) which stands for Dynamic Data Exchange. That will enable you to control values in the cells of one worksheet from code driven through another.
Search for DDE examples, DDE MSDN, etc. and you'll find tonnes of simple examples out there.
DCOM ??
For a while, MSFT wanted to extend DDE and similar technologies across networks, like Distributed COM but security issues got in the way and common sense prevailed.
RTD:
A bit more involved and better (IMHO) method is creating a simple RTD server (Real Time Data Server) that reads data from your sheet, and pumps it across a network or simply to another instance of Excel on your computer.
Either of these methods can be used to distribute live stock feeds, etc. coming onto expensive subscription terminals across a network (be aware of the licensing issues though for spreading any data around using these techniques).
RTD information can also be found with simple examples to set up an RTD server scattered across google search results.
Hope it was helpful.


KNN(k-nearest neighbor) algorithm as supervised and as unsupervised algorithm. What are the main differences? How can it be both?

Question: On internet and in articles KNN ist mostly described as supervised algorithm. But recently I have find also few articles where it is mentioned as unsupervised algorithm.I cannot find articles that are reviewing/comparing both of them. Can you recommend someliterature/articles where I could read more about it? Can you explain how can KNN be both? What are the differences?
Comment: [sklearn.neighbors.NearestNeighbors - knn for unsupervised learning?](https://datascience.stackexchange.com/questions/34061/sklearn-neighbors-nearestneighbors-knn-for-unsupervised-learning)
Comment: [Sklearn: unsupervised knn vs k-means](https://datascience.stackexchange.com/questions/34073/sklearn-unsupervised-knn-vs-k-means?rq=1)
Comment: [K-nearest neighbor supervised or unsupervised machine learning?](https://stats.stackexchange.com/questions/363669/k-nearest-neighbor-supervised-or-unsupervised-machine-learning)
Answer: The $k$-nearest neighbors supervised learning algorithm works by taking a point, calculating the distance in the feature space (predictors) between that point and all other points, determining the $k$ points that are closest, and using the labels ($y$) on those points to make a prediction. That prediction might be an average in order to do a regression. It might be the category with the most representation among those $k$-nearest neighbors. It might be a probability based on the relative number of categories represented in those $k$-nearest neighbors.
The key point, however, is that there is a feature space for calculating distances and then a target space of the variable(s) being predicted. This is exactly a supervised problem.
One unsupervised machine learning clustering algorithm is called "k-means", which you notice has a similar but distinct name. The gist here is that the distance between points and the cluster mean are calculated in order to assign points to clusters. However, there is no target space, and this is not a supervised method.
A place where $k$-nearest neighbors could be used in an unsupervised way if if you just want to know the $k$-nearest neighbors in the feature space. This could be used, for instance, for some kind of matching procedure.


Infinispan Clustering: Replication of entries loaded by a CacheLoader

Question: Sorry, wall of text; there's a summary at the bottom.
I am prototyping a Java application that will run on multiple servers. Every instance has an embedded Infinispan cache and the caches are configured to form a cluster in replication mode. The cache entries are loaded from an external system only - there is no need for actively adding entries using cache.put(key, value).
For that purpose, I implemented a custom CacheLoader. Loading values on-demand is working, but these entries are not replicated to other active cluster nodes. For test reasons, I tried adding entries with 'put' - these are replicated immediately.
The user guide pointed me to properties that affect cluster behavior when nodes are joining/leaving the cluster, or during writes, like fetchPersistentState, shared and fetchInMemoryState. The latter is useful in my case, since new nodes joining the cluster should receive the current state. And this initial synchronzation during startup is even fetching the entries loaded by the cache loader.
fetchPersistentState caused errors because my cache loader does not implement AdvancedCacheLoader - but since the advanced methods do not seem to be called after an invocation of 'load' I do not think that correctly implementing that interface would solve my problem.
I have also read about the ClusterLoader implementation that

consults other members in the cluster for values

but a roundtrip to the other nodes would increase response times while processing requests.
The rationale behind trying to load the value exactly once is that calls to the shared external system are considered to be rather expensive, so that the increased cluster-overhead created by replication messages should still be less problematic than loading the values on every node.
In order to have some kind of isolated test and code samples for this I forked the infinispan-quickstart/clustered-cache example on Github and adapted it to my needs:
https://github.com/flpa/infinispan-quickstart/tree/master/clustered-cache
The cache is backed by a CacheLoader now and nodes are periodically fetching/putting values to demonstrate how 'put' values are replicated but values fetched from the loader are not.
To sum this up:
Is it possible to configure an Infinispan cluster in replication mode that is populated entirely by cache loader lookups and replicates the results of those lookups on all nodes?
EDIT: I accidentally deleted the Github fork, so I recreated it from scratch including only the relevant 'clustered-cache' folder and adapted the link above.
Answer: I am afraid that out-of-the-box configuration options are not available. However, you can register listener on each node for the @CacheEntryLoaded event and in this listener execute putAsync(). Be sure to include flags SKIP_CACHE_LOAD, SKIP_CACHE_STORE and IGNORE_RETURN_VALUES to get the best performance.
Comment: Thanks Flavius, I implemented this solution in my test app and it's working. It'll probably take some time until I can test this in a real-life environment but I'll just accept the answer right away.


Getting error while pip installing tensorflow on Windows

Question: I tried installing tensorflow like this - pip install tensorflow but I get this error
ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR: No matching distribution found for tensorflow

So then, I tried adding in the version as well pip install tensorflow==2.2 but no luck. I tried version 1.15 as well but I still got the same error.
ERROR: Could not find a version that satisfies the requirement tensorflow==2.2 (from versions: none)
ERROR: No matching distribution found for tensorflow==2.2

As for using the pip3 install tensorflow. That didn't work as well, giving the same error.
ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR: No matching distribution found for tensorflow

OS - Windows 10
Python Version - 3.8.5
Pip is up-to-date
Answer: I installed using python3 -m pip install --upgrade tensorflow.
Don't ask me how.


Same Javascript Variable works only when manually entered in

Question: I've been working on a script to take text from one div on a page and enter it into another. I came across a strange problem. When I alert my FillinId variable I come up with questionTextF. However, when I try to use that value in my next variable, GrabFillinDiv, the value comes back null. If I manually enter in questionTextF instead, everything works. I can't do it this way though, because there are multiple FillinId's to grab content from.
Here's a JSFiddle:
http://jsfiddle.net/hzbdhxvs/
Here's my Javascript:
$(document).ready(function(){
            var QuestionTypeName = "MultipleListQuestion-test";
            var FillinDivParent = document.getElementById(QuestionTypeName);
            var FillinDivChildren = FillinDivParent.getElementsByTagName("div");

            for (i=0; i< FillinDivChildren.length; i++){
                var FillinId = $(FillinDivChildren[i]).attr("id");
                alert(FillinId);
                var TplId = FillinId.slice(0,-1);
                var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
                var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();
                alert(GrabFillinDiv.innerHTML);
                $("\"" + "#"+ TplId + "\"").html(GrabFillinText);

             }

        });

Comment: Note that, by usual convention, only constructors should begin with uppercase.
Comment: If you are using jquery, why don't you use it???
Answer: You are adding some quotes before and after the id. Don't do that:
for (i=0; i< FillinDivChildren.length; i++){
    var FillinId = $(FillinDivChildren[i]).attr("id");
    alert(FillinId);
    var TplId = FillinId.slice(0,-1);
    var GrabFillinDiv = document.getElementById(FillinId);
    var GrabFillinText = $("#"+FillinId).html();
    $("#"+ TplId).html(GrabFillinText);
}

var QuestionTypeName = "MultipleListQuestion-test";
var FillinDivParent = document.getElementById(QuestionTypeName);
var FillinDivChildren = FillinDivParent.getElementsByTagName("div");

for (i=0; i< FillinDivChildren.length; i++){
    var FillinId = $(FillinDivChildren[i]).attr("id");
    alert(FillinId);
    var TplId = FillinId.slice(0,-1);
    var GrabFillinDiv = document.getElementById(FillinId);
    var GrabFillinText = $("#"+FillinId).html();
    $("#"+ TplId).html(GrabFillinText);
}

  <form role="form">

          <input id="ResponseCheckBox" type="checkbox" value=""/>

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

        <input type="text" id="ResponseOtherSpecifyText" class="form-control-inline care-multipleSelect-otherText" />

  </form>

Which categories best describe your racial background? (Please choose all that apply)

test

        American Indian or Alaskan Native

Answer: Get rid of the "\"" insertions. Instead of
var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();

Try:
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+ FillinId).html();

http://jsfiddle.net/hzbdhxvs/1/


ENOENT: no such file or directory - error in pug

Question: When uploaded to Heroku, it is throwing me this error, while no error when running at localhost.
Here is browser message:

Here is my display.pug
extends ../LoginLayout/LoginLayout.pug
block content

- var createdAt = requser.local.profile.createdAt
script(type="text/javascript").
    $(document).ready(function() {
        var createdAt = Date.parse('!{createdAt}');
        //- console.log(createdAt);
        $('.memberSince')[0].innerHTML = moment(createdAt).fromNow(true);
    });

.parallax-container.display
    .parallax
        img(src=requser.local.profile.herobg)
    .container.white-text.center
        img.circle(src=requser.local.profile.dp style='width: 200px;')
        h1 #{requser.local.name}
        h6 Member since #[span.memberSince #{createdAt}] | Lives in #{requser.local.profile.location} | #[strong 232222] points
        a.btn.btn-large.blue.darken-3.waves-amber.waves-effect.white-text(href='#') #[i.fa.fa-user-plus.left] Follow

Answer: I solved this myself.
My file hierarchy:

and I was using:
extends ../LoginLayout/LoginLayout.pug instead of extends ../loginLayout/loginLayout.pug. notice the login starts from small letter as it was stored.


using events in deSolve to prevent negative state variables, R

Question: I am modeling the population change in a food web of species, using ODE and deSolve in R. obviously the populations should not be less than zero. therefore I have added an event function and run it as below. although the answers change from when I did nlt used event function, but it still producds negative values. What is wrong?
#using events in a function to distinguish and address the negative abundances
eventfun <- function(t, y, parms){
    y[which(y<0)] <- 0
    return(y)
}

# =============================== main code
max.time = 100
start.time = 50

initials <- c(N, R)

#parms <- list(webs=webs, a=a, b=b, h=h, m=m, basals=basals, mu=mu, Y=Y, K=K, no.species=no.species, flow=flow,S=S, neighs=neighs$neighs.per, dispers.maps=dispers.maps)
temp.abund <- ode(y=initials, func=solve.model, times=0:max.time, parms=parms, events = list(func = eventfun, time = 0:max.time))

and here is the ODE function(if it helps in finding the problem):
solve.model <- function(t, y, parms){

y <- ifelse(y<1e-6, 0, y)
with(parms,{
    # return from vector form into matrix form for calculations
    (R <- as.matrix(y[(max(no.species)*length(no.species)+1):length(y)]))
    (N <- matrix(y[1:(max(no.species)*length(no.species))], ncol=length(no.species)))

    dy1 <- matrix(nrow=max(no.species), ncol=length(no.species))
    dy2 <- matrix(nrow=length(no.species), ncol=1)

    no.webs <- length(no.species)
    for (i in 1:no.webs){

        species <- no.species[i]
        (abundance <- N[1:species,i])

        adj <- as.matrix(webs[[i]])
        a.temp <- a[1:species, 1:species]*adj
        b.temp <- b[1:species, 1:species]*adj
        h.temp <- h[1:species, 1:species]*adj

        (sum.over.preys <- abundance%*%(a.temp*h.temp))
        (sum.over.predators <- (a.temp*h.temp)%*%abundance)

        #Calculating growth of basal
        (basal.growth <- basals[,i]*N[,i]*(mu*R[i]/(K+R[i])-m))

        # Calculating growth for non-basal species D
        no.basal <- rep(1,len=species)-basals[1:species]

        predator.growth<- rep(0, max(no.species))
        (predator.growth[1:species] <- ((abundance%*%(a.temp*b.temp))/(1+sum.over.preys)-m*no.basal)*abundance)

        predation <- rep(0, max(no.species))
        (predation[1:species] <- (((a.temp*b.temp)%*%abundance)/t(1+sum.over.preys))*abundance)

        (pop <- basal.growth + predator.growth - predation)

        dy1[,i] <- pop

        dy2[i] <- 0.0005 #to consider a nearly constant value for the resource

    }

    #Calculating dispersals .they can be easily replaced
    # by adjacency maps of connections between food webs arbitrarily!
    disp.left <- dy1*d*dispers.maps$left.immig
    disp.left <- disp.left[,neighs[,2]]

    disp.right <- dy1*d*dispers.maps$right.immig
    disp.right <- disp.right[,neighs[,3]]

    emig <- dy1*d*dispers.maps$emigration
    mortality <- m*dy1

    dy1 <- dy1+disp.left+disp.right-emig

    return(list(c(dy1, dy2)))
})
}

thank you so much for your help
Answer: I have had success using a similar event function defined like this:
eventfun <- function(t, y, parms){
  with(as.list(y), {
    y[y < 1e-6] <- 0
    return(y)
  })
}

Answer: I am using a similar event function to the one posted by jjborrelli. I wanted to note that for me it is still showing the ode function returning negative values. However, when ode goes to calculate the next step, it is using 0, and not the negative value shown for the current step, so you can basically ignore the negative values and replace with zeros at the end of the simulation.


Is there any significance to complex function "monotone in norm?"

Question: So, I was reading a question earlier where someone asked if something would be strictly monotone in the complex plane, and the comment was that this would be meaningless, since the complex numbers aren't an ordered field.
What came to mind was a concept in my head of "monotone in norm".   This would be something of the sort $\forall x,y\in \mathbb C,\|x\|<\|y\|\implies \|f(x)\|<\|f(y)\|$.
Is this a meaningful property for complex functions?  My complex analysis is...pretty sparse, alas.
Comment: In the converse sense, there are several interesting *analytic* functions for which this is true. For example, all polynomials are eventually monotone in norm.
$$\left.\right.$$
This is probably pedantism, but if you didn't mean to restrict your focus to analytic functions, functions of ``monotone norm'' aren't in themselves very interesting or restrictive. They could do anything. For instance, take a natural log function that is nowhere continuous (which you can construct using two or more branches). This isn't a very nice or interesting function, but it has your property.
Comment: (nonconstant polynomials..)
Comment: @enthdegree No, polynomials other than $z^n$ are not monotone in norm. Also, why so much whitespace?
Answer: The only holomorphic functions that have this property are monomials $cz^n$. Indeed, the property implies (by continuity) that $|x|\le |y|\implies |f(x)|\le |f(y)|$, which in turn yields $|x|=|y|\implies |f(x)|=|f(y)|$. So, for every unimodular constant $\zeta $ the function $f(\zeta z)/f(z)$ has constant modulus, hence is constant. So,  $f(\zeta z)\equiv c(\zeta) f(z)$ from where, comparing the Taylor coefficients, we can conclude that at most one term of the Taylor series can be nonzero.
If we consider non-holomorphic functions, then it's more natural to look at real-valued functions. For them, the property you described is known as being a "radial[ly] increasing function". They are sometimes used for radial basis function approximation. However, they are not nearly as common as their decreasing counterparts, which are used all the time as mollifiers (and also for RBF approximation).


Content Type with People (list of people) in Select List to Choose From

Question: diving deep into Drupal 7 as a noob and wondering how can I create a field (select list) in a new content type that pulls in all the users in the system? I'd like to be able to associate certain content with a person, not necessarily as the author, but as the "person in charge of this area" for example. I'd like to show the persons name and some other info from the "people" area of the Drupal 7 core.
I am thinking I should use the people area rather than create a new content type for people. I added new fields to the "new user" form.
Any thoughts or ideas?
EDIT:::
Did find https://drupal.org/project/references module that seems to work great. However, I still would like to know if using People area is best for storing all users / people associated with my Drupal site. Thanks :)
Answer: Personally I often use Entity Reference, but I think this answer is the same regardless of the choice between Entity Reference and References modules. Both modules allow you to define a relation between two entities. If you need a reference from a node to another entity, this is a good solution.

I still would like to know if using People area is best for storing all users / people associated with my Drupal site.

When you say "People area", I think you mean Drupal's built-in user management. Users are fieldable entities, just like nodes. If you need to store data about a person, you can use both the user entity or define a "Person" node type. If the persons you're adding should be able to log in, now or in the future, you definitely want to create users. If they will never need to log in (for instance, you're building a site about people in ancient Rome), I would choose nodes.
Comment: Entity Reference is a killer module. WOW. I've done just what I needed with it. Thanks!
Comment: Thanks for the reply! I would like the ability for them to login possibly, so I'll keep going about it with the built in user-management area. The user reference module doesn't give me the persons first / last name... only their username. I'll give the entity reference a shot!
Comment: Entity Reference lets you use a view as source for the select box, and you can use the fields on that view to control which label the user will see. If you must, you can even go more advanced with a module like [Entityreference view widget](http://drupal.org/project/entityreference_view_widget), see also http://drupal.stackexchange.com/questions/24559/tagging-a-friend-in-a-node/100933#100933.


Output of string.split() method

Question: I'm trying to first split a string into two values, and then split the second value in that string into more values. For some reason, the second value doesn't seem to splitting correctly.
I've tried a lot of refactoring and type checking, but it seems like the first part correctly returns a string, while the output is an array of strings, just not the strings I'm trying to return (single characters rather than the expressions separated by "|"
public class HelloWorld{

     public static void main(String []args){
        String starter = "Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15";
        String [] newList = starter.split(":");
        for(int i = 0; i < newList.length; i++) {
            System.out.println(newList[i]);
        }
        String secondElement = newList[1];

        String [] secondList = secondElement.split("|");
        System.out.println(newList[1].getClass().getName());
        System.out.println(secondList.getClass().getName());
        for(int i = 0; i < secondList.length; i++) {
            System.out.println(secondList[i]);
        }
     }
}

The result from the second for loop is just a list of individual characters, i.e. V, o, d, a, ... rather than Vodafone,STOCK,10 as the first element of the second list
Comment: `"\|" would be the JAVA string containing the JAVA escape code \|. But there is no such escape code for JAVA strings. It is necessary that the evaluated string contains "\|", so there has to be a literal "\". But \ is the escape character. To get a literal "\", you need to escape it. The correct string would be "\\|".
Comment: try `...split("\|");` instead of `...split("|");`
Answer: You have to escape the '|' character:
String [] secondList = secondElement.split("\\|");

because the argument of split() is a Regex expression and | is a special Regex character.

Output of string.split() method


Symmetric $k$-tensor

Question: I've searched on Google but I could not find an example of a symmetric tensor. I've found this blog post but I cannot construct any example of a symmetric tensor. I know that a tensor $T$ is symmetric iff $T= \operatorname{Sym} T$. Could you give the simplest example, say on $\mathbb{R}^n$?
Comment: In the blog post you mentioned there is actually an example of symmetric tensor at the end.
Answer: Any symmetric matrix $M$ over $\mathbb{R}^n$ defines a symmetric tensor of rank two which maps ${\mathbb{R}^n}^*\times \mathbb{R}^n\rightarrow \mathbb{R}$ by $(\vec{x}^T,\vec{y})\mapsto \vec{x}^TM\vec{y}$. You may recognize this as an inner product on $\mathbb{R}^n$. The simplest example is given by the identity $I_n$, which defines the typical dot product on $\mathbb{R}^n$.
Comment: An inner product should be non-degenerate

Symmetric $k$-tensor


Required sample size and degrees of freedom for a VAR

Question: I have read in many textbooks that as the ratio between the number of coefficients to be estimated in a VAR and the number of time periods increases above a certain threshold, estimation becomes unreliable due to a loss of degrees of freedom. However, in no textbook was I able to find information regarding what that threshold is. Could someone provide some insight into this or recommend literature?
Suppose I have 4 variables and 3 lags. I then have 4+4*3=16 coefficients. My question is, how many observations should the model have so as to ensure that lacks of degree of freedom is not a problem. Would 10 times the number of coefficients be fine? Or is 5 times enough? That is what I mean by threshold. Clearly, 32 seems not enough from an intuitive standpoint. But I assume there must be some theoretical work, maybe based on simulations, that can give a more accurate (and less intuitive) answer.
Comment: Upon re-reading,maybe I was not clear enough with the phrasing of the question. Suppose I have 4 variables and 3 lags. I then have 4+4*3=16 coefficients. My question is how many observations should the model have so as to ensure that lacks of degree of freedom is not a problem. Would 10 times the number of coefficients be fine? Or is 5 times enough? That is what I mean by threshold. Clearly, 32 seems not enough from an intuitive standpoint...but I assume there must be some theoretical work, maybe based on simulations, that can give a more accurate (and less intuitive) answer...
Answer: One should not expect there to be a hard-and-fast rule for such thresholds. The reason is that the precision of the estimates does not only depend on the ratio between parameters and observations, but also, for example, the "signal-to-noise ratio". That is, if the variance of the errors driving the process is large relative to the signal in the regressors, the estimates will be more variable all else equal.
Take the easiest possible example of a VAR, a univariate AR(1)
$$
y_t=\rho y_{t-1}+\epsilon_t,$$
where we assume $\epsilon_t\sim(0,\sigma^2_\epsilon)$. Then, we know that the variance of $y_t$ is (see, e.g., here)
$$
V(y_t)=\frac{\sigma^2_\epsilon}{1-\rho^2}
$$
Hence, the signal-to-noise-ratio is
$$
SNR=\frac{\frac{\sigma^2_\epsilon}{1-\rho^2}}{\sigma^2_\epsilon}=\frac{1}{1-\rho^2}
$$
Hence, there cannot be a single uniformly valid threshold for the ratio of parameters and observations, as I argue there is more information in the regressor $y_{t-1}$ as $\rho$ increases. In the limit as $\rho\to1$, we even have "superconsistency", i.e., the OLS estimator converges at rate $T$ rather than $T^{1/2}$.
To illustrate, here is a little simulation study showing average standard errors over 5000 simulations runs for different sample sizes $T$ and different AR coefficients $\rho$ (see the code below for the values used). We observe that, for any $T$, the standard errors are on average smaller for larger $\rho$, as predicted. (As expected, they fall in $T$ for any $\rho$.) So, depending on where your preferred threshold is, it may or may not be satisfied for any given $T$ depending on the value of $\rho$.
Here, the number of parameters is of course 2 (the estimate of $\rho$ and the constant) for any $\rho$ and $T$, so that is held constant, so to speak:

<code>library(RColorBrewer)
rho <- seq(0.1,0.9,by = .1)
T <- seq(50,250,by = 50)

reps <- 5000
stderr <- array(NA,dim=c(length(rho),length(T),reps))

for (r in 1:length(rho)){
     for (t in 1:length(T)){
          for (j in 1:reps){
               y <- arima.sim(n=T[t],list(ar=rho[r]))
               stderr[r,t,j] <- sqrt(arima(y,c(1,0,0), method = "CSS")$var.coef[1,1])
          }
     }
}
jBrewColors <- brewer.pal(n = length(rho), name = "Paired")
matlines(T,t(apply(stderr,c(1,2),mean)), col = jBrewColors, lwd=2, lty=1)
legend("topright",legend = rho, col = jBrewColors, lty = 1, lwd=2)
</code>
This is by no means unique to VAR models. In general, there is little guidance as to for what sample sizes asymptotic approximations are useful guides to finite-sample distributions. One exception is the normal distribution as an approximation to the t-distribution, where eyeballing the densities suggests that from 30 degrees of freedom onwards, the two are so similar we may as well use the normal. But even there, the choice of 30 is quite arbitrary. One might even go further and say that this particular rule of thumb has done more harm than good, because, in my experience, it has led quite a few people to infer that asymptotic approximations are useful as soon as one has 30 observations no matter what context is given...
Comment: @JackShi, I made an edit - which I hope clarifies my point a bit further?
Comment: From what I gather from your post, the (appropriate) threshold for the ratio of parameters and observations depends on the specific context in which the dataset is given. Can you elaborate on this a little bit more?
Comment: @ChristophHanck Thanks for the excelent explanation! A related question that buggles me is what the effects of having less degrees of a freedom are exactly. Do we just have a loss of efficiency or is there also an effect on the biasedness of the coefficients (and consistency?)?
Comment: Likely both. I took your OP to refer to variance ("unreliable"), but there is of course also finite sample bias in the coefficients' estimates. In my example, it would work in the opposite direction, i.e., more bias for higher $\rho$, so that the total result on the MSE would be an open question.


What is a confidence interval for a population mean?

Question: I have been learning about the central limit theorem and confidence intervals from this video.
The instructor states that when all sample means are compiled it forms a normal distribution (according to the central limit theorem). She also states that the population mean (unknown) lies at the center of this distribution. She states that a confidence interval is constructed by taking a sample mean and adding 2 times the sample error (rule of thumb).
However, near the end of the video, she states that this formula is used for finding the "confidence interval of a population mean". How is this right? Aren't we taking a sample mean from the population? And when we construct a confidence interval from a sample, is it also based on the normal distribution? But how could it be, as a normal distribution is only made when numerous samples are taken?
Answer: I understand that you are confused about the term "confidence interval of a population mean" since you only have the sample mean and construct a confidence interval based on the sample.
I would like to raise the question, what would you like to do with a "confidence interval of the sample mean"?
Once you have the sample, you know the sample mean, i.e. you should be 100% confident that the sample mean is one specific number. There is no need for a confidence interval for your sample mean.
What you do not know, is the population mean. However, you have at least an idea of it, since you have collected a sample from the population. Your best guess of the population mean is the sample mean, as simple as it is.
But are we 100% confident that the sample mean is the population mean? Of course, we are not. How confident are we? Well, there are several different approaches to answer that question, but probably the most famous way is to apply a mathematical procedure on your sample mean, which gives you an interval that captures in 95% of the cases the population mean.
This is called the confidence interval, and the mathematical procedure you have just seen in the video. To make this interval capture the population mean in actually 95% of the cases, you must rely on central limit theorem (or apply other methods).
Comment: When dealing with this classic frequentist approaches, you must always think in the terms "what would happen if I repeated my study infinitely many times?". If central limit theorem applies, then your infinitely many sample means would follow a normal distribution. Since we know the normal distribution quite well, we can easily give the range where 95% of all values lie, i.e. mean +/- 2*SD. The "standard error" is nothing else than the theoretical standard deviation of the sample mean, based on CLT. It's theoretical because there is just one sample mean, of course, so it does not deviate.
Comment: Thanks, that solves my problem. In the last sentence you say "To make this interval capture the population mean in actually 95% of the cases, you must rely on central limit theorem", why do we have to rely on central limit theorem for it to capture the mean 95% of the time?
Comment: If you cannot rely on CLT, then judging the confidence in your estimate becomes harder. You need to answer the question "what distribution does my estimate follow?", which is hard to tell if you have only one sample and therefore only one sample mean. One solution might be bootstrapping, to just name a popular buzzword.
Comment: Thanks very much. Just one more thing, I understand that we use a normal for all the sample means (forms a normal distribution due to CLT), but I am still a bit confused about how the normal distribution is used for samples. This website (https://www.mathsisfun.com/data/confidence-interval.html) at the section "Standard Normal Distribution" a normal distribution with the confidence interval values, so are confidence intervals made by a normal distribution or something? Thanks a lot
Comment: And why do we do z score times the margin of error, and not the standard deviation?
Comment: You're welcome! What you refer to as "margin of error" or "standard error" is nothing else than the standard deviation of your estimate. This standard deviation becomes smaller, the more precise the estimate is (e.g. because it is based on a very large sample, since then you would not expect it to deviate that much if you repeat your study), hence the confidence in this estimate becomes larger and the confidence interval becomes more narrow. When constructing the confidence interval, one usually assumes that the estimate is normally distributed which is often legit due to CLT.


JSF - List of objects in a Managed Bean and memory management question

Question: I am creating my first JSF application. For this question I am going to simplify everything to try and make my question as clear as possible.
The application I am creating is a simple contact storing application that will allow you to create a new contact, store information such as addresses, phone numbers, where they work, and upload files that are associated to the contact.
When the application loads the user is displayed with a list of contacts that have already been created. They can click on the contact's image to open up the contact and view all of the information stored on them. This is where my question comes in.
All of this information is stored in the ContactManager.java managed bean. All of the data on the contact is displayed in datatables. So there is an address datatable, phone datatable, uploads datatable. Each datatable view resides within an appropriate tab. I am using Primefaces to create the tabs. So basically when a contact is opened the system has to load maybe about 10 lists of data as well as dropwdown lists used for select values. to populate these datatables in the tabs.
<code>@ManagedBean
@ViewScoped
public class ContactManager implements Serializable {

     private Contact contactInfo;
     private List<Phone> phones;
     private List<Addresses> addresses;
     private List<Company> jobs;
     private List<Files> uploads;

     //dropdown select lists
     private List<Country> countryList;
     private List<State> stateList;

     //Getters and setters for everyting
     ..... (I am not going to type it all out but its there)

     @PostConstruct
     public void openContact() {
         try {
             this.countryList = myDao.getCountryList();
             this.stateList = myDao.getStateList();
             this.addresses = myDao.getAddresses(contactInfo.contactId);
             this.phones = myDao.getPhones(contactInfo.contactId);
             this.jobs = myDao.getJobs(contactInfo.contactId);
             this.uploads = myDao.getUploads(contactInfo.contactId);
         }
     }
}
</code>
So basically when a user opens a contact all of that contact information is loaded into memory so it can be displayed in the view.
This example is small to the actual amount of lists and data that I am storing but for simplification sake I am wondering about memory management.
My system is going to be used by a number of users and loading all of this information worries me. When does the memory allocated for all of this get cleared? Am I responsible for clearing it?
If I have 10 users and they are all viewing contacts that have really big tables with a lot of data I fear that this is going to bring everything to a standstill.
Currently it runs fine on my system but I know that all of these tables and lists are kept in memory until either the user clicks and opens a new contact or closes the application.
Any insight on if this is the right way of doing things or how to handle large information like this would be great.
I am using JSF 2.0 / Primefaces 2.2RC2-Snapshot
Comment: Have you thought about using `@RequestScope` to free that memory as soon as possible ( after request is served ) or about using Ajax calls with `@ViewScope` and only particular loading in the `@PostConstruct` method and rest of data load on demand ( tab switching )?
Comment: @Gaim I have thought about loading it on demand during tab switching but what if the user clicks through all of the tabs. Then all of the data has been loaded into the member variables. It is an improvement up until the point when the users views all the data. Do I need to handle when they click away from a tab and set the current tab's object data to null or something?
Comment: @Gaim - Also @RequestScope does not work for my application because there is some information that I have to keep persistant such as the contactId and some view specific variable used for navigation.
Answer: If the tables are big, you need a lot of memory on server side, with or without JSF.
Do not use rich faces tables; use ui:repeat and write custom paging for it.
primefaces tables are better than h:dataTable or rich:datatable.
JSF 2.0 uses 50% less memory for each user.
Also, use @RequestScoped beans and ViewScoped; do not use SessionScoped beans.
You also can remove sessions beans from session from faces context.
<code>context = FacesContext.getCurrentInstance();
externalContext = context.getExternalContext();
externalContext.getSessionMap().remove("UserContext");
externalContext.getSessionMap().remove("SessionController");
</code>
Etc.
Also, if you have some id for store in the page and you think you can not use RequestScoped beans, it is mistake
integrate with your application tomahawk myfaces, and use t:saveState value="#{bean.categoryId}"/>
it is store id or objects, list maps, in the current page scope.


How can we isolate API urls in the frontend of a React App?

Question: I just started learning React and I thought of making a simple app where I will have some API endpoints and the frontend will hit them with GET/POST requests.
But how can I hide those API urls from other users i.e anyone can open DevTools, find the API url and misuse it.
Any help is appreciated.
Comment: You can't, they are always visible on every website
Comment: So they weren't hidden. You probably got an error because you didn't send cookies
Comment: I have seen certain sites like that, but when I tried to hit the URL directly from the browser, it gave me an error, but it is working just fine with the web application.
What type of measure was it?
Comment: Okay!! Now I get it. Thanks for the help.
Answer: I don't think there's a way to hide API endpoints in the way you are suggesting. Security measures would have to be implemented in the back end in order to prevent misuse.
Comment: You could do a couple of things:

Basic: Set up some form of user authentication, where you would require either a valid API key or token to be passed for example in the header of every request.

A bit more advanced: Set up [CORS rules](https://expressjs.com/en/resources/middleware/cors.html) and use a library like [helmet](https://github.com/helmetjs/helmet) for further security.
Comment: Can you please suggest some security measures, so that, even if someone have the API url, they won't be able to misue it, or in simple words, if the user copies the url and tries to hit it with from the browser directly from the address bar, he will get an error.


Signing an iOS framework plugin for Unity and including it in my Unity app for iOS

Question: I'm trying to build a Unity app for iOS.
For this app, I'm building a Framework Project in XCode that I will be using as a plugin library. I've successfully imported the plugin as a .framework folder and embedded it as a binary.
However, when I now build the app and deploy it to my iPhone for testing I get the error message "This app cannot be installed because its integrity could not be verified", so it seems like the signing of the plugin is not correct. If I remove it again, the app works fine.
I tried:

...creating a new bundle identifier and a provisioning profile for it and signed it with the bundle identifier. Didn't help.
...signing it with the same identifier as the Unity App. Now the error message just changed to "can't be installed. Try again later"

I read that if it's flagged as a developer build I would need to accept a certificate in the devices screen on the iPhone, but no new certificates are showing up there.
Any thoughts on how to proceed with this? I'm new to Swift development, so I might have missed something simple. I'm using MacInCloud for XCode development, then moving the plugin to my PC, and building and deploying the final app with iOS Project Builder for Unity (which is an amazing plugin).
Answer: I managed to solve my situation. I reset all my certificates and started from scratch. I made sure to only create one private key which I then exported to all my other environments so that every part of the project uses the same private key. This solved the issue.


Pass current langage to twig on custom blocks

Question: my custom module block, with supposely no cache
<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  /**
   * @return int
   */
  public function getCacheMaxAge() {
    return 0;
  }
}

the language context i am trying to add on internal urls

      {{ dump(language) }}
  {% for icon in icons %}
    {% if icon.url is not empty %}
          {% if icon.url starts with '/' %}

          {% else %}

    {% endif %}
      {% endif %}
  {% endfor %}

i understood the variable passed by hook_theme are static so i have tried to override it on preprocess block
function amu_social_icon_theme($existing, $type, $theme, $path) {
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'language' => \Drupal::languageManager()->getCurrentLanguage()->getId()
      ],
    ],
  ];
}

function amu_social_icon_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'amu_social_icon_block') {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vars['language'] = $language;
  }
}

None of these works. I need to empty drupal cache so that

{{ dump(language) }}

display the correct current language
Answer:
I understood the variable passed by hook_theme are static

Yes, you can consider default values defined in hook_theme as static, they are set when you install the module. To help developers clearing the cache also clears most things which are installed by modules, so that you don't need to re-install the module all the time, but this has nothing to do with render caching.
language is a variable of your custom theme, not of the block. Then you don't need a preprocess hook, you can add it directly to the block build containing this template:
  public function build() {
    return [
      '#theme' => 'amu_social_icon_block',
      '#language' => $language,

Caching of the current language works out-of-the-box. This is one of the three default contexts. However, you can't debug caching by debug output. Most times you have a cache hit, serving the content from cache, without running the code building the content.
Comment: @sonfd, out of the box this is the case for all render arrays. See https://drupal.stackexchange.com/questions/298480/how-do-i-specify-a-render-cache-context-as-universal
Comment: this causes User error: "language" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).
Comment: I've added a `#` sign before the variable name .
Comment: Does every render array vary by language by default? That's what your answer seems to imply.  Looking at OP's code, it doesn't look like the block is actually a translated entity. Won't you need to manually add a language cache context to the block?
Comment: i have tried  '#language' => $language but it is null
Answer: a default value seems to be needed in hook_theme
 */
function amu_social_icon_theme($existing, $type, $theme, $path) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  return [
    'amu_social_icon_block' => [
      'variables' => [
        'icons' => null,
        'lang' => $language,
      ],
    ],
  ];
}

as well as a #cache entry in the block build method
<?php

namespace Drupal\amu_social_icon\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Icon' Block
 *
 * @Block(
 *   id = "amu_social_icon_block",
 *   admin_label = @Translation("Social Icon block"),
 * )
 */
class IconBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $config = \Drupal::config('amu_social_icon.settings');
    return [
      '#theme' => 'amu_social_icon_block',
      '#icons' => $config->get('amu_social_icon_icons'),
      '#lang' => $language,
      '#cache' => [
        'max-age' => 0,
      ],
      '#attached' => [
        'library' => [
          'amu_social_icon/global-styling',
        ],
      ],
    ];
  }

  public function getCacheMaxAge() {
    return 0;
  }
}

Comment: Drupal calls should be avoided in class, inject dependencies instead. But besides that: nice!


presentation of subgroup and quotient group.

Question: If we have a presentation $\langle x_i: R_j\rangle$ of $G$,
(1) what does the presentation (in terms of the given generators and the given relations) of a subgroup of $G$ looks like? In particular, what does the presentation of a normal subgroup $N$ looks like?
(2) What does the presentation of the quotient group $G/N$ looks like?
It seems that a subgroup should have less generators and the same relations, a quotient group should have same generators but more relations. Is this true?
Comment: Yes you can always find a presentation of a quotient group with the same generators and more relations. But a subgroup is more complicated, and in general it might need more generators, not less. There is a general method called the *Reidemeister-Schreier* algorithm for finding a presentation of a subgroup.
Answer: (1) It depends. Removing some generators, and keeping all relations will give you a subgroup (you have to translate all relations involving the removed generators, you cannot simply remove them).
EDIT: Actually, "translating" the relations to a smaller set of generators won't work in general at all. Thanks to Derek.
Also, you can not create all subgroups in this way. A subgroup might in fact need more generators than the whole group. For example in the case without any relations (i.e. the free group), there is a nice (and possibly counter-intuitive) theorem that $\langle x_1,...,x_n:\emptyset\rangle$ is a subgroup of $\langle y_1, y_2 :\emptyset\rangle$ for any $k$.
(2) yes. Just add all relations of $N$ and you get the factor group $G/N$.
Comment: In your answer to (1), you may need to add extra relations to get a presentation of the subgroup generated by a subset of the generators. It is even possible for the original $R$ to be finite, but for the subgroup not to be finitely presented.
Answer: If you want more detail for (2), there's a really good proof (which gives an idea of how to construct such a presentation) of presentations of factor groups on pages 42/43 of D.L.Johnson's book on presentations


DFSR files appearing on destination before they finish replicating

Question: We have a DFS environment. If we have a 100MB file for example that we put in the DFS share, it will appear very quickly on the destination server at another site even though with the bandwidth available there is no way it could have completely transferred. We believe this is causing our issue since when we then try to delete/rename the file on the source server it will keep reverting back.
Answer: There are features such as RDC and cross file RDC that allow to optimise the data that needs to be transferred over the wire to replicate these files. If you have near identical files that are already part of the replica set, then this is expected behaviour. See http://technet.microsoft.com/en-us/library/cc773238(WS.10).aspx#BKMK_029 for details.
IMHO this doesnt sound like an easy problem to solve over serverfault. I tend to prefer to steer people in the right direction when the problem seems complex. You will likely need to check if the initial sync has completed, get backlog details in each direction and then dump idrecord details for files to determine and check GVSN to see where they are changing.
There is a lot of information DFSR related on http://blogs.technet.com/askds and on http://blogs.technet.com/filecab that is specific to DFSR troubleshooting.
HTH
Comment: We have two servers replicating via DFS at two separate sites. They are both running 2003 R2. The root issue is that when we put a file on a server, and immediately try to rename or delete it on the source, it will revert the original back. This seems to happen more so to larger files. I believed the issue was that since it was appearing on the destination while it was still replicating, it was becoming the master file because it kept updating. That way, even if we were to delete the source file or rename it since the destination is still updating it would replicate back the destination file.


Swift make init Dictionary in struct

Question: i have a let of [[String:Any]] that i want to put it inside my struct data model, because i want to edit the data, can anyone tell me how should i make the dictionary that can contain this type of dictionary?
this is the var dictionary :
let toolListDict : [[String:Any]] = [
    [
        "Name": "Wrench",
        "qty": 6
    ],
    [
        "Name": "Cutter",
        "qty": 15
    ],
    [
        "Name": "Pliers",
        "qty": 12
    ],
    [
        "Name": "ScrewDriver",
        "qty": 13
    ],
    [
        "Name": "Welding Machine",
        "qty": 3
    ],
    [
        "Name": "Welding Glasses",
        "qty": 7
    ],
    [
        "Name": "Hammer",
        "qty": 4
    ],
    [
        "Name": "Measuring Tape",
        "qty": 9
    ],
    [
        "Name": "Alan Keyset",
        "qty": 4
    ],
    [
        "Name": "Air Compressor",
        "qty": 2
    ]
]

and so far this is the model data that i created :
struct Tools: Codable{
var name: String
var qty : Int

init(name: String, qty: Int){
    self.name = name
    self.qty = qty
}

}
how do i make an init dictionary inside my struct so i can just put that let into my struct?
i want to just add that dict into my data model like this :
let tool = try Tools(dict: toolListDict)

i hope i explain it clearly enough sorry if my english kinda confusing, thanks.
Comment: You can use something like a `DictionaryDecoder` from [this](https://github.com/elegantchaos/DictionaryCoding)
Comment: @Sweeper ahh thanks im check this out
Answer: Here are two possible solutions. First one is to map from the dictionary elements into the struct. For this we need a failable initializer since we are using compactMap
Note that I took the liberty to change the naming somewhat of the custom type
struct Tool: Codable {
    var name: String
    var quantity : Int

    init?(name: String?, quantity: Int?) {
        guard let name = name, let quantity = quantity else {
            return nil
        }
        self.name = name
        self.quantity = quantity
    }

    //...
}

Then it becomes simple to convert toolListDict
let tools = toolListDict.compactMap {
    Tool(name: $0["Name"] as? String, quantity: $0["qty"] as? Int)
}

Another option is to first encode the dictionary using JSONSerialization and then decode the result using JSONDecoder, for this we need to add a CodingKey enum to the custom type
enum CodingKeys: String, CodingKey {
    case name = "Name"
    case quantity = "qty"
}

and the encoding/decoding is done like this
do {
    let data = try JSONSerialization.data(withJSONObject: toolListDict)
    let tools = try JSONDecoder().decode([Tool].self, from: data)
    //...
} catch {
    print(error)
}

Swift make init Dictionary in struct


Approximate scalar dot product with a vector's sum

Question: I have two vectors $u$ and $v$ of size $n$. The $u$ vector is a linear increasing function. For the $v$ vector the individual elements are not known, only its sum. Is it possible to approximate the $u \cdot v$ somehow? I have noticed that in my case $u \cdot v \approx \text{mean}( u) \cdot \sum v$ but it might be coincidence for one case. Is there any theorem about that? or any other better approximation I could do?
Comment: What exactly do you mean by $u$ being a "linear increasing function"? And by "individual elements" of $v$, do you mean its components?
Comment: @ShirishKulhari I mean that $u = (a, a + \delta, \dotsc, a + (n - 1)\delta)$ for some $a$ and $\delta$. Yes, its components.
Answer: You are asking for the difference $\sum_{k=1}^n u_k v_k-\frac1n \sum_{k=1}^n u_k \sum_{k=1}^n v_k$, where $u_k=ak+b$ so $\frac1n \sum u_k = b+a \frac{n+1}2$.
This means $$\sum_{k=1}^n u_k v_k-\frac1n \sum_{k=1}^n u_k \sum_{k=1}^n v_k=a\sum_{k=1}^n (k-\frac{n+1}2) v_k= a\sum_{k=1}^n (k-\frac{n+1}2) \left(v_k-\frac1n\sum_{j=1}^n v_j\right).$$
This will for example be small if $v$ is close to its mean for all $k$. Using various inequalities for $\sum a_k b_k$, you can derive estimates such as
$$\left|\sum_{k=1}^n u_k v_k-\frac1n \sum_{k=1}^n u_k \sum_{k=1}^n v_k\right|\le |a|\sqrt{\sum_{k=1}^n (k-\frac{n+1}2)^2} \sqrt{\sum_{k=1}^n(v_k-\frac1n\sum_{k=1}^n v_k)^2},$$
which tells you your approximation is good if the variance of $v$ is small.
Comment: could you elaborate how you substituted $v_k$ with $\left(v_k-\frac1n\sum_{k=1}^n v_k\right)$ between second and third equality?
Comment: We have $\sum_{k=1}^n (k-\frac{n+1}{2})=0$, so $\sum_{k=1}^n (k-\frac{n+1}{2})\frac1n \sum_{j=1}^n v_j=0$ as well.


Newly created field not being added to entity

Question: I have created a form that adds a subset of field types to an entity (does not support bundles).  (the reason for the custom form is that end users find the Drupal standard 'Manage fields' workflow too difficult)  The class extends FormBase.  When the 'submitForm' function is executed, the field is saved but not added to the entity.
This is the code to save a date field (with text values filled in for explanation purposes):
$field_storage_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'type' => 'datetime',
  'translatable' => TRUE,
];

$field_values = [
  'field_name' => 'field_test_date',
  'entity_type' => 'my_entity_id',
  'bundle' => 'my_entity_id',
  'label' => 'Test Date',
  'translatable' => FALSE,
];

$this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values)->save();
$field = $this->entityTypeManager->getStorage('field_config')->create($field_values);
$field->save();

When the form is submitted, the field is created correctly but not added to the entity.
When I export the field configuration to YML, the following appears under dependencies:
dependencies:
  config:
    - field.storage.my_entity_id.field_test_date

Creating an identical Node field results in the following field configuration YML dependencies:
dependencies:
  config:
    - field.storage.node.field_test_date
    - node.type.basic_page

I suspect the field created with my custom form should also add the second configuration dependency like:
my_entity_id.type.my_entity_id

I tried adding the following before the field is saved but the 'addDependency' function is protected.
$field->addDependency('config', 'my_entity_id.type.my_entity_id');

Answer: You can't add this dependency, it's bundle configuration which you don't have and don't need in a bundleless entity. For testing better add a user instead of a node field or check the already pre-installed field.field.user.user.user_picture.yml
To create the field config you only need to specifiy the field storage and the bundle (for a bundleless entity this is the entity id). The other values are then extracted from the storage config:
$storage = $this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values);
$storage->save();

$field = $this->entityTypeManager->getStorage('field_config')->create([
  'field_storage' => $storage,
  'bundle' => 'my_entity_id',
]);
$field->save();

BTW part of the field UI is also the configuration of display modes. You need to add the new field as component at least to the default view and form mode, so that the new field is visible. See How to change the entity view display configuration programmatically?
Comment: Thanks again for helping me through this. The fields are almost fully functional. The only thing that doesn't work is that the added fields do not appear as options on the 'Add fields' when I try to add them to a view. The submit method includes $this->entityDisplayRepository->getViewDisplay('my_entity', 'my_entity')->setComponent($storage->getName(), ['label' => 'inline'])->save(). I looked at the link you included but I'm not sure what else needs to be done to get the added fields to appear in Views.
Comment: This is for adding the field to a view mode. Not connected with Views. For Views you need a views_data handler. See https://drupal.stackexchange.com/questions/302392/how-to-use-content-entity-type-in-a-view


Describing/sketching region of integration of triple integral

Question: I'm having great difficulty with the following problem:

This question concerns the integral $\int_{0}^{2}\int_{0}^{\sqrt{4-y^2}}\int_{\sqrt{x^2+y^2}}^{\sqrt{8-x^2-y^2}}\!z\ \mathrm{d}z\ \mathrm{d}x\ \mathrm{d}y$. Sketch or describe in words the domain of integration. Rewrite the integral in both cylindrical and spherical coordinates. Which is easier to evaluate?

Below is what I believe I have established so far...
The projection of this integral's domain onto the $xy$-plane is the portion of the circle $x^2+y^2=4$ on $0\le x\le2,\ y\ge0$.
The bounds on $z$ correspond to

$z^2=x^2+y^2$ (cone) and $x^2+y^2+z^2=8$ (sphere).

These bounds intersect at

$x^2+y^2=4$.

Below $z=2$ (where the bounds on $z$ intersect), I believe that the cone and cylinder, $x^2+y^2=4$, are completely inside the sphere.
Would it hence be correct to say that the region of integration is the solid lying between the cone and the cylinder, on $x\ge0$, $y\ge0$ and $0\le z\le2$? I'm struggling to visualize this problem.
When I attempt to move on, and evaluate the integral in cylindrical/spherical coordinates, my solutions differ by a factor of 2.
That is, I evaluated this integral as,

$\int_{0}^{\frac{\pi}{2}}\int_{0}^{2}\int_{0}^{\sqrt{8-r^2}}\!z\ r\ \mathrm{d}z\ \mathrm{d}r\ \mathrm{d}\theta=2\pi$

And,

$\int_{0}^{\frac{\pi}{2}}\int_{0}^{\frac{\pi}{2}}\int_{0}^{2\sqrt{2}}\!\rho\ \cos\phi\ \rho^2 \sin \phi\ \mathrm{d}\rho\ \mathrm{d}\theta\ \mathrm{d}\phi=4\pi$

Can you please help me to identify where I am going wrong?
Thank you very much.
Answer: You are very close.
The integral in cylindrical coordinates has the right value, but the lower limit for $z$ should be $r$, not $0$.
Notice that in spherical coordinates the angle $\phi$ should be integrated from $0$ to $\pi/4$. This restrict us to the volume inside the cone.
Addendum:
The volume is the region between the cone and the sphere in octant I ($x,y,z\ge 0$).
See the figure below.

In cylindrical coordinates we have
$$\int_{0}^{\frac{\pi}{2}}\int_{0}^{2}\int_{r}^{\sqrt{8-r^2}}\!z\ r\ \mathrm{d}z\ \mathrm{d}r\ \mathrm{d}\theta.$$
In spherical coordinates we have
$$\int_{0}^{\frac{\pi}{4}}\int_{0}^{\frac{\pi}{2}}\int_{0}^{2\sqrt{2}}\!\rho\ \cos\phi\ \rho^2 \sin \phi\ \mathrm{d}\rho\ \mathrm{d}\theta\ \mathrm{d}\phi.$$
Comment: Thanks. Can you please offer some insight on how the domain of integration should be interpreted? I think this is where my confusion largely lies.
Comment: @user77858: Glad to help. I added some details and a figure.


How to implement Page not found (404) for unpublished content?

Question: On my site, some nodes are unpublished forever instead of being deleted. I'd like to return Page not found (404) for anonymous trying to access unpublished node pages instead of Access denied (403). It's not about displaying a different message to the user, but rather about returning the 404 error code (important for bots).
So I've added the following to my module:
function mymodule_init() {
global $user;

  $normal_path = current_path();
  $parts=explode('/', $normal_path);
  $nid_part = $parts[1];
  $node = node_load($nid_part);
  if (!isset($node)) {
    return;
  }
  if (($node->status == 0) &&
    ($node->nid == $nid_part) &&
    ($user->uid == 0)) {
    drupal_not_found();
  }
}

But I still get Access denied as anonymous user on unpublished pages. How to implement it?
Comment: first, I would suggest using hook_boot(), not hook_init(), since hook_init() does not run on cached pages. If that doesnt solve it, I would start by setting a system message in your module, line by line to see what values the information is returning to ensure it is correct
Answer: You should be able to do it with Rules:

The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Using Rules...
Event: Content is being Viewed (by content type if you desire)
Condition: Content is Published, Negate
Event: Redirect to custom 404 page

This requires that you set up a custom 404 page, but most people do that anyways, and core takes care of everything else.
Specify 403 and 404 error pages for more info on setting up a custom 403 and 404 page
Comment: After setting the Rules like you suggest (http://i.imgur.com/Bfa7zSH.jpg) I still get "Access denied" (incorrect) for anonymous and "Page not found" (correct) for admin. So it looks like access check has higher priority than the rule.
Comment: hmm... Content Viewed must be too far along the path, that sucks it was a nice and clean solution.
Answer: My solution was to allow access to unpublished nodes, but then return a 404 result before rendering the page.  If you have other modules controlling or depending on node_access(), this solution may not be for you.
/**
 * Implements hook_node_access().
 *
 * Allow users to view unpublished nodes, but modify them later to return 404
 * in hook_view_node_alter().
 */
function MODULE_node_access($node, $op, $account) {
  if ($op == 'view') {
    return NODE_ACCESS_ALLOW;
  }

  return NODE_ACCESS_IGNORE;
}

/**
 * Implements hook_node_view_alter().
 *
 * Provide a 404 page for unpublished nodes.
 * Access is allowed through hook_node_access().
 */
function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if ($node->status == NODE_NOT_PUBLISHED) {
    drupal_not_found();
    drupal_exit();
  }
}

My use case was much more limited, and so I was able to limit hook_node_access() to only affect permissions for anonymous users, and then have hook_node_view_alter() ignore logged in users.
I also inlined code from drupal_deliver_html_page() in order to provide a custom 404 message instead of the site-wide page given by drupal_not_found()
Answer:
Use the view_unpublished module to grant access to unpublished nodes for anonymous users. - https://www.drupal.org/project/view_unpublished
Add this to your module:

    /**
     * Implements hook_init().
     */
    function MYMODULE_init() {
      // For anon users, show a 404 for unpublished content instead of a 403.
      if(user_is_anonymous() && ($node = menu_get_object()) && $node->status == NODE_NOT_PUBLISHED) {
      drupal_not_found();
      drupal_exit();
      }
    }
Answer: I have used Hook_preprocess to direct them to the 'page not found' page.
I was able to redirect them to the 404 page by the following code. hope this helps for someone in future.
This was written for a Drupal 6 site. I have slightly modified @camcam's code for drupal 6. you'll be able to use his code for drupal 7 and use drupal_exit() for exit() method.
function Hook_preprocess_page(&$vars) {
  global $user;

  if ($vars['title'] == 'Access denied') {
    $normal_path = $_GET['q'];
    $parts=explode('/', $normal_path);
    $nid_part = $parts[1];
    $node = node_load($nid_part);

    if (!isset($node)) {
      return;
    }

    if (($node->status == 0) &&
      ($node->nid == $nid_part) &&
      ($user->uid == 0)) {
      drupal_not_found();
      exit();
    }
  }
}

cheers. this is my first post here.
Answer: I've always used this: https://www.drupal.org/project/unpublished_404
It is currently unmaintained (and in the process of getting a new maintainer) due to a security issue, but there is a patch available in the Issues forum for this module.
https://www.drupal.org/node/2752665#comment-12157403


exchangeability vs. shift invariance

Question: Let $X_n$ be a sequence of real RVs indexed by $n \geq 0$.  Can someone provide an example of a sequence $X_n$ that is exchangeable (law invariant under finitely supported permutations on the natural numbers) but not shift invariant (law invariant under left shift)?  What about the other way?
Answer: If the sequence $(X_n)$ is exchangeable then $(X_1,X_2,\ldots,X_n,X_{n+1})$ and $(X_2,\ldots,X_n,X_{n+1},X_1)$ coincide in distribution, in particular $(X_1,X_2,\ldots,X_{n})$ and $(X_2,\ldots,X_{n+1})$ coincide in distribution. This holds for every $n\geqslant1$ hence  $(X_n)$ is shift invariant. Thus, exchangeability implies shift invariance.
Let $X_0$ denote a nondegenerate symmetric random variable and $X_n=(-1)^nX_0$ for every $n$. Then $(X_n)$ is shift invariant but the distributions of $(X_1,X_2)$ and $(X_1,X_3)$ are different hence $(X_n)$ is not exchangeable.
Thus, shift invariance does not imply exchangeability.

exchangeability vs. shift invariance


Show that the union of two sets, each of measure zero, has measure zero

Question: Show that the union  of two sets, each of measure zero, has  measure zero
I have some ideas but not sure if it is sufficient.
Let f be a set of discontinuities on function f and let g be a set of discontinuities function g.
Thm states that if f and g are continuous at number a, then the sum is continuous.
Since f and g have measure zero,
$m(f \cup g) \leq (f+g)$
Thus f+g have measure zero, the union must have measure zero.
Comment: are $f$ and $g$ functions or sets ?
Answer: With outer measure $\mu^*$ we have $$\mu^*(F \cup G) = \mu^*(F) + \mu^*(G)$$  since $\{A_n\}$ covers $F \cup G$ if and only if it covers $F$ and $G$.


CSS Navbar items

Question: Hello respected devs here,
I am completely new to web-developing and trying to build my website.
Here the problem with the CSS code is that the middle navbar items (.nav_links li) doesn't stay at one line as it pushes the Trends item in navbar to start at a newline as seen in the attached image in the post(Please see the attached image). I want all items to stay at one line with the same spacing between the items.
Maybe the fix is simple, I'd really appreciate your help, thanks

HTML
 <!DOCTYPE html>

        <link href="styles.css" rel="stylesheet">
        <title>N Dress Boutique. Now Shop Everything at your Finger Tips</title>

N

Home

Dresses

Trends

            <button class="button">Contact</button>

CSS:
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color:#b7b7b7;
}

body {
    background-color: black;
}

header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 10%;
    background-color: #332323;
}

.logo {
    cursor: pointer;
    color: white;
    font-size:large;
}

.nav_links li  {
    display: inline-block;
    width: 40%;
    padding-left: 3%;
    padding-right: 10%;
    cursor: pointer;
    border-left: 1px solid white;

}

.button {
    background-color: #302b2b;
    padding: 5px 10%;
    color:white;
}

Answer: You only give each item a width of 40%. If you want them all to stay on the same line, you should change it to 33% or 30%.
Comment: That changes the spacing between the items and items overlap on each other. However, changing width to 70px fixes the problem.
Comment: Should I keep width 70px? If it's good coding or implementation, I am fine with it or there's a better way?
Answer: The most easy way to solve this is using a table instead. It makes your items always fit in the same row. Note that the table must be small enough otherwise it is going to overflow from the screen.
Comment: I haven't tried it. Most of the youtube tutorials I have seen is they are always using nav tags
Comment: Let me play with your idea and I will get around with it.

CSS Navbar items


Modified Newton method and contraction principle

Question: I am studying Newton's method modified by the book Zorich, Mathematical analysis II, page 39,40:

It seems to me, if I make no mistakes, that there is a problem in the derivative of $ A (x) $. The author says that $ | A '(x) | = | [f' (x_0)] ^ {- 1} \cdot f '(x) | $, while I would say that:
$$ | A '(x) | = | 1- [f' (x_0)] ^ {- 1} \cdot f '(x) | $$
Am I wrong?
Answer: Yes, your observation is correct. This is also confirmed by the fact that this corrected expression is the smaller the closer $f'(x_0)$ is to $f'(x)$, that is, the closer the step is to the Newton method.
Perhaps they mixed this up with the derivative of the Newton step where this first  term indeed cancels,
$$
N(x)=x-[f'(x)]^{-1}f(x)\implies N'(x)=I-I+[f'(x)]^{-1}[f''(x)][f'(x)]^{-1}f(x)
$$
Comment: Thank you, therefore the condition for $A(x)$ to be a contraction becomes this:
$$ 0 <[f '(x_0) ^ {- 1}] \cdot f' (x) <2 $$
right?
Comment: Yes. The closer to $1$ the better.


How to filter Search API index view by taxonomy parent

Question: I am using the default database server that comes with search api. I have the Hierarchy Index ticked and I also have the taxonomy field that I want selected.
Could someone give me instructions on how to configure the view to have it filtered by the taxonomy parent/show only the children of the selected parent term? I just want a drop down like you would have with a regular view.
(I got this to work in D7 a while ago but I think that was because the field still retained its taxonomy data type when indexed but now with D8 it has none of that.)

I can add a field that has a parent relationship but that does nothing.
I tried adding a field Vocabulary » Taxonomy term » Term Parents and tried to filter by that but nothing.
Answer: I just figured this out the answer was simpler than I thought.
I was trying to use contextual filters & relationships like other answers said but what worked was just simply adding the Taxonomy Field to Filter Criteria then selecting the desired parent. That's it. No need to add a relationship to it.
Edit:
There is still a problem: it doesn't work when using a grouped exposed filter it gives this error:

A value is required if the label for this item is defined.

Log Message:

PHP -  Warning: trim() expects parameter 1 to be string, array given in ...

I tried changing the filter to Combined field filter with the Taxonomy as a field so the input would be string but I still get another error.

PHP - Error: Call to undefined method ...


Ubercart or learn a new ecommerce package?

Question: Im a big Drupal fan which is why Ubercart is the obvious choice for me when it comes to ecommerce. Ive made a couple of Ubercart sites and I havn't been massively impressed.
Ubercart doesn't seem very powerful when you need extensive business logic, can be hard to theme and has javascript reliance. Admittedly ive only played with others like magento and zencart, but Ubercart doesn't seem to lead in its field the way Drupal does in its.
Im reluctant to learn a new ecommerce package due to the time required, but the javascript reliance alone makes me wonder if I have to. Has anyone else had a Drupal background and faced a similar dilemma with ecommerce?
Thanks
Comment: I do not know the answer to your question because I don't have enough experience with different ecommerce platforms. I *do* know that if you're starting today, you should consider using Drupal 7 and [Drupal Commerce](http://drupal.org/project/commerce), which is the successor to Ubercart.
Comment: Ive not starting out, ive used drupal for a few years and ive made 2 sites with ubercart. Thanks
Comment: OK, sorry, then I misinterpreted your question.
Answer: Disclaimer I help develop commerce (commit patches) from time to time and maintain a few commerce modules, so I might be a bit biased in my opinions
I haven't done ecommerce outside of Drupal, but I have extensive experience with both (Ubercart) Drupal 6 and (Drupal commerce) Drupal 7.
Drupal commerce has a lot of great advanced both for developers and site builders.
Since it has heavy views and rules integration, it makes it very easy to configure the modules to do what you want to do. With Rules you can add a lot of custom logic like discounts. The tax support is also very good already and is very easy to customize for your location.
The only things that's missing with Drupal commerce right now is the host of modules for various stuff compared to ubercart Drupal 6. But this is not as bad as it might sound, and there are a lot of modules being created in the community around commerce.
For developers the experience developing with commerce is the best I've tried for a long time. I started when commerce was still in alpha and have had to deal with API's chaining etc. This has all stabilized now, and the result is very impressive. You can tell that commerce is built from the ground up by people who know how commerce should be made with Drupal. It's very flexible and there's no inconstancy and strange hacks like there is in ubercart. One area in particular where there is a big difference is the price handling system is very cleverly built. Commerce is built to handle multi currency unlike ubercart which I've found to be a major pain.
Conclusoin
All in all I find that commerce is more powerful out of the box using only the UI, and the code you write is in my experience generally more clean and easier to maintain. It doesn't have any legacy code, which is easy to see and it is built to take advantage of all the new Drupal 7 features.
Comment: Does Commerce have javascript reliance? Thanks
Comment: @jdln It does make use of the #ajax framework, I don't know if is required though.
Comment: I see that the maintainer has [clearly invited](http://drupal.org/node/1134714) you to help him test the js dependency of Drupal Commerce. Why not lend him a hand? Test results are a great starting point for development, so you would be helping yourself and the community.


Advice on keeping Ec2 free tier - really free

Question: I have a question similar to this one.
I've taken a first foray into Ec2 - I expect really really low usage and have no power user requirements, and so I thought that the free instance would be ideal.
All I have done so far is bring up the instance, and yum update it. I checked the billing estimator, and it already seems to think that that I am accruing charges. it's not much, but I still feel slightly like I'm being nickel and dime'd - wondered if anyone had any guidance on keeping a free instance really 'free'
Thanks, Ace
Comment: You fired up a micro instance, yes? Which billing estimator are you looking at?
Comment: What OS did you pick? Note that you can deploy with RHEL but it isn't free. Pick a basic Linux (LAMP) AMI and you'll be fine.
Comment: I picked the AMI that was free tier eligable , the billing page says i'm accruing charges based on usage, but other than having logged in a few times,  i haven't done anything much with it
Comment: I've shut this instance down. I will try again with another one and record precisley what I do. We'll see what happens. Thanks for the responses
Comment: @phatmanace what was your update? I am also encountering this. I on the other hand, just uploaded a simple website template on it but looks like I'm being charged the same amount every month.
Comment: @johhnyq: some time ago, I moved to digital ocean and haven't looked back. It costs me $5 a month. Always. Without variantion
Answer: Free tier of EC2 equates to:

1 Micro Linux(Acceptable OSs) and 1 Micro Windows(Running Server 2012 base).
You receive 15GB of data transfer out across all AWS services.
1 Elastic IP per running instance and they must be bound to the instance.
30GB of provisioned Elastic Block Storage
2 million I/Os on those EBS devices
Elastic Load Balancer with 15GB of data processiong.

Also AWS Free tier information can be found here https://aws.amazon.com/free/
Answer: What components are you being charged for?
The free tier includes enough compute time to run a micro instance and 15gb of data transfer. If you create snapshots of your machine, turn on detail monitoring, add an elastic ip, or do a number of other things, you might incur extra charges.
You can see your billing break-down here:
https://portal.aws.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=activity-summary


iPhone 6 Screen Resolution with CSS and JavaScript

Question: I read that the iPhone 6 Screen Resolution is 750*1334. But when I have for example a text, etc. and center it, it is not centered precisely. But when I use 50% with CSS, then it is centered precisely. A simple ID with DIV:
"margin-left: 375px;"
"margin-left: 50%;"
Comment: I wrote the "margin-left: 750px;" wrong it should be "margin-left: 375px;" but it is not centered.
Answer: Try using meta viewport in the head of your html
<meta name="viewport" content="width=device-width, initial-scale=1">

this should fit the content according to the device
Comment: Also I see your new, just make sure to properly format your questions and make sure your code is formatted correctly in context to the rest
Comment: Thank you, but unfortunately this also doesn't centered it.
Answer: Please look here for the code:
https://www.w3schools.com/code/tryit.asp?filename=FWSYYEYX7IV5
Answer: Simple, just remove margin-left: 375px;
and add text-align: center; (in #text)
 <!DOCTYPE html>

Test

Comment: I recommend not using px or margin: attributes for centering too much as this can cause trouble later in development in a website
Comment: OK, but what is when I use something other than a text? Also I need to use margin-left because I have multiple objects which I do center.
Comment: text align is a specific attribute , margin-left only defines the space between the object and the left side, the bigger the margin the furthur away it is
Comment: Another problem is when I use media queries. When the iPhone 6 is not 750 px, how do I know the exactly resolution?
Comment: Maybe I describe my problem not exactly. screen.width*devicePixelRatio returns 750px for iPhone 6, but in fact it is not so. Therefore I can't center it with 375 px, and I can't use media queries because the iPhone 6 is not 750 px?
Comment: Please check off my answer if this helped


PostgreSQL: Calculated field in JSON

Question: Is there a way to calculate a field that is in JSON. Here is how my table is setup:
CREATE TABLE test1
(
     id int not null,
     data JSONB
)

Here is the document I am inserting
{
     'name': "test name",
     'age': 46,
     'heartrate': 211,
     'heartrateminuseage': function(){ return this.heartrate - this.age; }
}

How can I make something like this work?
Answer: Let's assume that you have data like:
CREATE TABLE test1(id INT NOT NULL, data JSONB);

INSERT INTO test1(id, data)
VALUES (1,'{"name": "test name",
            "age": 46,
            "heartrate": 211}'),
      (2,'{"name": "test name2",
           "age": 50,
           "heartrate": 200,
           "heartrateminuseage": 1000}');

To calculate "heartrateminuseage" you could use extract values first and set using jsonb_set:
SELECT id, data
   ,jsonb_set(data,'{"heartrateminuseage"}',
              to_jsonb((data->>'heartrate')::int - (data ->>'age')::int),
              true) AS data_2
FROM test1;

Output:

As for calculated column:

Create a view

  CREATE VIEW wv_test1
  AS
    SELECT id
      ,jsonb_set(data,'{"heartrateminuseage"}',
                 to_jsonb((data->>'heartrate')::int - (data ->>'age')::int),
                 true) AS data
    FROM test1;

Create a trigger that will update column
Create a function

More info: Computed / calculated columns in PostgreSQL and Store common query as column?

PostgreSQL: Calculated field in JSON


Erro ao limpar um DataGrid

Question: Depois que eu salvei meus itens que estão no DataGrid em uma base de dados, gostaria que limpasse. Portanto utilizei da seguinte maneira:
dg.Items.Clear();

Mas dai aparece esse erro:

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

Ele esta sendo usado ou algo parecido? Como solucionar isso?
Comment: Posta o resto do código, como você está fazendo pra atribuir o `ItemsSource`
Answer: Já experimentou fazer isso aqui:
dg.ItemsSource = null;
dg.Items.Refresh();

Comment: Dessa maneira funcionou sim. Mas fiquei pensando, isso é boa prática né? e não vou ter problema na hora de add ou fazer alguma alteração?
Comment: Não sei se é a melhor prática, mas dessa forma você limpa a referência ao `source` anterior e fica livre pro resto.
Comment: Muito obrigado :D

Erro ao limpar um DataGrid


How to control unintentional, natural vibrato in singing?

Question: So, I'm 14, going on 15.  And by vibrato, I mean of the voice (vocal cords?).  Anyway, a good description of it would be that it just came out of the blue.  I was singing to myself one day, maybe a year ago, and it just happened.  I noticed soon after developing vocal vibrato that I developed "humming" vibrato.  That makes sense, I suppose.
My problem is, unless I really force it - and it doesn't feel "right" when I do - I can't not vibrate.  In other words, I vibrate whether I want to or not.  I recognize that it is (relatively) rare for someone to be born with unnoticed and undeveloped natural vibrato, let alone for someone who really doesn't sing that much at all.  I'm in orchestra, not choir.
What I'd really like to do is to be able to control when I vibrate.  I can stop just fine while I'm humming, but, again, if I'm singing I can't.  Also, whether humming or singing, I cannot control the frequency of the vibrato - I'd really like to slow it down, because I clocked myself at 10-12 Hertz, and once at 16 Hz.
Just a note: this is not "artificial" vibrato.  I've examined the sensations closely, and I can say for a fact that I am most definitely not moving my stomach or diaphragm to accomplish vibration, and I'm not moving my jaw either.  It's a pure, natural, yet unconscious and uncontrollable vibration.
Answer: You can learn to control your vibrato with study with a professional voice teacher. You need feedback from a professional who can analyze what you are doing and help you control it.
I'm 49 years old, and my voice seems to be much like yours. I've always had a lot of natural vibrato. I sang in choirs all my teen years.
I went to music school and got a bachelor's degree in music with voice as my principal instrument. When I arrived at music school I intended to study jazz and pop singing, but a jazz vocal professor at my school took me aside and said, "You can't sing jazz and pop and I can't teach you to sing jazz and pop. You have a natural operatic voice. You must study opera singing." So I got assigned to an operatic voice professor and did that for four years. My professor did have to teach me how to "rein in" and control my vibrato, which was too wild and uncontrolled for proper classical singing. It did not take very long, but it did require working with a professional teacher.
To this day, classical musicians tell me that I have a light vibrato when it comes to operatic singing, something that's better-suited to Baroque music or Mozart on the one hand or the contemporary English choral tradition on the other. At the same time, jazz, rock and pop musicians tell me that I have too much vibrato, and why can't I stop singing that way?
I can belt out a hard rock song, without vibrato, but only for a short while. It always hurts my voice and causes problems. I can sing operatically or classically all day long, but five minutes of trying to sing in the rock or jazz style can cause me to hurt my voice and have a sore throat for the rest of the day.
Well, it seems I'm an unusual case. I am in fact a very good singer; I've worked hard at it. I've just had to concentrate on the styles of music that are naturally suited to my voice, and that means various styles of classical music and light opera.
Answer: As a professional voice instructor, I can assure you there's not much you need to worry about. Many times a natural vibrato (as long as it's variation in pitch, not air control - i.e. inconsistent breath support, and not laryngeal or "gospel jaw") is actually sign of proper singing technique. This includes things like proper diaphragmatic support, posture, open throat, soft-palate placement, tongue placement, and overall vowel placement. As long as you're completely sure you're using proper technique, you may be dealing with a healthy natural vibrato.
There are exercises, however, to help you gain control of your vibrato trills. It takes time and dedication (practicing daily for 6-9 months is usually the average turnaround for developing vibrato - however some get it in a matter of a couple months and some it takes years).
I suggest you hire a professional vocal coach to watch and listen to you sing. He/she can help determine what the reason for your vibrato is with more information. As well as provide the best exercises to help you correct the problem.
Answer: I just had to respond to a couple of points on here as absolute nonsense, and this is by no way intended to be an attack on the posters here but moreover what they have been taught or led to believe.
I will give you one example:
"I arrived at music school I intended to study jazz and pop singing, but a jazz vocal professor at my school took me aside and said, "You can't sing jazz and pop and I can't teach you to sing jazz and pop. You have a natural operatic voice. You must study opera singing."
This is absolute nonsense.  You may well have a natural tendency to sing in this style but to say you are restricted to singing opera because that what your base is defies belief.
Your voice only does what you train and teach your muscles to do - it's nothing more complicated than that. If you push too hard without being relaxed you will strain and things will become an effort and you'll become hoarse and croaky. If you're not warmed up before a show, whether it be by simple lip trills or sliders etc then you won't get the best out of your voice.
You can alter the tone of your voice in the same way that you can sing using the soft palate or with the larynx lowered, raised or slap bang in the middle - and yes, you can also train your voice to produce an effortless vibrato at a speed that you wish (the average is around 6 oscillations per second).
Anyone who tells you otherwise is lying - it's that simple!
The only difference between singing with a faster vibrato and a slower one is that you need to do exercises at a slower pace - it's a bit more difficult than if someone has no vibrato whatsoever because bad habits are exactly those, but it's definitely not unachievable and you should start seeing results within a few weeks of 1 hour exercises every day :)
I have been a singer for long enough to not only benefit from improved techniques (no scales) and a more relaxed way of learning and expression that I decided to become a vocal coach and spread these techniques and processes to others.
I presumed that the voice I had was as good as I could be - my range was "OK" (or so I thought) at about 3 octaves.... within 6 months I am now on 5 octaves and heading for 6 - oh, and this range is in FULL voice, not chest and then falsetto (head voice).
Finally, just another myth - if you can sing a high note in Falsetto but not in Full voice then with training YOU CAN!! Any note you can sing in Falsetto you can sing in Full!
Comment: Please don't include email addresses or a signature in your post: this should be put in your "about me" section in your profile. Other than that, good answer.
Answer: Speaking as a layman (not professional) when it comes to singing, I've always been interested in sacred choral music since grade school back in the early 1960s. I've done a lot of research about singing on my own and, have been fortunate enough to sing in school and church choirs. And a little bit of professional vocal coaching along the way as a student. For what it's worth, vibrato has been something which was elusive to me until about the 1990s. However, I've worked long and hard for it to finally kick in as a natural element of my singing. Meaning, that vibrato can only come about AFTER everything to produce a free tone is correctly in place. By default, the human voice has vibrato already and it requires correct technique for it to manifest itself naturally. Once that occurs, I would be the last person to suggest that it be removed entirely. It can't be done without harmful effects to the vibrant voice. Good luck to you as you endeavor to sing in years to come.
Answer: I think that 'vibrato' is something that is natural, like you said.
I am a pop and soul singer and I struggled with my natural vibrato for about 3 years, however with careful techniques, I did overcome it.
If you want to be a more classical singer, you should embrace it, because it is a really nice sound. However if it does seem to become a problem, you should seek help from a professional teacher.
Obviously for me, as a pop/soul singer it did become a problem but as I am now Grade 5 pop/rock singer I think there are certain techniques.
I'll give you one tip though, when singing a sentence.. Stop and sing it over and over again and REALLY listen and see if you are using vibrato, if you are, try again until you notice it's not there. If you can't detect it then try and notice how you sang without it, and try again using that technique.
I hope I helped:)
Answer: I agree with previous answers about vibrato being natural when the singing technique is well-developed. Note also that some people have a wider vibrato than others because of different biology and physiology of the human body. Everybody's voice is different (that is why we have different voice types and fachs) so everybody's (natural) vibrato is also different.
It is possible to control your vibrato when your singing technique (=muscles) is well-developed but it is more difficult if your natural vibrato is wide. In that case you would be "fighting" against your natural big and wide vibrato (which e.g. dramatic operatic voices have, see

), and this requires more training compared to a situation where your natural vibrato is small and voice more straight (many pop singers like Michael Buble

 or Ed Sheeran have good technique and naturally very small vibrato, you could also check for example this lesson

).


Como documentar parâmetros recebidos pela função "func_get_args"?

Question: Como eu posso estar documentando parâmetros que são recebidos através da função func_get_args?
O motivo é de estar podendo passar vários parâmetros para a função com a mesma finalidade!
/**
 * Gets a smart text filtered and formatted of according with the property name provided
 *
 * @param string $code The property name to be called
 *
 * @return string Returns the content of property in `$code` with formatting filter as a string
 * @see   Skreth\Code\Text::getTexts()
 * @since 0.2
 */
public static function code($code)
{
    if (!is_string($code)) throw new InvalidArgumentException("Smart text is not a string");

    return StringFilter::formatting(self::getTexts($code));
}

Como assim, podendo ser possível passar vários $code:
public static function code()
{
    $code = func_num_args();
    $result = [];

    foreach ($code as $value) {
        if (!is_string($value)) throw new InvalidArgumentException("Smart text is not a string");

        $result[] =  StringFilter::formatting(self::getTexts($value));
    }

    // OU, TALVEZ (Acredito que foreach seja mais perfomático, estou certo?)...
    $result = array_map(function ($value) {
        if (!is_string($value)) throw new InvalidArgumentException("Smart text is not a string");

        return StringFilter::formatting(self::getTexts($value));
    }, $code);

    return implode(' ', $result);
}

Aceito dicas de boas práticas de programação também :D
Answer: Conforme a resposta no SOen
A maneira antiga seria:
http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.param.pkg.html
/**
 * @param int $param,...
 **/

No entanto isto não é mais suportado, Desde o PHP5.6 os Variadic Method Parameters são parte do PHP e o PHPDoc também fez a atualização pra isto. Parece funcionar no PhpStorm IDE desde o EAP 139.659 (8.0.2+). Não tenho certeza sobre outros IDEs.
https://youtrack.jetbrains.com/issue/WI-20157
Em todos casos a sintaxe apropriada é esta:
/**
 * @param int ...$param
 **/