How to overwrite a table in PostgresSQL using copy_from in Python?

Question: I have written a python script that copies the data from CSV to PostgresSQL table using psycopg2 copy_from function.
But I noticed that the data keeps on getting appended rather than getting overwritten in the table.
I need to overwrite the table. Is it possible to achieve by copy_from or copy_expert function in python?
I know I can achieve that by copying the data from CSV to a temporary table and then dropping the original table and rename the temp table, but I want to avoid that approach.
What are other optimum alternatives I can use to overwrite large tables on a daily basis from data in CSV?
Comment: why you dont use a store procedures that first delete all table and then insert?
Comment: Why stored procedures? Can't I just write delete and insert query directly?
Answer: You should just create a function which encapsulates copy_from function and has the following piece of code before calling copy_from, in order to truncate the table:
<code>    with engine.connect() as connection:
        connection.execute(f"TRUNCATE {table_name};")
</code>


Retornar valores em comum de várias matriz de objetos em Javascript

Question: Galera fiz um exemplo simples para ilustrar meu problema. Tenho 3 arrays de objetos a datasOne, datasTwo e datasThree e o que quero é retornar um novo array somente com os objetos que tem nos 3 arrays. Por exemplo, se tiver somente o Gustavo nos 3 arrays, então ele que será retornado. Mas tem um detalhe que se o datasThree for um array vazio, então irá trazer os dados em comum somente do datasOne e datasTwo e se somente o datasTwo que tiver dados e os outros dois arrays tiver vazios, então irá retornar os dados somente do datasTwo. Em outras palavras é retornar os dados em comum somente dos arrays que tiverem dados. Eu consegui fazer esse algoritmo e funciona da maneira que quero, mas gostaria de saber outra forma de fazer isso menos verbosa e talvez mais simples e também funcionar para se caso eu adicionar mais arrays para comparar como um datasFour por exemplo. Agradeço quem puder me ajudar.
Meu código abaixo:

let datasOne = [
  { id: 1, name: 'Gustavo' },
  { id: 2, name: 'Ana' },
  { id: 3, name: 'Luiz' },
  { id: 8, name: 'Alice' }
]

let datasTwo = [
  { id: 1, name: 'Gustavo' },
  { id: 3, name: 'Luiz' },
  { id: 8, name: 'Alice' }
]

let datasThree = [
  { id: 1, name: 'Gustavo' },
  { id: 3, name: 'Luiz' },
  { id: 2, name: 'Ana' },
  { id: 5, name: 'Kelly' },
  { id: 4, name: 'David' }
]

let filtered

if (datasOne.length > 0 && datasTwo.length > 0 && datasThree.length > 0) {
  filtered = datasOne.filter(firstData => {
    let f1 = datasThree.filter(
      secondData => firstData.id === secondData.id
    ).length
    let f2 = datasTwo.filter(
      secondData => firstData.id === secondData.id
    ).length
    if (f1 && f2) {
      return true
    }
  })
} else if (datasOne.length > 0 && datasTwo.length > 0) {
  filtered = datasOne.filter(firstData => {
    return datasTwo.filter(secondData => firstData.id === secondData.id).length
  })
} else if (datasOne.length > 0 && datasThree.length > 0) {
  filtered = datasOne.filter(firstData => {
    return datasThree.filter(secondData => firstData.id === secondData.id)
      .length
  })
} else if (datasTwo.length > 0 && datasThree.length > 0) {
  filtered = datasTwo.filter(firstData => {
    return datasThree.filter(secondData => firstData.id === secondData.id)
      .length
  })
} else if (datasThree.length > 0) {
  filtered = datasThree
} else if (datasTwo.length > 0) {
  filtered = datasTwo
} else if (datasOne.length) {
  filtered = datasOne
}

console.log(filtered)
Answer: Primeiro você precisa de uma função que retorna a intersecção entre 2 arrays. A princípio poderia ser algo assim:
function interseccao2(array1, array2) {
    return array1.filter(e1 => array2.some(e2 => e1.id === e2.id));
}

Só que esta função não é lá muito eficiente, pois para cada elemento de array1, ela percorre novamente o array2 desde o início, até encontrar o elemento (no pior caso, quando o elemento não existe, percorrerá todo o array2). Claro que para poucos arrays pequenos a diferença será imperceptível, mas se tiver muitos arrays com vários elementos (e/ou ainda com poucos elementos em comum), poderá ficar lento sim.
Uma outra forma é usar um Set, que é uma estrutura otimizada para buscas (além de não permitir elementos repetidos - ver mais aqui e aqui). O problema é que Set não funciona para objetos, então podemos usá-lo para guardar apenas o campo que nos interessa, que é o id:
function interseccao2(array1, array2) {
    var idsB = new Set(array2.map(b => b.id));
    var res = [];
    for (const elemento of array1) {
        if (idsB.has(elemento.id)) {
            res.push(elemento);
        }
    }
    return res;
}

Ou seja, primeiro eu crio um Set contendo os id's do array2. Depois eu filtro o array1, pegando os elementos cujos id's estão neste Set. O resultado será a intersecção entre os elementos. Também daria para escrever desta forma:
function interseccao2(array1, array2) {
    var idsB = new Set(array2.map(b => b.id));
    return array1.filter(e => idsB.has(e.id));
}

Fazendo um teste básico, as duas opções com Set se mostraram bem mais rápidas que a primeira solução acima usando some.
Mas novamente, para poucos arrays pequenos, a diferença será imperceptível (afinal, para poucos dados, tudo é rápido). De qualquer forma, é interessante atentar para esses detalhes, pois pode ser que um dia você precise processar muitos arrays maiores e saber desses pormenores pode fazer a diferença.

Enfim, agora que já sabemos obter a intersecção entre dois arrays, basta generalizar para vários, excluindo os vazios. Ficaria assim:

// calcula a intersecção entre 2 arrays
function interseccao2(array1, array2) {
    var idsB = new Set(array2.map(b => b.id));
    return array1.filter(e => idsB.has(e.id));
}

// calcula a intersecção entre vários arrays, ignorando os vazios
function interseccao(...arrays) {
    // pega somente os arrays não vazios
    var naoVazios = arrays.filter(array => array.length > 0);
    if (naoVazios.length == 0)
        return []; // se todos são vazios, não tem o que calcular

    var res = naoVazios.shift(); // começa com o primeiro array
    for (var array of naoVazios) { // calcula a intersecção com os restantes, de 2 em 2
        res = interseccao2(res, array);
    }
    return res;
}

let datasOne = [
  { id: 1, name: 'Gustavo' },
  { id: 2, name: 'Ana' },
  { id: 3, name: 'Luiz' },
  { id: 8, name: 'Alice' }
];
let datasTwo = [
  { id: 1, name: 'Gustavo' },
  { id: 3, name: 'Luiz' },
  { id: 8, name: 'Alice' }
];
let datasThree = [
  { id: 1, name: 'Gustavo' },
  { id: 3, name: 'Luiz' },
  { id: 2, name: 'Ana' },
  { id: 5, name: 'Kelly' },
  { id: 4, name: 'David' }
];

console.log(interseccao(datasOne, datasTwo, datasThree));
// [ { id: 1, name: 'Gustavo' }, { id: 3, name: 'Luiz' } ]

// testando com o segundo array vazio
console.log(interseccao(datasOne, [], datasThree));
// [ { id: 1, name: 'Gustavo' }, { id: 2, name: 'Ana' }, { id: 3, name: 'Luiz' } ]

Repare também que coloquei ponto-e-vírgula no final das linhas. Pode parecer "frescura", e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não usá-los, como essa e essa (veja mais sobre isso aqui).
Answer: Inicialmente criamos a função dataFilterByIntersectionName com o spread operator no argumento para criarmos um array com os arrays de objetos sem precisar saber previamente o tamanho dele.
Dentro da função começamos filtrando os arrays de dados vazios, no caso em que o resultado desse filtro gere um array de tamanho 1, isso quer dizer que só tem uma fonte de dados então retornaremos esse próprio array como você mesmo pediu no enunciado.
Agora criamos a constante returnedData para segurar todos valores que passarem pelo teste da repetição. Pegamos o primeiro array de objetos do filteredData para ser a base da comparação de nomes com nomes para obter o número de vezes em que o nome repete. Como vamos fazer a comparação? Vamos usar a primeira forEach para percorrer cada obj1 de dentro do primeiro array de objetos do array filteredData, e dentro do escopo desse primeiro forEach criamos um let count para segurar a contagem do número de vezes que o nome repete.
O segundo forEach do filteredData é para abrir o array de array de objetos, e o segundo forEach para abrir o array de objetos (repare que o argumento ...data cria um array de arrays de objeto), e por que isso? Porque comparando nome a nome pela varredura de todos objetos saberemos que se a quantidade de vezes em que o nome repete for numericamente maior ou igual ao tamanho do array de arrays de objetos, então esse nome está contido pelo menos uma vez em cada array de objetos, podendo haver o caso de existir dois Gustavo, por exemplo, em um único array também. Por isso a condicional comparando o nomes, pois se for verdadeiro a gente acrescenta a contagem em 1, depois de percorrer todos os arrays de objetos do array de arrays criamos a condicional para puxarmos o objeto com os dados para o returnedData caso verifique a condicional segundo a comparação do valor count com o tamanho do ...data, depois disso o primeiro forEach continua para o próximo objeto e zera a contagem, assim até varrer totalmente os nomes e retornar os dados.

const dataFilterByIntersectionName = (...data) => {
  const filteredData = data.filter((array) => array.length > 0);

  if (filteredData.length === 1)
    return filteredData;

  const returnedData = [];

  filteredData[0].forEach((obj1) => {
    let count = 0;
    filteredData.forEach((array) => {
      array.forEach((obj2) => {
        if (obj1.name === obj2.name) {
          count++;
        }
      });
    });

    if (count >= filteredData.length)
      returnedData.push(obj1);
  })

  return returnedData;
}


How to test for pairwise differences between factor levels while looking at an interaction with another factor?

Question: Let's say I have a survey with questions 1 through 10 about different characteristics of animals rated from 1 to 10 and this is repeated for 5 different animals.
Suppose I collect 50 surveys so my data looks something like:
<code>   Person Question  Animal Rating
1      P1       Q1     Dog      7
2      P1       Q1  Rabbit      3
3      P1       Q1     Cat      6
4      P1       Q1   Horse      3
5      P1       Q1 Hamster      5
6      P1       Q2     Dog      8
7      P1       Q2  Rabbit      5
8      P1       Q2     Cat      6
9      P1       Q2   Horse      3
10     P1       Q2 Hamster      7
</code>
Where Q1 could be something like: How cute is this animal?
Q2: How strong is this animal?
And so on…
Is there a way to compare the different types of animals and different questions to see which questions are related to which kinds of animal? This would be in order to find the highs and lows of each kind of animal.
I thought of conducting an ANOVA but this does not allow me to test for pairwise comparisons between each animal within each question.
From my data, I can see that there is a significant interaction between the questions and animals but can't decipher which animals within each question differ from one another – as the data is always compared against a base factor level (e.g. dog in this case).
The interaction between Dog and Q1 might show as significant when the base is Cat, but might not be significant when Rabbit is the reference level for example. And I don't think it would be valid to conduct many ANOVAs with different reference levels.
Is there a way to get a contrast matrix with the differences between each kind of animal for each question and their respective statistical significance?
Thanks in advance
Comment: You have two questions and five animals, so you have $(2-1)(5-1)=4$ DF for Q*A interaction. Partition the interaction sum of squares using four orthogonal 'contrasts' that express the comparisons you want to make. Test to see which contrasts are significant (ad hoc criterion).
Comment: @BruceET in my actual case I have 15 questions and 5 animals * 24 people completing the survey
Comment: Well, then there would be more contrasts, Provided that the Question-by-Animal interaction is significant, you would construct and test only at the ones of interest.
Answer: I don't think you need to overthink this. First, do your anova and test that the interaction effect is significant. Then create the scaled interaction effects, like so:
$$
\sqrt{25} \frac{(\hat{y}_{ik} - \hat{y}_{il}) - (\hat{y}_{jk}-\hat{y}_{jl})}{4s}
$$
where $s$ comes from the anova and $\hat{y}_{ik}$ is the average rating of animal $k$ to question $i$. These differences would have a standard $t$ distribution with 1288 degrees of freedom, $(25-1)(15-1)(5-1)$, so basically normal, if there were no interaction effects.
But you have just shown from the global test that there are interaction effects somewhere. So calculate the effects and see where you find major outliers from a normal distribution.
There is perhaps more art than science to this. Strictly speaking, you can't do standard t-tests on all these interactions -- they are not independent, you are doing multiple comparisons, and you already know that some of them must be "significant" since the global test indicated significance. It's more a question of ranking them and looking for the largest values and seeing if what you get makes sense.
If the significant interaction is due to one animal being weird or one question flagging a different quality than the others, this approach should indicate where the problem lies. But if every animal is sort of a one-off, this approach will be confusing. But in that situation, all you can conclude is that every animal is different with respect to the questions posed.
@BruceET's suggestions are also valid. With 15 questions and 5 animals, you can build up to 56 orthogonal contrasts, which you can test independently. These need to be chosen in advance of the analysis. My approach is more heuristic, and you don't get specific p-values out of it.
On the other hand, you might want to view this as a problem in measurement theory. Suppose your 15 questions can be grouped into a smaller number of traits -- say a cute/fierce axis and a trainable/not-trainable axis. It might make more sense to explore a factor structure for the questions and see if the same structure holds for all animals. Then you could compare the animals on the basis of how they load on the factors.


não consigo recuperar uma imageview no (R.drawable)

Question: Era para aparecer (R.drawable.image1) para que eu recuperasse ela mas sempre da esse erro na classe R.não sei mais o que fazer se alguem puder me ajudar nessa situação...
Answer: Aparentemente é por que falta importar a lib R.
Vai na linha onde ta o erro aperta "alt + enter" e importa a primeira lib que aparecer
Comment: funcionou muito obrigado


Weights in the neural network are not changing

Question: I have a neural network model with 20 layers. There are 30 input nodes and 5 output nodes. I am using backpropagation algorithm to train the model. I can see that in the first 5 layers, the weights are not changing. I don't understand why that is happening. Can someone point me in the direction of how to fix it?
Comment: How did you initialize the weights? Are your inputs continuous values? What's the typical range of these input nodes?
Comment: @horaceT zero weights initialzation lead to symmetry. To break the symmetry, I randomly assigned values to weight. All inputs are categorical inputs.
Comment: You have to be careful with weight initialization. If they're too small, it'd take many iterations to learn. If they're too large, the neurons could be saturated and would never learn.
Comment: I don't see what's off topic about this. Questions on ANN & deep learning are on topic here.
Comment: How are the gradients in different layers changing? Usually the problem is exploding or vanishing gradients.
Answer: There is nothing to fix. All knowledge you put into your model can be memorized in those last 15 layers. Probably your model is totally over fitting.
Explanation:
Back propagation works from layer to layer and tries to adjust weights to achieve expected results. If you have narrow and deep model expected result can be found just after altering 15 layers even if you have 20.
It also can easily cause model over fitting that happened to you. You have high accuracy with training set, and high error with validation set.
To avoid it you need to acquire much more data that will be able to "fulfill" model, or shrunk model to cause it generalize it's training.
Comment: Training accuracy: 0.98 and  10 Fold CV error: 0.25
Comment: I have a model with only 2 hidden layers, but still the first layer's weights don't change after training. Weird.


Does using JFace's Viewers preclude good MVC separation?

Question: I'm writing a GUI app that I want to use Swing and SWT. The end-user will specify somehow which should be used (it won't use both at the same time!). SWT is what I prefer generally and I have been looking at JFace, but it seems like if I use its most powerful features I will increase the coupling between the GUI and the model, and make it far harder to abstract the GUI so Swing can be used as well.
Is this the case? Can one use JFace without tying GUI details into the model or vice-versa?
Answer: For what I know, using JFace viewers ioffers quite good separation of view and model.
The only tight coupling here is the choice of the actual viewer implementation (e.g. using TableViewer versus TreeViewer to bind your model to either a Table or a Tree widget respectfully).
As to your first part of the question tat indicates you want for some reason to decouple your application from a choice of GUI framework, I would suggest you take a look at UFace project
UFace project aims to provide exactly what you seem to be aiming for -- a single UI implementation that can run against many GUI backends (it calls Providers):
UFace project page at the moment of this writing lists support for following providers:

JFace/SWT
Swing
GWT

(I have also heard rumors of some work being done on supporting Qt Jambi provider as well)
Comment: This sounds perfect! Thank you!
Answer: You can't switch dynamically. JFace calls SWT. It cannot be asked to call AWT instead.
As for whether JFace couples the model to the GUI, well, no. It has a set of model interfaces, but you can glue whatever model you like to them. It is up to you to do this cleanly if your customer wants the option of ripping out JFace some day.
Comment: I said that *I* want to use Swing and SWT, not the end-user. And it's out of the scope of the question, but I have a good reason for the requirement.

I'm not trying to get JFace to call Swing or AWT instead, I'm just wondering is it possible to build an MVC app where the GUI is seperated enough from the model that I can make it easy to switch (and the MVC approach is how I was told here to do that), but still gain from JFace's more powerful features?
Comment: You wrote: "The end-user will specify somehow which should be used (it won't use both at the same time!). " Apparently, I don't know what you mean by 'end user'.
Comment: I meant that the provision of the option between SWT and Swing is a decision I made. The end user will get to choose which is used at runtime.
Comment: That would imply a giant pile of parallel code for Swing and JFace, no?
Comment: Yup. But I want choosable user interfaces and MVC with a dash of programming to an Interface gives me that.


How to create an unsortable Field with multiple values?

Question: When a CCK field accepts more than one value, the widget will display a sortable table (usually with those cross-shaped handlers); this is the default behavior. I would rather have a non-sortable widget, since the order doesn't really matter. I hope this will avoid the usage of a table element, as well.
How can I achieve this? Do I need to use hook_form_alter()?
Answer: I think you'll need to create your own module for this. Instead of using hook_form_alter(), I'd suggest doing things the "cck way". CCK provides hooks which allow modules to provide custom widgets for CCK fields. You can create a module to provide a new Widget option for multi-value fields that doesn't use an HTML table, and doesn't allow for reordering. There's a great article on Lullabot about this. It also talks about creating your own fields and formatters, but you can skip down to the widget part at the end. The sample code is very well documented and should help you understand what's happening. At the very least this will be a great starting point. If something in the article doesn't make sense, feel free to ask for clarifications and I'll add what I can.
Comment: +1 for this method. It's the "proper" way even though it's quite involved.
Comment: this is the wonderful answer i was expecting, thanks a lot.
Answer: In lieu of another answer for the time being, have you considered hiding the handles using CSS or perhaps some jQuery?
Also, could you explain what you mean when you say 'avoid the usage of a table'? Did you mean database table, or HTML table?
Comment: I meant an HTML table element.


How does a SvelteKit load function access local storage, when it runs on server side?

Question: When visiting a deep link in my app, the component related to the deep link is the first page to be rendered, so I think its SvelteKit load function must run on server side, is that correct?
If yes, I wonder how does the load function access local storage? It needs data from local storage like user credentials, tokens and so on.
I tried, but it seems that it has access to load function only when it runs on client side, not on server side.
Thanks in advance!
Answer:
It needs data from local storage like user credentials, tokens and so on.

No, it does not. localStorage is a browser thing and you generally should not store anything security related in there (unless it is encrypted). If somehow a malicious script gets run, it would be able to access that information.
Authentication tokens should be stored in HTTP-only cookies.
The docs note:

The argument to a load function is a LoadEvent (or, for server-only load functions, a ServerLoadEvent which inherits clientAddress, cookies, locals, platform and request from RequestEvent)

So as you can see, in the server load function you would get access to the cookies.
Comment: So, the `load` function doesn't have access to local storage, but have access to `cookies`, is that correct? Sorry but I still don't understand how to access local storage. Could you elaborate a little further?
Comment: On the server it has access to cookies (`+page.server.js/ts`), if you define it in `+page.js/ts` it will run both on the client and on the server and it will not have access to cookies on the client. When it runs on the client you could access `localStorage`, but you should then make sure to not do so on the server. There probably is little point in doing so, though, because then the function behaves inconsistently.
Comment: To summerize it, as long as the `load` function runs on the server side, which is the case when visiting via a deep link, it does not have access to either cookies or local storage. Is this understanding correct?
Comment: You can simply ensure that it only runs on the server by defining it in `+page.server.js/ts`, that way it does not matter from where the page is accessed. And as stated, cookies can only be accessed on the server, local storage can only be accessed on the client.
Comment: Using HTTP-only cookies means you have to worry about CSRF attacks which you don't have to worry about if you store your tokens in localstorage. So it's a question of would you rather worry third party scripts stealing tokens or would you rather worry about protecting all of your endpoints against CSRF attacks. I wouldn't so adamantly say that storing tokens in localstorage is bad.
Comment: @hostingutilities.com CSRF is not that much of an issue any more. Most browsers will not just send credentials like they used to when the request comes from a different domain. (See [`SameSite`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite), which should have reasonable defaults and can be set to be sure.)


Metric to measure how "standard Gaussian" a set of samples is?

Question: Assume that I have a set of $N\in\mathbb{R}^{D}$ samples from some otherwise unknown multivariate distribution $p$. I seek a metric which might tell me how "close" $p$ is to a standard multivariate Gaussian distribution $\mathcal{N}\left(\mathbf{0},\mathbf{I}\right)$. I am particularly interested in metrics which can pick up on tricky forms of non-Gaussianity, such as those in the Datasaurus Dozen (below).
Can you recommend any metrics which might serve this purpose?
Comment: [tag:kolmogorov-smirnov-test]?
Comment: Interesting suggestion! I wasn't aware that there are variants of that test for multivariate distributions, but apparently there are (https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#The_Kolmogorov%E2%80%93Smirnov_statistic_in_more_than_one_dimension). Thanks!
Comment: The test isn't distribution-free in multiple dimensions, but the uniform norm on CDFs still a perfectly good metric.
Answer: One important question is whether you want a metric that says, for example, that a Binomial(0.5, 20) distribution is close to a Normal (because obviously) or far from a Normal (because it's discrete).
Another question is whether you want a metric for all distributions or just one for empirical distributions in datasets (so everything is discrete and has  probability masses that are multiples of $1/n$.
Yet another question is how much you care about ease of computation, and in how many dimensions.
For a metric on all distributions that says the Normal and Binomial are close, you want something that metrizes convergence in distribution.  The total variation distance or the Hellinger distance would be good.
For a metric on all distributions that says the Normal and Binomial are not close, you want something based on the likelihood ratio. If it doesn't have to be literally a metric in the topological sense, the Kullback-Leibler divergence would do; if it does, you could use the symmetrised Kullback-Leibler divergence
For something that's easy to compute on data sets (but hard to work with mathematically) you could use a nearest-neighbour distance such as $\max_y\min_x d(x,y)$ for the distance between a point in one data set and its nearest neighbour in the other (that's not symmetric, you can add the same thing with $x$ and $y$ switched to make it symmetric). Or replace the $\max_y$ by a mean over $y$ or something.
Comment: Yes, Stein-type distances would also be good, and they specialise nicely to Normal (and Poisson)
Comment: Thank you for the suggestions! That's a great answer, with a lot of nuances I didn't actively consider. I suppose the case I had in mind was the one in which the distributions likely aren't discrete, but approximated with a finite number of samples (with the hope that, as ensemble size increases $N\rightarrow\infty$, in the case $p=\mathcal{N}$, the metric would converge towards $0$). I'll look into the options you proposed! One other option I was aware of is the "Kernelized Stein Discrepancy", which is quite general, but I thought perhaps the Gaussian case yields some special solutions.


How to add theme from github with composer

Question: I have a Drupal 8 installation and I like to install a theme from github.com using composer.
It is this theme https://github.com/forumone/gesso
Can anybody help me what I have to add to the composer.json and where?
Answer: If you still want download theme from github, you can edit file composer.json by add more repository:
Add this code
 {
    "type": "package",
    "package": {
        "name": "forumone/gesso",
        "version": "2.0",
        "type":"drupal-theme",
        "source": {
            "url": "https://github.com/forumone/gesso.git",
            "type": "git",
            "reference": "8.x-2.x"
        }
    }
}

after
{
    "type": "composer",
    "url": "https://packages.drupal.org/8"
},

and run composer require "forumone/gesso"
 to download theme and update composer.lock.
Comment: Just to clarify here, the dev branch for this theme is parallel on both GitHub and drupal.org. Alternatively, one could do `composer require drupal/gesso:2.x-dev` to get the dev branch. To me it looks exactly the same. So, you don't need to pull from GitHub in this instance. The only time you would want to do this is when a package does not live on d.o. at all, 99% of the time they are on packagist (third party vendor). The rare case is when you have a private repo on GitHub, then this is the approach you would want to take.
Answer: Adding this answer for more clarification for future readers:
The theme in question as of this comment date has a stable release from April 2018. But the development branch is active and updated.
In such a case, you would do this to fetch it instead of the latest stable:
composer require drupal/gesso:2.x-dev
To go even further, you can tack a commit sha on the end of the version to 'pin` the code at that commit - unless you want rolling updates from HEAD. This is a versatile option that you can opt for in Composer that is not so known in the Drupal circles.
You don't need to pull from GitHub in this instance. The only time you would want to do this is when a package does not live on drupal.org at all, 99% of the time they are on Packagist (third party packages, like Prophecy etc).
The rare case is when you have a private repo on GitHub/GitLab or elsewhere, then this is the approach you would want to take to fetch it.
Comment: This is a good answer, because you give the advice of best practice. So I've learned a lot today. How to add package to composer.json and how to use dev-version with cli command.
Answer: You shouldn't use the Github repository, unless you're getting involved in the theme's development - it doesn't contain a composer.json file, so isn't supposed to be installed this way.
You could mess about trying to set it up as a custom repository, but given that this is a theme hosted on (and packaged by) drupal.org, it would be easier to just install it the standard way:
composer require drupal/gesso

Comment: @lesleyn. The development snapshot has been updated on February, 2019. If you want to know when the next official release will be made, you can check/ask on the theme issue queue, on drupal.org.
Comment: You would have to add the github repo as a new repository item and call it that way. It isn't ideal, and the Gesso theme should have updated its d.o. project as thats where everyone expects to obtain packages. https://getcomposer.org/doc/05-repositories.md
Comment: on drupal.org the files are from last year and on github from this year. That's why I want to install from github.
Comment: What @Kevin said. And just to add that when code isn't in a stable branch, it's often because it's not considered to be stable. i.e. don't run it in production without a plenty of testing. You can find out how to add a custom github repository in the composer docs, just make sure you have `type: drupal-module` if you want it to be moved into the correct folders etc when installing
Answer: In your theme root add composer.json as follow
 {
  "name": "my/theme",
  "description": "Theme.",
  "type": "drupal-theme",
 }

And in your main composer.json(Drupal) under "Repository" section add
{
  "type": "vcs",
  "url": "email@example.com:my/theme.git",
  "no-api": true
}

And then run composer update


Store C++ classes in JNI context

Question: I have two C++ classes, one for creating a factory and another of the type of object which this factory creates.
Code Snippet:
class A{

};

class Factory
{
    public:
        A *CreateObject(char *p);
};

Factory *CreateFactory(char *);

So, I want the similar classes on Java side, for Factory and concrete class A. But, I am not able to understand that, when I call the CreateFactory function through JNI, where should I store the Factory instance which it returns?
Please help!
Comment: Most of the time when you're using JNI you want the class representation to only exist in Java. JNI allows you to create native methods, which can access the Java Object that they're part of (if they're not static). If it is really necessary that you have c++ class instance you might want to store it as a long (bad practice) or, if you know the size, store it as a DirectByteBuffer (also bad practice).
Answer: You can associate native objects with Java objects by creating a private long field in the Java class and store the pointer to the native object in that field via JNI.
Comment: Exactly, I completely agree, I guess using JNI is something that you want to avoid. If anything go with [JNA](https://github.com/twall/jna) which has nearly no performance loss (unless unsafe JNI is enabled).
Comment: @Mast3rPlan: as native code is always. But that's the way the JRE classes itself do it. Notice the `private` modifier for the field. If you can't avoid using native code there aren't much alternatives.
Comment: I would say using a private long field is definitely the easiest way to go, although I still strongly suggest using the java class itself to store any data when possible.
Comment: @Mast3rPlan: Agreed. I recommend avoiding native code as much as possible. So usually the stored pointers are OS resources and not C++ objects in real life code.
Comment: Thank you for suggesting JNA

Store C++ classes in JNI context


What do experts expect to get out of this SE site?

Question: We've had a few meta questions where discussions focus on attracting (and presumably keeping) experts on this site.
I'd be interested to know what other experts and professionals hope to gain by being involved in this site?  What are your motivations for being here, and what do you like/dislike about the site so far?
I will not be so bold as to try define expert - if you consider your self a professional or expert submit an answer below.
Comment: +1. Nice question. Once it is populated with replies; a sister question of _What do enthusiasts and the wider public expect to get out of this SE site?_ could be useful to flesh out the whole gamut.
Comment: Hmm. If they saw my name on it, some academics I've rather annoyed this week might dismiss it out of hand. So I'm hoping someone else will, since the question has value to touch upon both commitment camps.
Comment: @LateralFractal why not write that now?
Answer: About me: junior academic faculty; microeconomist.
As an asker of questions, I envisage the following being useful (in decreasing order of usefulness):

Help on specific technical points. E.g. "I have this model, can anyone see a way to show that payoffs are quasi-concave?" or "Why does the equilibrium in this specific model not behave in the way one would expect/can anyone see a problem with the solution?"
"Professional recommendations". e.g. Recommendations for graduate level books or research papers on specific topics or suggestions regarding specific issues in/approaches to teaching economics.
Somewhat easier questions outside of my direct expertise. e.g As a professional economist, I would like to know more about macroeconomics and econometrics, but cannot ask questions on these topics with the same level of sophistication (alas, my human capital in these areas has depreciated too far).

As an answerer, I'll have a go at anything I think I can contribute to, but I would like to see more questions along the lines of the first point above as they provide a good exercise.
Comment: Strongly agree on all points, as well as ordering.
Answer: I am an Assistant Professor of Economics in a department that is somewhat distant from the centres of economics research. I hope that this site will deliver the same value as tea-time in a good research department. To elaborate

I want to be able to discuss the background assumptions, motivations
and vision behind technical questions in economics. I would specially
like to be able to get answers from more senior experts who may
understand things in ways that have been lost from the current literature.
I want to know what ideas are in the air in the research fields I am
interested in. There is a considerable time lag an idea becoming hot
among researchers at the forefront of a subject and its appearance in
print. I hope that this site will make such ideas more accessible to
me.
I want my thinking to be stimulated by questions from my peers
which are small enough to think over an afternoon but not entirely
obvious.
I want to calibrate my own level of understanding by seeing
what my peers think of my answers.
I want to reach out to more
students and beginners who are genuinely interested in economics and
are thinking hard about it.
Answer: I am a graduate student nearing the end of my dissertation. I strongly agree with @Ubiquitous' points. In addition, I'm hoping to see (and ask/answer) the following types of questions, organized by whom I would talk with "in real life:"

The types of questions that I might ask my adviser about research topics: "is X a good idea, why or why not -- what are key points of literature in this area -- what are some of the important technical considerations of this idea -- what are potential empirical strategies to bolster a methodology or theory implementing this point -- what are some theoretical papers to read if I am trying to prove X."
The types of questions I might ask other researchers/students like myself -- specific aspects of their research about which I am unfamiliar, or simply bouncing ideas for research off another researcher.
The types of questions I ask friends who are in the private sector or otherwise "working in the real world:" what are some specific features of a particular type of problem, so I might try to frame out a theoretical model I could bring to bear on that problem (which may or may not actually be useful for actual practice).

I'd even be interested in having more broad "practical strategies of research"-type questions. That is, boring things like how to solve the "annotate a pdf comfortably/naturally on a tablet" problem, or "practical computers for coding in every spare moment."  :)
Essentially, I'm hoping to find something like the wonderful "grad cafe" environment of the lunchtable at my most enjoyable PhD internship: other advanced researchers with whom I can "spitball," bounce ideas off of, and dig into technical questions (analytical issues for proofs, computational issues for simulations, statistical/data issues for empirical estimation).
Comment: +1 for that last paragraph!
Answer: As an industry professional, I'm looking to quickly find those technical bits of knowledge about the real world that don't make it to the text books.  I'm probably less interested in discussing economic theories and models in a broad sense than the academics probably are - simply because I will have already spent plenty of time discussing them in flesh and blood.
On the other hand, when reading analyzing economic data releases there are frequently tiny nuances that can make a difference to your interpretation of the data.
Perfect example questions for me so far are probably these:
How do reserves move between the 12 federal reserve banks? (asked by me)
How come the CBO reported the Federal Deficit for FY2014 was \$483 Billion when debt went up by \$1.1 trillion? (answered by me, but could well be the sort of thing I'd ask)
Obviously on the flip side, I am happy to share any technical knowledge I have to help the numbers add up for someone else.
That said, I am already enjoying reading some of the more broad and theoretical questions, and so I very much hope to learn a lot by hanging around.
Answer: I am not an expert, no you dont have to point me to my reputation here to prove that, I know for a fact that I am not, the reason I am answering is because this could be useful to attract experts as reasons that others here may not have thought of. But again, as an outsider (to the "experts" group) there is always a chance that I could be wrong.
First reason (Selfish to the expert) - There are many people using stackoverflow (referred as SO) site as a proof of their expertise, authors, consultants all kinds of people (Example:https://stackoverflow.com/users/1144035/gordon-linoff). academic expertise is one thing, ability to apply to practical questions is another, and so as a practical online resume this is helpful to some experts
Second reason (Wont work until the community grows) is that people who are at the top of the Maslow's pyramid may actually look at this as a social service, when this SE grows (which SO has achieved) people can see this platform as a place of choice to help people
Third reason (wont happen until this becomes very large) - this platform, if and when it reaches a size where most experts in this field would deem it necessary to participate here for one reason or the other your reputation would become your identity. Someone with 100000 reputation in SO is an expert, but someone with 400000 is at least seemingly better and hence becoming part of this community at the earliest gives them the edge
Comment: I don't think either of these points are too important. 1) With economics, a lot of people can half dangerous semi-knowledge and post and vote according to that. Having high reputation here is nothing I'd want to put on my cv, simply because it only signals that I "waste" time unproductively but not my expertise.
Comment: 3) I don't think this will be relevant, same argument as in 1. Having many votes doesn't make an answer necessarily correct, peer reviewing is a better solution (despite having its own problems).
Comment: 2) People who are on the top of the pyramid have many possibilities of doing "social service", and already have it as part of their job description.


Pass a @selector between classes, calling the method from an instanced Object

Question: I have a viewController with a method: doSomething:. I have a class Menu that sets up a menu with a button, on which I have "added a target" so I can call a selector from the button. This subclass is instanced from the viewController.
When I tap the instanced menu's button I would like to call the method in the viewController. The obvious way to set this up would be to add an observer to NSNotifications, but seems kind of klunky. Can I somehow pass the selector from the view controller to the instance like so:
in Menu.h
-(void)setupMenuWithAction:(SEL)action {

called from the ViewController:
[menu setupMenuWithAction:@selector(doSomething:)];

Tried it and it does not work, gives unrecognized selector error when the button is tapped, but I'm wondering if it is a valid concept, and if so how can I fix it.
Answer: Change the method in Menu.h to include a target -- make it -(void)setupMenuWithAction:(SEL)action andTarget:(id)target. Within that method, call the selector with [target performSelector:action];
Then, from the ViewController, call [menu setupMenuWithAction:@selector(doSomething:) andTarget:self];
Comment: @Mrwolfy Not a problem; didn't realize you wanted to directly add it as the action for a button. Use this -- ```[myButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];```
Comment: @Mrwolfy Got it. I edited it after posting changing ```object``` to ```target``` (because that's what Apple's documentation calls it). You must have used some bits of the original code combined with some bits of the new code :)
Comment: very interesting, but not sure how to add the bit: [object performSelector:action];... the method setupMenuWithAction: just makes a button and adds a target with the selector. Do I make another method to call performSelector:? sorry, being dense.
Comment: OK, yeah that makes total sense, and I did that. Still gives me the unknown selector error though.
Comment: @Mrwolfy Just went over it and it looks good to me. Just to be clear, ```doSomething:``` is a method in the View Controller, right?
Comment: yep, I double checked that. Triple checking now.
Comment: strangely, maybe, it works just fine if I add the target to the instanced button directly from the vc. Just seems less clean way to code it.
Comment: Ahh got it now. used this (addTarget:object) to add the target!         [button addTarget:object action:action forControlEvents:UIControlEventTouchUpInside];
Answer: For the function in the class that has the actual selector, use '+' instead of '-'. i.e. use the class method instead of instance method


Definition of indefinite integral and its existence

Question: I have a question regarding existence of indefinite integral.
Consider a function $f:\mathbb{R}\rightarrow \mathbb{R}$. Using the definition, this function is integrable on $[a,b]$ (i.e. the definite integral on $[a,b]$ exists) if $f$ is bounded on $[a,b]$ and the lower integral (supremum over partitions of the lower Riemann sum) is equal to the upper integral (infimum over partitions of the upper Riemann sum).
My question is: when does the indefinite integral of $f$ is well defined? Do we need $f$ integrable on any $[a,b]$?
Answer: It probably suffices to say that $\int_0^x f(t) dt$ exists for every $x$, since that implies integrability over any interval $[a, b]$. For once you know that exists, you can define
$$
F(x) = \int_0^x f(t)~dt
$$
and $F$ is an indefinite integral for $f$, by the fundamental theorem.
Any other indefinite integral for $f$ has the same derivative (everywhere) as $F$, and hence, by the mean value theorem, differs from $F$ by a constant.
Perhaps your question means "Is there a function $f$ that's not integrable over some interval $[a, b]$, and yet still has an indefinite integral?"
If you'll confirm that this is what you were really wondering, I'll try to answer.
Comment: Provided $[0,x]$ belongs to the domain of $f$.
Comment: The answer then is: a sufficient condition is $f$ integrable on any $[a,b]$. It is harder to say whether it is necessary. Right?
Comment: Yves: the domain of $f$ was specified as the whole real line. STF: yes, that's a good summary of my answer.


What is the correct html code to access Blockly Factory code?

Question: Using VSCode and Block Factory [https://blockly-demo.appspot.com/static/demos/blockfactory/index.html].
I've have this in index.html:

    ...
      body {
        background-color: #fff;
        font-family: sans-serif;
        overflow: hidden;
      }
      h1 {
        font-weight: normal;
        font-size: 140%;
        margin: 10px;
      }
      #defineBlocksWithJsonArray {
        float: bottom;
        height: 90%;
        width: 100%;
      }
    </style>

In index.js (Block Factory code):
'use strict';
Blockly.defineBlocksWithJsonArray([
{
  "type": "color_rgb",
  "message0": "Red %1 Green %2 Blue %3",
  "args0": [
    {
      "type": "input_value",
      "name": "RED"
    },
    {
      "type": "input_value",
      "name": "GREEN"
    },
    {
      "type": "input_value",
      "name": "BLUE"
    }
  ],
  "output": null,
  "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}
]);
javascript.javascriptGenerator.forBlock['color_rgb'] = function(block, generator) {
  var value_red = generator.valueToCode(block, 'RED', javascript.Order.ATOMIC);
  var value_green = generator.valueToCode(block, 'GREEN', javascript.Order.ATOMIC);
  var value_blue = generator.valueToCode(block, 'BLUE', javascript.Order.ATOMIC);
  // TODO: Assemble javascript into code variable.
  var code = '...';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.javascript.ORDER_NONE];
};

A debug console error message -> https://snipboard.io/i5gmtQ.jpg.
I'm new to JavaScript and to Blockly.  What is the correct html code to access the Block Factory code?
Answer: Change index.html to:

    <meta charset="utf-8">
    <title>Toolbox Customization Codelab</title>

    <link rel="stylesheet" href="toolbox_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">


Survival Analysis—Equal follow up time

Question: My question is whether my data are a survival analysis problem.
I have 3 groups (2 interventions and 1 control). The 200 patients are all followed up for 6 months only. The follow-up is done by observing the records in a public hospital for any readmissions. I am making the assumption that a patient does not visit any other hospital.
I am interested in the time (in days) to readmission of the patients after their initial discharge. The time of the initial admission was the time they entered the study. The start date is not the same for all individuals – a range of 2 years, more or less.
Basically I have different start times, but the censoring time is the same for all censored patients. It is 180 days for all censored patients.

Does this affect the survival curve or the comparison between the groups?
Is there another analysis that I should apply that nbetter matches my data and setting?

When running the Kaplan Meier curve in SPSS, I get a straight line (going down) at the 180 days (x axis). Is this OK?
Answer: Yes, these are survival analysis/event history analysis data.
The beginning of time in survival analysis is rarely calendar time, but is the first day the individual was observed in the study. This affects your interpretation in that intervention/treatment effects are understood to affect person time (e.g. to affect the hazard function in a given abstracted notion of "days since start of observation", or "days since diagnosis" or "days since treatment"... depending on the nature of your study design), rather than affecting the hazard function in terms of calendar time (i.e. you are not trying to estimate change in hazard due to treatment on June, 3rd, 2014).
If you only followed people for 6 months: that's 180 days; unless everyone experienced readmission by 180 days, there should be some right censoring, and the survival curve should not plummet to 0 at 180 days.
Comment: If 50% survived, then 50% did not, and cannot be censored by definition, if "(right) censored" means "observed without ever experiencing the outcome."
Comment: thank you for your answer! I just discovered what went wrong with the plummet curve. Coding issue.
Comment: just came across  and I was wondering whether by having all my censored cases at 180 days would violate the censoring independence assumption. Additionally, I have approximately 50% of the patients that survived. Does this violate any assumptions? (i.e. high censoring)

Survival Analysis—Equal follow up time


Getting the path for .NET Core runtime Dlls

Question: I inspect .NET dlls with the MetaLoadContext, introduced in .NET core 3.0.
Since the MetaLoadContext needs an assembly resolver (e.g. the provided PathAssemblyResolver) , I want to create an own one which has the strategy that it loads the .NET runtime DLL (e.g. netstandard.dll) from the SDK installation path. The issue is how can I get programmatically the SDK installation path with the runtime DLLs ?
Answer: To get the path of the runtime .NET core DLLs call
<code>System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
</code>


Comparar valor diferente, valor "null" não entra no resutaldo

Question: Tenho uma tabela de arquivos, e nela existe um campo chamado "tipo_documento", que é preenchido com 1 ou quando não é preenchido fica NULL, o problema é que quando eu dou um SELECT e uso o comparador para retornar todos os resultados com o tipo_documento diferente de 1 (AND tipo_documento <> 1), os dados que possuem NULL não são retornados, por que isso ocorre?
A forma que eu achei para contornar isso foi assim:
AND tipo_documento <> 1 OR tipo_documento IS NULL

Comment: O valor NULL significa que o valor dos dados para a coluna é desconhecido. Um valor desconhecido não pode ser comparado com outro valor. Use-se as cláusulas IS NULL ou IS NOT NULL para testar um valor NULL.
Answer: Qual é o tipo do campo?
Era realmente para funcionar só com AND tipo_documento IS NULL.
Comment: É porque poderá ter outros valores, mas por que só o diferente de 1 não basta?


How to allow powershell to download an EXE from a .net core MVC web app?

Question: I have a .net core MVC web app that depends on a .net framework console app.  When the Core app builds, so too does the console app and I get the exe in the bin directory:

This is working great, however now I need to provide an endpoint through the web app that allows anyone to download the EXE (the intent is to allow a powershell script to download the exe via an endpoint).
How can this be achieved?
I understand the following can be used to actually download the file:
Invoke-WebRequest http://localhost:8080/download/tokenizer.exe -OutFile c:\download\tokenizer.exe

However I don't know how to get the exe accessible.  I believe I need to move the EXE from the bin to some directory that I then configure as being publicly accessible, but I'm lost on the details here.
Comment: How are you serving the rest of your static content? (`wwwroot`?)
Comment: @SLaks I just checked and yes it's `wwwroot` - I'm a bit new to .net core conventions.  Does that mean I need a post-build event to copy into wwwroot?
Answer: By default ASP.NET Core static files middleware will only serve content types that it understands.  Unknown file types will return a 404.
The middleware can be configured to serve unknown file types, however it is safer to add your own content types explictly:
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".exe"] = "application/vnd.microsoft.portable-executable";
app.UseStaticFiles(new StaticFileOptions
    {
        ContentTypeProvider = provider,
    });

Answer: .Net Core applications serve static files from the wwwroot directory (you can see this configured in Startup.cs).
To serve a static file, you need to copy it there.
Comment: Is any custom configuration needed to support `GET` with `exe` files?  I know .net framework / web.configs needed some coercing in this situation...
Comment: And - do you know what the best way to copy a file to wwwroot from the `bin` directory would be?
Comment: I don't think .Net Core does any filtering by extensions.  You should use a Post-Build event.
Comment: Right - that's what I'm playing with now.  I'll create another question for this.  Thank you!
Comment: I have the file being copied via `copy /Y $(ProjectDir)bin\debug\netcoreapp2.0\tokenizer.exe $(ProjectDir)wwwroot\exe\tokenizer.exe` and see it however navigating to `/exe/tokenizer.exe` gives me a 404.  Any ideas?
Comment: djones answer highlights that it will by default deny unknown file types. Putting in wwwroot is not enough.


Dificuldade com laço for em Ruby

Question: Estou com dificuldades de exibir dinamicamente o conteúdo de variáveis.
Por ex:
        minha_var_1 = %{Um texto}
        minha_var_2 = %{Outro texto}
        minha_var_3 = %{Mais outro texto}

Mas, já tentei exibir tanto com:
        for i in(0..2)
          puts minha_var_"#{i}"
        end

Como:
        for i in(0..2)
          puts "minha_var_#{i}"
        end

Sem lograr sucesso.
Qual seria a maneira correta de exibir este conteúdo dinamicamente?
Comment: puts( ' loop #1 ' )
for i in ["texto1","texto2","texto3"]  do
        puts( i )
end   seria isso que tu quer?
Comment: Obrigado pela resposta @haykou, mas testei e não funcionou...
Comment: Usando array eu consigo fazer a exibição, mas sem a utilização de arrays nada...
Answer: Se você realmente quer acessar múltiplas variáveis em um loop, a linguagem permite isso. Pode usar a perigosa função eval, que recebe como argumento um código no formato de uma string e o executa. Assim eval("1+1") resulta em 2 e eval("system 'shutdown now'") desliga o seu computador. Portanto você pode acessar suas variáveis usando eval("minha_var_1") ou eval("minha_var_2"). É uma questão de construir a string certa e passar para o eval.
minha_var_1 = "Um texto"
minha_var_2 = "Outro texto"
minha_var_3 = "Mais outro texto"

for i in 1..3
  puts eval("minha_var_#{i}")
end

Mas, é claro, não existe nenhum motivo concebível para você querer usar um código assim. Use arrays ou um hash para essa tarefa:
Usando Array:
minha_array = ["Um texto", "Outro texto", "Mais outro texto"]

for i in 0..2     # note que arrays contam a partir do zero
  puts minha_array[i]
end

Usando Hash:
meu_hash = {
  1 => "Um texto",
  2 => "Outro texto"
  3 => "Mais outro texto"
}

for i in 1..3
  puts minha_array[i]
end

Answer: Creio que a solução utilizando uma array é a mais apropriada.
# Declarando as variáveis
var1 = "um texto"
var2 = "outro texto"

# Atribuindo o valor das variáveis ao array
array = [var1, var2]

# Realizando a iteração através de cada item do array para que seja exibido na tela
array.each do |item|
  puts item
end

O resultado exibido no console será:
um texto
outro texto

Answer: Propensa solução fazendo uso de arrays:
    #criando o array de strings
    minha_var = [%{Um texto}, %{Outro texto}, %{Mais outro texto}]
    #exibindo o array com laço for
    for i in(0..2)
      puts minha_var[i]
    end

Mas não achei uma solução sem a utilização de arrays...

Dificuldade com laço for em Ruby


How to order nodes with a number like 1.1.1

Question: I have a long list of files to be downloaded with different categories.
So I created a node for each file.
And assigned a term field for the categories
A file can be used in different categories so I cant sort by posted date or the order might be wrong.
Is it possible to create a text field on nodes and then order them in a view based on that number? Example

1.1.1
1.1.2
2.1.1
2.1.2

Views Natural Sort might work for this but I can only get it working on titles.
Answer: You can do this with hook_views_query_alter(). I had a similar requirement few time ago where i have to sort nodes where title those have numbers should display before the nodes those have alphabets.
Here is a snippet i created at dropbucket.rog
http://dropbucket.org/node/1484
Steps:

Add one new text field to the content type you using for files. use textfield because integer or float type field will not allow you value in format 1.1.1.
Create a view.
Add a sort criteria the field you added either desc or asc. because you are going to alter this in hook_views_query_alter().

I tried with textfield name "sort". Change the field name whatever you use in content type, in query alter. You can get field name in view query display if query display is enabled in views settings.
Create a custom module.
<code>function custom_views_query_alter(&$view, &$query) {
  if($view->name == 'your_view_name'){
      // Remove all the sort order fields.
      $query->orderby = array();
      // Show number before the alphabets in titles.
      // This is trick which add 0 to the field to cast it to number then check the not equal to condition.
      $query->orderby['0']['field'] = 'field_data_field_sort_field_sort_value+0<>0';
      $query->orderby['0']['direction'] = 'DESC';
      $query->orderby['1']['field'] = 'field_data_field_sort_field_sort_value';
      $query->orderby['1']['direction'] = 'ASC';
  }
}
</code>
Comment: Amazing thank you so much for the in detail answer


Build context menu for news articles (sample image included)

Question: I have a complex view that queries and presents a lot of news articles depending on year and month contextual filter arguments. Everything works fine so far. However, now I want to show kind of context menu next to the view result that looks like this (shows multiple screens with different menu content depending on current display):

What is the best/most elegant way to realize such a context menu? (no ugly hacks)

What I've already tried
I tried to accomplish that using the Views UI – no luck. Creating two different View blocks (one for a list of years and one for the months of currently selected year) didn't work, because in order to get a distinct result set I need identical fields that are used for "collapsing". The field I used was "Post date" – and this always differs.
I guess that I must write a custom module where I leverage the Views API and create that markup for the context menu. But where do I start? And how can obtain the current contextual filter arguments?
Answer: Not really an answer, but perhaps a lead.  In Drupal 6, a similar thing was accomplished with the book navigation block.  You could have the book navigation block filter to a certain number of steps up/down tree from the node page that you were currently viewing.
I am not sure how this could be accomplished with existing views configuration, as I think tree navigation is not a common thing for views.
This is more the kind of trick I would expect to find in Taxonomy, based on the vocab's hierarchy.  There, navigation can be a more certain thing, as the structure is defined in the vocab, and they are just filling the tree leaves with tagged nodes.  Again with the Drupal6 reference, but perhaps you can scavange code from http://drupal.org/project/taxonomy_treemenu
If you do code something, release it back to the community?
Comment: Thanks for your response! In the meantime I found  solution. I created two Views blocks and implemented some views alter hooks where I inject values for contextual filter arguments. Works like a charm (even caching).
Answer: Perhaps views tree can give you what you need
https://www.drupal.org/project/views_tree


Nonlinear funtionals of smooth maps between Riemannian manifolds

Question: Let two smooth Riemannian manifolds $M$ and $N$, and let $C^{\infty}(M, N)$ be the family of smooth maps between them.
I would like to study functionals of the form $$E[\cdot]: C^{\infty}(M, N) \to \mathbb{R},$$ where for each $F \in C^{\infty}(M,N)$ i.e., a smooth map
$$F:M\to N,$$ $E[F]$ represents strain or energy of the map $F$ (but the energy can be negative etc.). The following three properties define what I mean by strain:

Continuity, i.e., $E[F]$ is continuous in $F$ (in some norm on $C^{\infty}(M, N)$, see definition below for elaboration)
$E[F]$ is a valuation on $M$ (please see definition below in elaborations)
$E[F]$ is invariant to rigid deformation of $F$ (please see definition below in elaborations)

My goal is to better understand this family of functionals and how they can be represented. To get handle of the subject, I would like to understand if one can represent them using integrals on $M$.
So that given arbitrary $E[\cdot]$ we can always write
$$
E[F] = \int_M  D_F(x) dV_n, \tag{$\ast$}
$$
where $dV_n$ is volume form on $M$ and $D_F(x), x\in M$ is some kind of density on $M$ that depends on $F$ in a reasonable fashion.
To make progress with this question (and really understand if it makes sense to pose it) here are few things I struggle with:

Find a good reference for functional analysis in this general case, where the functional is not linear.
Is there some hope to prove my claim $(*)$, if yes what one can try to say about the density $D_F(x)$, how does it depend on $x$ or on $F$, e.g., is it for example necessarily continuous in $F$?
Is there any principal way to generate such functionals, if not by using integral, perhaps one can approximate any such functional by some simpler nice functionals (just like continuous functions can be approximated by smooth bump functions)?

Below are elaborations and definitions of the terms used above with an example of such a functional: Dirichlet energy.
Any comments, answers or thoughts on the subject would be greatly appreciated.

Elaborations:
I have a smooth map $F$ from a smooth Riemannian n-manifold $M$ to $N$
$$
F: M \to N.
$$
Suppose I want to compute Dirichlet energy of $F$ in this very general setting and better understand what kind of functional this energy is.

To this end I define a functional, $E_D[F]:C^{(\infty)}(M,N) \to \mathbb{R}$, given by:
$$
E_D[F] := \int_{M} \mathrm{Tr}\left\{\mathrm{det}(DF)^\top\mathrm{det}(DF)\right\} dV. \tag{$\ast\ast$}
$$

The above can be interpreted using the following inner product on $C^{\infty}(M, N)$ (smooth maps between smooth manifolds $M$ and $N$):
let $F,G \in C^{\infty}(M, N)$ define:
$$
\langle F, G \rangle_D := \int_{M}  \mathrm{Tr}\left\{\mathrm{det}(DF)^\top\mathrm{det}(DG)\right\}  dV,
$$
$$
\|F\|_D^2 := \langle F, F \rangle_D.
$$
So that $E[F] = \|F\|_D^2.$
What properties does $E_D[F]$ have as a functional on $C^{\infty}(M, N)$?:
(Edited: As pointed out in the comments, this definition of inner product is a sloppy one and one needs to introduce connection on manifold $N$ to make the product of Jacobians meaningful)

Continuity. The functional $E_D[F]$ is continuous (in the above defined norm)

i.e., for small enough
$$
\|F- G\|_D <\delta,
$$
we have
$$
\left|E_D[F] - E_D[G]\right| < \varepsilon.
$$

Valuation. In addition, the functional $E_D[F]$ is a valuation on $M$.

By this I mean  that if we cover $M$ by submanifolds $U, V \subset M$, i.e.,  $M = U \cup V$, such that $U \cap V$ is also submanifold of $M$. Then we can compute $E_D[F]$ by considering the following maps:
$$
F|_U:U \to N,
$$
$$
F|_V:V \to N,
$$
$$
F|_{V\cap U}:V\cap U \to N.
$$
Then
$$
E_D[F] = E_D[F|_U] + E_D[F|_V] - E_D[F|_{V\cap U}].
$$

Rigid deformation in-variance Let $V$ be a smooth vector field on $N$, we can use $V$ to define, for each point $p \in N$, an integral curve $\gamma:[0, b] \to N$, which is the curve on $N$ characterized by the property
$$
\gamma(0) = p,
$$
$$
\gamma'(t) = V_{\gamma(t)},~~t \in [0, a].
$$
Roughly, all of the integral curves of $V$ define a flow $\Theta_V: N \times [0, a] \to N$ of $V$ on $N$. With the help of integral curves, we can now make sense of what we mean by applying $V$ to $N$ ($V$ acts on $N$). This can be interpreted as mapping each point $p\in N$ by the flow of $V$ . Which in turn means  that we are moving each point along the integral curve of $V$ for some time $t \in [0,a]$. So that for a fixed $t \in [0,a]$ we have

$$
\Theta_V^{(t)}: N \to N,
$$
we can now make sense of composition $\Theta_V^{(t)} \circ F: M \to N$, and compute Dirichlet energy of this composition:
$$
E_D[\Theta_V^{(t)} \circ F].
$$
Dirichlet energy has this property, that if the Vector field $V_K$ is Killing vector field (this is specific field that preserves the Riemannian metric $g$, i.e., for Lie derivative we have $\mathcal{L}_V g = 0$ and therefore Killing vector field defines isometric transforms of $N$) we have:
$$
E_D[F] = E_D[\Theta_{V_K}^{(t)} \circ F].
$$
Reiterating my question, I want now to consider the family of all functionals that have the listed property and understand if they all have the form $(**)$, more generally if one can write them as an integral with those other density.

References
- I found this question on mathoverflow that seems to be somewhat
related.
- Another paper that looks at a similar setting
Comment: First, most manifolds do not have nontrivial Killing vector fields. Second, some $N$ might have too much: for example on $S^2$, there are infintely many Killing vector fields so that the flow sends the south pole to the north pole (think of rotations along the plane passing through both points, there are infinitely many such planes)
Comment: I dont think your inner product is well defined. DF and DG are sections on different bundles.
Comment: @ArcticChar I agree it is unconventional but I think it is well defined. Let $p \in M$,  you are right that one differential maps to $T_{F(p)}N$ while the other maps to $T_{G(p)}N$, those are two different vector spaces. However the dimensions of both those vector spaces match, now if I fix some orthogonal frame on $N$ and $M$. Then both $T_{F(p)}N$  and $T_{G(p)}N$ can be written as matrices of the same dimensions. So I can just take matrix product (with transpose) so it seems to me that the inner product is well defined (doesn't mean it is a smart one though :)).  Am I missing somethings?
Comment: @ArcticChar alternatively one can probably plug in a transition matrix using flow on $N$ so that I can compare the two different vector spaces (just like with the definition of Lie derivative).
Comment: It is still not well defined. The way you define it, it is dependent on the orthornormal basis.
Comment: @Arctic Char, If I have metric on $N$ this yields me Killing vector field on $N$, so I can use it to define flow on $N$ that moves vectors around while preserving  the metric, then use this flow to compare different tangent spaces. This will require to patch the inner product definition and plug in between the Jacobians a transition matrix (built from flow of the Killing vector field). Do I still miss something?
Answer: The Dirichlet energy example is well understood, and you can find a wealth of literature under the name minimizing harmonic maps (this is what its minimizers are called). Partially answering your question no. 1, you can expect some unexpected features in the analysis of similar functionals:

The function space is not a linear space, let alone an inner product space (as pointed out in a comment, there's a flaw in your description of the inner product).
It makes a difference whether your function space consists of smooth functions or Sobolev functions. That is, it's possible that smooth functions are not dense in the corresponding Sobolev space $W^{1,2}$.
Related to the previous point, there's something called the Lavrentiev phenomenon: the infimum of the Dirichlet energy can be strictly smaller on $W^{1,2}$ than on $C^\infty$ (say, if you prescribe some boundary data).
The Euler-Lagrange system for this functional is nonlinear (if you write it in coordinates or via an embedding) and smoothness doesn't follow from it automatically (like it does for similar functionals in the flat setting). And indeed, Sobolev minimizers can have singularities.

Ad 2, I cannot say anything for certain, but it does look like your "valuation" axiom forces the functional to look like a measure. If it was replaced it with a stronger axiom
$$
E[F|_M] = \sum_i E[F|_{U_i}]
\quad \text{whenever $U_i$ are disjoint and sum up to $M$,}
$$
then we would say that $\mu_F(U) := E(F|_U)$ is a measure and thus $E(F|_M) = \int_M d \mu_F(x)$ - which means that $E$ is an integral of a measure, although a priori this measure doesn't have to be absolutely continuous. In larger generality, there might be some pathological examples (similarly to how not every finitely additive measure is also countably additive etc.), but I'm not sure if this is what you're looking for.


Convert a POCO to json using only certain fields

Question: I have an object, Project, that contains many fields, some complex some not. It is an EF class, so I can't edit it to add attributes.
I just want to generate a JSON object containing 2 of the fields (one int (id) and one string (name))
I'd hate to create another ViewModel just for this...
In my viewmodel I have a List<Project>. Is there a way to use HTML helpers to get a JSON representation of only the properties I choose without using attributes?
Here is an example of the Project class:
public class Project
{
    public int Id {get; set; } <-- Serialize this
    public string Name { get; set; } <-- Serialize this
    public Object AnotherObject [ Get; Set; } <-- Ignore this
    ....
}

I'd like it to become:
[{"id":"27","name":"test1"},{"id":"34","name":"test2"},{"id":"35","name":"test3"}]

The ultimate goal here to is output the json directly to the view as a var so that it can be used in building a JsGrid.
If there is a way to do it with Html helpers, that would be great.
Thanks!
Answer: Json.NET has a great built in ignore feature. If you tag the Property you want to exclude with the [JsonIgnore] attribute, the serializer will not serialize that property.
[JsonIgnore]
public bool IsValid { get; set; }

Comment: Also note that if you decorate the class with `[DataContract]` or `[JsonObject(MemberSerialization = MemberSerialization.OptIn)]`, you can get it the other way around - so that properties are only serialized if you decorate them with `[JsonProperty]` or `[DataMember]`
Comment: Yeah.. I guess your right. I'll make a viewmodel for each class and just re-use them later if I need. Using EF is nice, but it also trips you up when trying to do other things...
Comment: I am aware of that feature. In my question I specifically stated that using attributes is not possible as the class is an EF class and I want to avoid creating a viewmodel just for one class.
Comment: Well you can use the attribute decorations in your EF models, assuming that you have Json.NET in that assembly, but that isn't a very good option.  Unless you want to write some custom Reflection routines, I would just make a view model.  That would be the SOLID way to do it. (entity for data access, view model for display in the UI)
Comment: EF can be a blessing and a curse.  Its usually a good rule to keep the EF POCOs as strict representations of your data and only use it with database access.  Since your DB tables are probably not 1 to 1 representations of what your UI displays, view models or DTOs are encouraged and inevitable.
Comment: As someone who REALLY believes in DRY (don't repeat yourself), the whole concept of models, view models, DB models, entities, etc drives me absolutely up the wall. I am constantly searching for ways to re-use what I have and the answer is almost always to re-write it in a *slightly* different way...
Comment: I think DRY is an important principle, but if you take it too literally you can potentially run into design flaws. Your models (although similar in the data they contain) serve different purposes.  Your EF models have virtual properties, your view model has the JsonIgnore attribute. I would argue that you aren't repeating yourself because functionally these are different things. I think DRY applies more to code where you have methods/routines that constantly apply logic to a string and return it, or convert a type to another, etc. If you do that in more than one place than DRY comes into play.


Split old .NET code into designer partial class

Question: I'm working on an older .NET code base that has all the designer code stuffed into the same code file as my code (pre - partial classes).
Is there a mechanism to tell Visual Studio 2008 to go back and refactor designer code into a X.designer.cs partial class file?
Comment: This is duplicate of http://stackoverflow.com/questions/762528/how-to-automatically-convert-vs2003-classes-to-partial-designer-cs-files
Comment: I wrote myself a snipper for code of the Designer.cs, which is a good compromise between doing it all by hand, or trying to automate everything.
Answer: What I just did was completely manually:

Create yourform.Designer.cs
Add it to Visual Studio (right click, add existing item)
Add the partial keyword to your existing class.
Add the namespace exactly like in the original cs to the yourform.designer.cs
Inside this namespace, add the class definition (don't forget to include the partial keyword). Do not add inheritance and/or interfaces to this partial class in Designer.cs.
After this is done, you're ready to cut and paste the following:

a) Remove the components object you might have in your original Winform. If the application was .NET 1.1 you will have something like this:
    ///
    /// Required designer variable.
    ///
    private Container components = null;

b) Add a new components object in the Designer class:
    ///
    /// Required designer variable.
    ///
    private System.ComponentModel.IContainer components = null;

c) Unless you had a specific dispose method, this is the standard. If you don't have any form Inheritance, I think that base.Dispose can be safety removed:
    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose( bool disposing )
    {
        if ( disposing && ( components != null ) )
        {
            components.Dispose();
        }
        base.Dispose( disposing );
    }

d) Copy all the code inside the  #region Windows Form Designer generated code to the new Designer.cs class.
e) You should also copy all the member variables for all your objects (labels, texboxes, etc. that you use in the designer).
That should be all about it. Save and compile.
Remember that a partial class can be split among N number of files, but all must share the SAME namespace.
Is it worthwhile?
Well, in my case, I had a bunch of huge winforms with tons of code and controls. VS2008 crawled every time I switched from/to designer. This made the code view more responsive. I remember having to wait for 3-5 seconds before having a responsive code. Now it takes 1…

UPDATE:
Doing steps 1 to 5 and moving an existing or adding a new control won't automatically move anything to the designer.cs class.
New stuff goes to the new Designer class, but old stuff remains where it was, unfortunately.
You also have to close and reopen the file (after you have added/created the partial class) for VS to draw correctly in the Designer; failure to do may result in empty forms being drawn.
Comment: +1 this is what I did to some of the massive forms in our project at work.  Makes it so much easier to diff the changes without the forms designer code in them.
Comment: I'm surprised you had to go through so much trouble. Once you've created the partial class in the correct namespace, little more should have been necessary, since the Designer serializes to code (in the partial class). This is why it overwrites manual changes if you're not very careful. If you've got more of these to do, try doing all but moving the members. Then, open in Designer, change something trivial, and then Save. See if it moves the members at least.
Comment: That's what I thought, but if you do steps 1 to 5, you end up with an empty partial class. Moving a control in the designer then saving the form doesn't move anything to the Desginer class. (I've tried all that before resorting to manual). I'm trying again as I type. Nothing happens. Will see what is the "minimum" you have to move.
Answer: If anyone is still looking for an automated method of doing this there's a VS macro here that will do most of it for you.
A very nice tool.
Comment: While the link posted here works, it takes you to a blog post, that blog post has a DropBox link for the actual macro, and unfortunately that DropBox link is now dead.
Answer: I have had good luck with the free stand-alone application DeCodEx (Designer Code Extractor).
DeCodeEx loads in a Visual Studio project, detects which files are WinForms, and automatically splits designer code out of the original .cs or .vb file into a new .designer.cs or .designer.vb file.
For large projects it is much easier than trying to manually split out the files yourself.
Comment: Thanks for your good suggestion. Please note that each source file must have only one class definition before convert.
Comment: This works, but the tool uses an old version of c# and vb.net languages, so some features like anonymous functions, & intended & _ don't work. I've use vs 2019 so I had to replace things like that before starting the conversion. The tool works with utf-8, some of my files were in other encodings, so I've to convert too. link to the utf-8 visual studio: [https://stackoverflow.com/questions/43800861/convert-all-cs-files-to-unicode-in-visualstudio]
Answer: To merge the yourForm.designer.cs to yourForm.cs, Follow the below steps
Edit .csproj in notepad and add the following code
<Compile Include="yourForm.designer.cs">
    <DependentUpon>yourForm.cs</DependentUpon>
</Compile>

Comment: There is no need to do this in the latest versions of VS.NET. At least, in VS 2017. To add the .Designer.cs to the existing old form, I right-clicked the project node, selected the Add New Item command, typed in the corresponding name of the file - and VS added it as a subnode for the form's main file and created this  key in the .csproj file automatically.
Answer: Is the solution file of the older .NET code 2003/2005?  I've tried to do what you're talking about by using the conversion wizard in VS2008.  During conversion it should try to parse your .aspx pages and build designer files for them.  What the designer generator has a problem with is that these older .aspx pages are so malformed that they simply can't be parsed.
I've come to the realization that perhaps trying to convert old ASP.NET code up to 2.0 or 3.5 is, in itself, going to be a large project.  I have not yet found an effective way to factor out the designer code from old existing code, so I'd also be happy to learn of a solution here.
Comment: I'm actually working on a winforms app.  As best as I can tell, it didn't even make an attempt during the conversion to VS2008.
Comment: Oh, my bad.  Yeah, I'm not sure about your situation then; hopefully somebody can come back with something useful!
Answer: If it's WinForms - I have a PowerShell script that edits the project and adds .designer.cs for all forms/controls.
You'd still have to move the designer code by hand though (or improve the script) - I only had a few forms and it wasn't worth the effort to add that too.
I can look it up and post it if that would help.
Comment: nah, since it's not fully automated it's probably not worth the trouble.  As the other commenter says, it's not *that* big a deal.  Just a little annoying.
Answer: I'd be interested to see what happens if you open one of these forms in the designer and save it; or modify it and save it; or do one of the above after creating a .designer.cs file with only an empty shell of the partial class. It wouldn't surprise me to find the designer placing at least the changes into the .designer.cs file.
Comment: I've just did that. Had an old winform (NET 1.1) I opened in VS2008 with .NET35. I created (notepad) the designer.cs and added it to VS. The IDE detected it, but unless you add the 'partial' and add the class to designer.cs, VS will ignore it. Both forms must be in the same Namespace. I also had to change the System.ComponentModel.IContainer; in .NET 1.1 was different. I copied/pasted Dispose method, the definitions and the InitializeForm method. It worked. Can be a pain if the form is a mess :)
Comment: Sorry for the typo: I've just DONE that. :)


xsin(1/x) Holder on [0,1]

Question: I know $x \sin(1/x)$ is not Lipschitz on $[0,1]$, but some experimentation makes me conjecture that it is $1/2$-Holder.  What is a good way to prove this?
Comment: it is not Lipschitz
Comment: Right, I was about to fix that.
Answer: Check this paper and the first reference paper. https://arxiv.org/pdf/1407.6871.pdf
Answer: I will sketch the proof that $f(x)=x \sin(x^{-1})$ is 1/2-Holder on $[0,1/2\pi]$.
There are two cases.

If $x,y\in [\frac{1}{2\pi (n+1)} , \frac{1}{2\pi n}]$.

Write $x= \frac{1}{2\pi n+ \xi}$ and $y=\frac{1}{2\pi n+\zeta}$ where $0 \le \xi,\zeta \le 2\pi$.
There exists a constant $0<c_1$ such that
$$| f(x)- f(y) | \le c_1 \frac{|\xi-\zeta|}{n} \le  c_2 \frac{\sqrt{|\xi-\zeta|}}{n} $$
On the other hand
$$ \left| x-y \right| \ge \frac{|\xi-\zeta|}{\left( 2\pi (n+1) \right)^2} $$
So that
$$| f(x)- f(y) | \le c_3 \sqrt{|x-y|} $$

Without loss of generality, we can assume $y\in [\frac{1}{2\pi (n+1)} , \frac{1}{2\pi n}]$ and that $x<\frac{1}{2\pi (n+1)}$.

Then, by periodicity of sinus, there exists $x'\in [\frac{1}{2\pi (n+1)} , \frac{1}{2\pi n}]$ such that $f(x')=f(x)$ and by 1. we get
\begin{align*}| f(x)- f(y) |=| f(x')- f(y) | &\le c_3 \sqrt{|x'-y|} \\
&\le c_3 \sqrt{|x-y|}
\end{align*}
The exponent $1/2$ is sharp and I guess the best constant is $\sqrt{2}$.

xsin(1/x) Holder on [0,1]


Monotonic Transformation and same preferences?

Question: Charles' utility function is U(x;y)=xy. Anne's utility function is U(x;y)=1000xy. Diana's utility function is -xy. Elizabeth's utility function is U(x; y)=-1/(xy+1).Fergie' s utility function is xy-10000. Margaret's utility function is x/y. Philip's utility function is x(y + 1). (the goods x and y are two very expensive goods. We leave you to speculate about what they are.) Which of these persons have the same preferences as Charles?
I tried this question and found that the MUx/MUy is the same for Charles,Anne, Diana,Elizabeth, Fergies and Margaret.Yet the answer says only Anne,Fergie and Elizabeth have same preferences.
I don't understand how. Also,how can we show that which, of the functions are MONOTONIC TRANFORMATIONS of Charles.
I am sooooo confused :(
What is the meaning of Same Preferences? (concave, convex etc)
Answer: You are only checking whether the utility functions generate the same indifference curves. This is necessary, but not sufficient: you should also check whether preferences are increasing or decreasing in $x$ and in $y$.
For Charles, Anne, Fergie and Elizabeth, utility increases in the northwest direction (increasing in $x$ and in $y$). For Diana, utility increases in the southeast direction (decreasing in $x$ and in $y$). For Margaret, utility increases in the southwest direction (increasing in $x$ and decreasing in $y$).
Note: you can find a more detailed discussion on https://economics.stackexchange.com/questions/5237/indifference-curves-and-preferences


Playing classical without Left index finger for a lefty (or Right index for right handed)?

Question: After a recent accident where I had my L index amputated, I would like to start playing classical guitar again after 15 years of absence. to complete the picture, I'm right handed and trauma was on my Left hand.  I bought a Left hand acoustic a month ago and have started to relearn as a Lefty. All is going well, but now I would like to get back to classical guitar and play fingerstyle on my acoustic again as a Lefty. I am retired and have plenty of time.
I know that PIMA are the fingers used in classsical. Now my question is it feasible/worth it to try relearning without index and use pinky instead?
Thanks in advance for your opinions or experiences
Answer: I would say it certainly is. Now I haven't had any kind of hand injury, but still, after 16 years of playing, I recently started trying to incorporate the right-hand pinky into playing. And it just goes quite well.
By the way, there are even some classical guitarists who vouch hard for the right-hand pinky. I can think of Štěpán Rak, but I think that I have seen Kazuhito Yamashita using the pinky as well. And there will be more guitarists like that, I just don't happen to know about them. I guess that in flamenco guitar, there will be lot of them (because they probably didn't adopt the classical opinion of PIMA being the only "correct" fingers).
So: is it feasible? Yes, certainly, and it could be even recommended that people with healthy hands use the pinky as well. (I still didn't manage to get a good output with it if I try to use it in block chords, but I tried tremolo with 4 fingers and that went very well.) And I would say that with some practice, you can get just as good as anybody using PIMA. The only disadvantage will be that you won't be able to use all five fingers, which makes the right hand even more powerful, but not by much, I would say.
By the way, if you're re-learning from scratch, you will possibly have much easier time than me. I've been playing 16 years without the pinky, so it's not that easy to get into it.
Comment: @Michel: that's rough. However it is possible (but I'm **not** a doctor or anything like that!) that if you start practicing, the recovery will actually speed up or maybe you will attain even better portion of recovery (just because you demand more from the finger). BTW, Django Reinhardt had only three fingers on each hand, I believe, and it didn't stop him from being one of the greatest jazz guitarists ever. He is maybe an overused answer to the question "can I play with injured hands", but still it's very inspirational.
Comment: Thanks. Very encouraging. Actually the picture is more complex. I had my middle finger completely amputated as well and reimplanted. Recovery is going great with a very high percentage of sensory recovery after 10 months. Range of motion is also coming pretty good, but still a bit of stiffness with middle finger. I will get down to it  soon and let you know of outcome.