Linux Python # selenium - JS object - return dom element - utag as a whole object // get utag.db_log

Question: Why does selenium return utag["data"] works but utag fails?
How to return/retrieve/export the whole utag object (via selenium in python)?

typeof(dataLayer)
"object"
typeof(utag)
"object"
typeof(utag.db_log)
"object"

// on page https://tealium.com/

var testFunc = function(){
    return dataLayer;
};
testFunc ()
// works

var testFunc = function(){
    return utag.data;
};
testFunc ()
// works

var testFunc = function(){
    return utag;
};
testFunc ()
// works

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://tealium.com")

#jsObj = '''utag_err'''            # fails
#jsObj = '''console.log( utag )''' # fails
jsObj = '''utag.data'''            # works
jsObj = '''utag["data"]'''         # works
#jsObj = '''utag'''                # fails

searchTxt= f'''return {jsObj}'''
driver.execute_script(  searchTxt )

Answer: Utag contains circular structures. They are not always supported in other languages' structures and certainly not supported in JSON.
There are ways to stringify a circular object. See this post: How can I print a circular structure in a JSON-like format?
But I would just rebuild the object from scratch. You're unlikely to need 90% of utag object in Selenium anyway. Just have one function in code that builds a global utag object for you in Selenium and when you need more, you can just add fields in there. You can also add some simple processing in there too, so it would act as a utag wrapper for you.


What is the average distance run by a professional footballer?

Question: I'm interested to know the average distance a professional footballer covers in a Premier League game.
Answer: This will change dramatically based on the tactic employed by the manager, and the position a player plays in but typically midfielders run the most and cover about 10-11 km over 90 mins. Beyond 11 km is not unheard of but is considered to be a "hard-worker", especially 12+ km. Those players would typically be central midfielders with defensive focus, alternatively defensive midfielders.
References:

an article from Daily Mail, not a comprehensive list but representative nevertheless
Here's a scholarly article on performance stats, mostly based on La Liga and Champions League.


Criar usuário com acesso somente às views do Banco de Dados em MySQL

Question: Como criar um usuário que visualize somente as views do meu banco de dados em MySQL?
Estou usando as seguintes configurações:

Ubuntu Server 14.04.5 LTS
  MySQL: 5.5.55
  Apache: 2.4.7
  phpMyAdmin: 4.0.10
Comment: Relacionada: [Como fazer um usuário no SQL Server 2008 visualizar apenas uma VIEW?](https://pt.stackoverflow.com/questions/215562/como-fazer-um-usu%C3%A1rio-no-sql-server-2008-visualizar-apenas-uma-view)
Answer: Olá,
Acredito que se você utilizar a seguinte estrutura, você concederá as permissões apenas a view desejada
GRANT priv [(colunas)] [, priv [(colunas)]] ...
ON {*.* | db.* | db.sua_view}
TO usuario [IDENTIFIED BY 'senha']
[, usuario [IDENTIFIED BY 'senha']] ...
[WITH [GRANT OPTION |

Dê uma conferida neste link: Gerenciamento de Usuários e Controle de Acessos do MySQL
Comment: Por nada ;). Por favor marque esta como a resposta correta.
Comment: Marcus, valeu!!!
Deu certinho!
Comment: Como marcar essa resposta como correta? Não vejo opção.
Comment: Tem um botão em formato de visto (" V ") abaixo das setas de positivar e negativar


After the migration from Asp net core 2.2 to 3.0,I am seeing a 404 Not found

Question: In my web api solution, after the migration from Asp net core 2.2 to 3.0, I have changed the code in my startup as below:
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    return app.UseEndpoints(routes =>
    {
        routes.MapControllerRoute("test", "storage/I{controller}/{action}", null, null);
    });
}

When I hit my endpoints via the tests, I am seeing a 404 Not found.
Answer: Depends on how you define your end points, you may need to add routes.MapControllers();
app.UseRouting();
return app.UseEndpoints(routes =>
{
    routes.MapControllerRoute("test", "storage/I{controller}/{action}", null, null);
    routes.MapControllers();
});

Comment: Adding routes.MapControllers did not work for me. Can you elaborate a little more about what you meany by depends on the endpoints?
Comment: I meant if you have [Route("api-path")] or [HttpPost("action-name")] inside the controller, you have to add routes.MapControllers(); line
Comment: Maybe also take a look on this: https://aregcode.com/blog/2019/dotnetcore-understanding-aspnet-endpoint-routing/
Answer: if you used identity so, you need to add like below in ConfigureServices:
services.AddControllersWithViews();

and also you must add like below to Configure instead of what you used:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

Answer: Go to solution to open Folder in File Explorer select path and set Cmd and enter
write in cmd
dotnet ef migrations add init_db
dotnet ef database update
it will work


Stored Procedure - Error #1064

Question: Getting error during Creating Stored Procedure for Callable Statement:
I know some thing very simple going wrong, but i'm just unable to figure out!
My QUERY:
USE demo;
1. CREATE PROCEDURE
2.  INSERT_emp_data (IN ID INT, IN NAME VARCHAR(2), IN AGE INT, IN IMAGE BLOB)
3. BEGIN
4.  INSERT INTO emp_data VALUES(ID, NAME, AGE, IMAGE);
5. END;
/

SQL query:
CREATE PROCEDURE
    INSERT_emp_data (IN ID INT, IN NAME VARCHAR(2), IN AGE INT, IN IMAGE BLOB)
BEGIN
    INSERT INTO emp_data VALUES(ID, NAME, AGE, IMAGE);
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4

Appreciate your help!
Thank for your time!
Answer: When you write a stored procedure in MySQL, you should use the DELIMITER statement.  In addition, you should name your columns so they do not conflict with column names.  And, when using INSERT always list the columns name.  So:
DELIMITER $$
CREATE PROCEDURE INSERT_emp_data (
    IN IN_ID INT,
    IN IN_NAME VARCHAR(2),
    IN IN_AGE INT,
    IN IN_IMAGE BLOB
)
BEGIN
    INSERT INTO emp_data(id, name, age, image)
        VALUES(IN_ID, IN_NAME, IN_AGE, IN_IMAGE);
END;
$$
DELIMITER ;

Comment: Thank You, very much!, I will remember this always from and now, though it was my first time for creating procedure!, Appreciate your help!

Stored Procedure - Error #1064


How to reset a remote GitHub branch via GitHub API or Octokit?

Question: I am having a specific situation, when I need to programmatically hard-reset a GitHub branch (basically, delete all commits in the branch). I can only use Octokit, or GitHub API, not git cli. But I can't see corresponding endpoints in API or methods in Octokit to reset remote branches. Is it even possible?
Thanks.
Comment: I have no idea whether there are any such APIs, but the Git-protocol-level equivalent of `git reset` is `git push`. That may require a forced push (or force-with-lease) in some cases, and that may require permissions on GitHub; the permission rules are entirely up to GitHub.
Comment: @torek there is really nothing to "push". I am writing an API client, which has no storage, therefore there is no cloned repository, and not even git cli installed.
Comment: Doesn't matter whether there are commits to send or not: the push protocol operation consists of the usual negotiation, followed by sending any objects if needed (in this case no objects are needed), followed by a request: *set this reference name  to hash ID *. That request *is* a `git reset`.
Comment: Note that it is literally impossible to delete *all* commits in any branch, because any branch name is simply a ref-name of the form `refs/head/` that contains the hash ID of some valid, existing commit. The commits that are *in* or *on* that branch are that specific commit, plus all reachable previous commits. Usually, when someone says "remove all the commits" they mean "remove some of the commits, namely those that are *only* reachable from this name". GitHub won't actually *remove* the commits, as they never delete any commit: all are always available by hash ID.
Answer: No, not possible from github rest api.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Programa para ler 4 valores e mostrar na ordem crescente

Question: Comecei a pouco a prender sobre programação, eu meu professor passou a seguinte questão para ser feita com estruturas de seleção If Else em Java:
Construa um programa para ler quatro valores e os mostrar em ordem crescente.
Fiz então o seguinte programa:
package javaapplication2;
import java.util.Scanner;
public class JavaApplication2 {

    public static void main(String[] args) {
        Scanner teclado=new Scanner(System.in);
        long a,b,c,d;

        System.out.println("Digite um número inteiro:");
        a=teclado.nextLong();
        System.out.println("Digite mais um número inteiro:");
        b=teclado.nextLong();
        System.out.println("Digite outro número inteiro:");
        c=teclado.nextLong();
        System.out.println("Digite o ultimo número inteiro:");
        d=teclado.nextLong();

        if((a<b)&&(b<c)&&(c<d)){
          System.out.println("Os números digitados na ordem crescente são: "+a+b+c+d);
        }else{
            System.out.print("");
        }
        if ((a<b)&&(b<d)&&(d<c)){
          System.out.println("Os números digitados na ordem crescente são: "+a+b+d+c);
        }else{
            System.out.print("");
        }
        if ((a<c)&&(c<b)&&(b<d)){
          System.out.println("Os números digitados na ordem crescente são: "+a+c+b+d);
        }else{
            System.out.print("");
        }
        if ((a<c)&&(c<d)&&(d<b)){
          System.out.println("Os números digitados na ordem crescente são: "+a+c+d+b);
        }else{
            System.out.print("");
        }
        if ((a<d)&&(d<b)&&(b<c)){
          System.out.println("Os números digitados na ordem crescente são: "+a+d+b+c);
        }else{
            System.out.print("");
        }
        if ((a<d)&&(d<c)&&(c<b)){
          System.out.println("Os números digitados na ordem crescente são: "+a+d+c+b);
        }else{
            System.out.print("");
        }
        if((b<a)&&(a<c)&&(c<d)){
          System.out.println("Os números digitados na ordem crescente são: "+b+a+c+d);
        }else{
            System.out.print("");
        }
        if ((b<a)&&(a<d)&&(d<c)){
          System.out.println("Os números digitados na ordem crescente são: "+b+a+d+c);
        }else{
            System.out.print("");
        }
        if ((b<c)&&(c<a)&&(a<=d)){
          System.out.println("Os números digitados na ordem crescente são: "+b+c+a+d);
        }else{
            System.out.print("");
        }
        if ((b<c)&&(c<d)&&(d<a)){
          System.out.println("Os números digitados na ordem crescente são: "+b+c+d+a);
        }else{
            System.out.print("");
        }
        if ((b<d)&&(d<a)&&(a<c)){
          System.out.println("Os números digitados na ordem crescente são: "+b+d+a+c);
        }else{
            System.out.print("");
        }
        if ((b<d)&&(d<c)&&(c<a)){
          System.out.println("Os números digitados na ordem crescente são: "+b+d+c+a);
        }else{
            System.out.print("");
        }

Mas quando chega nesta parte:
if ((b<c)&&(c<d)&&(d<a)){
          System.out.println("Os números digitados na ordem crescente são: "+b+c+d+a);
        }else{
            System.out.print("");

Ele para de funcionar, não imprimi mais ("Os números digitados na ordem crescente são: "+b+c+d+)a minha dúvida é se realmente é posso usar só If Else para está questão?
Comment: Você só imprime em 12 dos 24 casos possíveis.
Answer: E não acredito que usando apenas if else seja a melhor forma para ordenar números. Isso porque a combinação de verificações para atender todas as situações em que um conjunto de números podem ser dispostos cresce exponencialmente a quantidade de números a serem ordenados.
Para saber a quantidade de verificações que devem ser feitas é só calcular o fatorial da quantidade de números a serem ordenados.
No seu caso são 4 números que significam que serão necessárias 4! combinação de ifs o seja você terá que fazer 24 comparações if para cobrir todas as possibilidades em que seus quatro números podem estar dispostos.
Caso se em seu exercício fossem solicitados 5 números você teria que fazer 120 comparações. Para 6 números seriam precisos 720 comparações.

Para resolver o seu problema, e evitar a explosão combinatória, eu usei um algorítimo de ordenação. O nome dele é bubble sort e é um algoritmo de ordenação dos mais simples. A ideia é percorrer o vector diversas vezes, e a cada passagem fazer flutuar para o topo o maior elemento da sequência.
O algorítimo do bubble sort é esse aqui:
faça
    declare :trocado falso
    para cada elemento no vetor até o penúltimo faça
      se os elementos não estão na ordem certa
         trocar elementos de lugar
         atribua verdadeiro para :trocado
      fim se
    fim para
fim faça se :trocado for falso

Se quiser mais informações sobre o bubble sort tem na Wikpedia: https://pt.wikipedia.org/wiki/Bubble_sort
Se quiser ver como as pessoas usam o bubble sort de uma pesquisada aqui na página: https://pt.stackoverflow.com/search?q=bubble+sort
Solução
Troquei as variáveis a,b,c  e d por um vetor long[] valor, de quatro posições , pois será mais fácil de trabalhar com o bubble sort.
Implementei o bubble sort em linha, direto, no seu código. Está contido no laço do while.
Também importei java.util.Arrays; Somente para facilitar a impressão do vetor valor no final do código.
import java.util.Scanner;
import java.util.Arrays; // Para imprimir os valores no final

public class JavaApplication2 {

    public static void main(String[] args) {
        Scanner teclado=new Scanner(System.in);

        // Troquei as variáveis a,b,c,d por um vetor, pois será mais fácil de trabalhar com o bubble sort

        long[] valor= new long[4];

        System.out.println("Digite um número inteiro:");
        valor[0]=teclado.nextLong();
        System.out.println("Digite mais um número inteiro:");
        valor[1]=teclado.nextLong();
        System.out.println("Digite outro número inteiro:");
        valor[2]=teclado.nextLong();
        System.out.println("Digite o ultimo número inteiro:");
        valor[3]=teclado.nextLong();

        teclado.close(); // Libera recursos de System.in

        boolean flag; // Flag será usada para indicar se foi feita uma troca

        do {
            // A cada iteração é marcado como se não houvesse ainda troca
            flag = false;

            // Percorre por todos os elementos menos o ultimo,
            //pois serão comparados o elemento com seu seguinte
            for(int i=0; i < valor.length - 1; i++) {

              // verifica se os elementos estão na ordem certa
              if (valor[i] > valor[i + 1]) {

                  // Se não estiverem ordenados os troca de lugar
                  long aux = valor[i]; // Variável para auxiliar para troca dos valores
                  valor[i] = valor[i + 1];
                  valor[i + 1] = aux;

                  flag = true;// Indica que hove uma troca
              }
            }
        } while (flag); // Se hove uma troca o algorítimo continua.

        System.out.println("Os números digitados na ordem crescente são: " + Arrays.toString(valor));

    }
}

Answer: Espero que ajude você... Fiz de forma rápida em PHP. Não foi muito testado
$a = 4;
$b = 2;
$c = 8;
$d = 6;

$primeiro = $a;
$segundo = 0;
$terceiro = 0;
$quarto = 0;

// verificando primeiro numero
if ($b < $primeiro) {
    $primeiro = $b;
}elseif($c < $primeiro) {
    $primeiro = $c;
}elseif ($d < $primeiro) {
    $primeiro = $d;
}

// verificando segundo numero
if($a > $primeiro) {
    $segundo = $a;
} else {
    $segundo = $b;
    if($c < $segundo) {
        $segundo = $c;
    }elseif ($d < $segundo) {
        $segundo = $d;
    }
}

// verificando terceiro numero
if($a > $segundo) {
    $terceiro = $a;
} else {
    if($b > $segundo) {
        $terceiro = $b;
    } else {
        $terceiro = $c;
        if($d < $terceiro) {
            $terceiro = $d;
        }
    }
}

// verificando quarto numero
if($a > $terceiro) {
    $quarto = $a;
} else {
    if($b > $terceiro) {
        $quarto = $b;
    } else {
        if($c > $terceiro) {
            $quarto = $c;
        } else {
            $quarto = $d;
        }
    }
}

echo $primeiro .' - '. $segundo .' - '. $terceiro .' - '. $quarto;

Comment: A pergunta é sobre **Java**.
Comment: Está na pergunta: "... **comecei a pouco a prender sobre programação**, eu meu professor passou a seguinte questão para ser feita com estruturas de seleção If Else **em Java**..." . Leia [Como escrever uma boa resposta](https://pt.stackoverflow.com/help/how-to-answer), qualquer dúvida faça o nosso [Tour]
Comment: para quem sabe realmente programar a linguagem é irrelevante ... assim como fiz em PHP poderia ter executado em qualquer outra linguagem.


Does using the extension method ToList() waste resources?

Question: I have a question about LINQ, IEnumerable<>, and List<>.
When I have a List<T> and want to filter or search it, I use LINQ like this:
var psec = from p in MyListOfSomeObjects
           where ((p.Tipo == tipo) || (p.Tipo == null))
           select p;

But in one particular case, I need an actual List<T>, instead of an IEnumerable<T> as returned by the LINQ query.
I could use psec.ToList<T>() to get my List<T>, but my question is:
Does the method ToList<T>() waste time or computer resources? Does it do some iteration or loop across the IEnumerable<T> to build a List<T>?
Answer:
Do the method Tolist<>() waste time or computer resources?

It depends.  If you need a list, then it's likely not a waste.  It does use time and resources to build the list.

Do it some iteration or loop across the IEnumerable psec to build a List<> ?

Yes.  It iterates through the enumerable and builds the list from the items within it.
In general, if your goal is just to enumerate through the results (ie: use in a foreach loop), there's no need to convert to a List<T> via ToList(), and doing so is just wasteful.
Comment: If you use it as a single LINQ statement, do you know if the ToList is optmized to any degree?
Comment: @James No - it doesn't matter whether it's done in one "statement" or not.  The compiler treats it the same way, and it's just a method call.  `ToList()` just (effectively) returns `new List(sourceEnumerable)`
Comment: @James its really exactly the same as if you do: `List newList = new List(psec);`


How to create multi sites

Question: I have just started to learn Drupal. So, I apologize to ask such a silly question here.
I wanted to create multi sites in Drupal. I have unlimited access to create Subdomains, Parked Domains, Addon Domains, Email Accounts and All SQl Databases with my hosting provider.
I wanted to create total 4 websites.

One that I have already created just to play and learn drupal with just Basic Structure and layout.

Rest of the three websites should have same layout and theme but different layout and theme then what I have already created called Basic Structure.
So, theses three purposes should have Same Theme and Same layout with Different Databses with Same User Names and Password.

One for Development purposes,
One for Staging purpose and
One for Clients Editing purpose (where client can play with our mock-up website for their content editing purpose).

I have read lots of reviews and steps to create multi sites in Drupal. Everyone explained it nicely in different ways. And I tried all the different ways to make it work. So, by trying and doing all those, I have messed up everything.
So, now I wanted to create again from beginning.
Can anyone help me with that? Can any one provide steps to how to create multi site in Drupal? I am just beginner for Drupal. So, can anyone please explain the steps in detail?
Also, What is the best practice to create multi sites? With Parked Domain or with Sub Domain?
Thanks for your help!
Answer: If the only purpose is to have a a dev/test/live environment, you should just go with a service like Pantheon which provides all of those for you with an ease of maintenance.
If you want to host it yourself, here's the gist of what you do...

Make sure you only have one Drupal root. Can't stress this enough. If possible, also be on version control (git) as this will help immensely.
Create 4 separate MySQL databases. Would go with a naming convention of like CODE_dev, CODE_test, etc.
Inside of your sites directory, create 4 directories, each with their own settings.php and files directory. You can name them whatever, just keep it consistent for ease of use. ie, dev.example, test.example, etc. Add their database credentials to their settings file.
In your sites directory, you will create a file called sites.php. In there, you will assign a directory name to a URL. So if you used dev.example as the name of your development site directory, and your subdirectory URL looks like dev.example.com, the format will look like this:
$sites['dev.example.com'] = 'dev.example';
Do that for each directory/site.
In your registrar for your DNS settings, point all of the subdirectories to the same IP or path as the top level domain (example.com), which should be the Drupal root directory. From there, Drupal will take care of the rest.

I think that's it, but anyone feel free to correct me. As far as the themes go, put it in sites/all/themes so all sites will have access to them. If you want a site to only have access to a specific theme/module, put it in THAT site folder.
For example: sites/dev.example/themes/THEMENAME
Comment: Thank you so much KyleTaylored for all step by step information.
I have followed all your steps. But, I don't understand last step no. 5. So, can you please elaborate step-5 more? I am going to set up this for the first time. So, I don't know how to set DNS. I tried though but I guess I did it wrong way so it gives me "This webpage is not available".
Thank you so much for all this help.
Comment: I probably should have asked what your hosting is like, because really you could do this through cPanel if you have it available. Basically you just want all of the subdomains to point to the root directory where Drupal is installed. Make sense? Confirm that the top level domain is working first.
Comment: THANKS for your prompt response and your help.
Yes, I have access in cPanel. But, in cPanel where should I set up all this?
There are Simple DNS Zone Editor, Advanced DNS Zone Editor, SubDomains, Parked Domains, Redirects options. And I have unlimited access to create anything.
But, I don't know where, what and how should I set?
Do I need to create Subdomain? Or do I need to go to Simple DNS Zone Editor? Or anything else?
I tried to play with Simple DNS Zone Editor and subdomain but it gives me Internal Server Error.
Comment: I would reset your DNS settings to default, and then you can create subdomains that point to the root folder.

How to create multi sites


Why one code (matmul) is faster than the other (Python)

Question: The problem deals with basic matrix operation. In the following code, c1 essentially equals c2. However, the first way of computing is much faster than the second one. In fact, at first I thought the first way needs to allocate a b matrix that is twice larger than the a matrix, hence may be slower. It turns out to be the opposite. Why?
import time
import numpy as np
a = np.random.rand(20000,100)+np.random.rand(20000,100)*1j

tic = time.time()
b = np.vstack((a.real,a.imag))
c1 = b.T @ b
t1 = time.time()-tic

tic = time.time()
c2 = a.real.T @ firstname.lastname@example.com
t2 = time.time()-tic

print('t1=%f. t2=%f.'%(t1,t2))

An example result is
t1=0.037965. t2=4.375873.

Comment: I replaced the numpy.matmul @ sign with numpy.dot and had significant speed improvements.
Comment: @SohrabT I tried it and, yes, np.dot is faster indeed. It confuses me because the document [link] (https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) says when the inputs are 2d arrays, the use of '@' is prefered.
Answer: a.real and a.imag are in place accesses while np.vstack creates a new copy. The way @ operator (matmul()) deals with a.real and a.imag takes longer time. To make it faster, you can create a copy of each and then pass it to @ or use np.dot(a.real.T, a.real) and np.dot(a.imag.T, a.imag) (I am not sure of each implementation in BLAS).
For large matrices, the first method in the following code should still be slightly faster:
a = np.random.rand(20000,100)+np.random.rand(20000,100)*1j

tic = time.time()
b = np.vstack((a.real,a.imag))
c1 = b.T @ b
t1 = time.time()-tic

tic = time.time()
b = a.real.copy()
c = a.imag.copy()
c2 = b.T @ b + c.T @ c
t2 = time.time()-tic

print('t1=%f. t2=%f.'%(t1,t2))

Output:
t1=0.031620. t2=0.021769.

EDIT: Dive deeper:
Let's take a quick look at various memory layouts:
a = np.random.rand(20000,100)+np.random.rand(20000,100)*1j
print('a.flags\n', a.flags)
print('a.real flags\n', a.real.flags)

a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
...
a.real flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False

So a is C_CONTIGUOUS and a.real is not. I am not sure how @ implements the calculations, but my guess is it is different with cache tricks and strides and unrolled loops. I will leave that to experts to explain. Now, array.copy() by default is C_CONTIGUOUS (BE CAREFUL: np.copy() is not C_CONTIGUOUS by default.) and that is why the second approach above is as fast as first one (where b is also C_CONTIGUOUS).
@George C: I think the first one is slightly faster because np.vstack creates a new C_CONTIGUOUS object that can leverage cache tricks in one place, while in the second approach the output of a.real.T @ a.real and email@example.com are at different locations of memory and require extra effort to calculate. Here is a link to more explanation.
Disclaimer: Any expert that knows the details of NumPy implementation are welcome to edit this post.
Comment: Good observation.  `a.real` is not `C contiguous`, and `matmul` appears to choose a much slower evaluation method. (maybe not even using the fast BLAS library).  `np.dot` does not have this problem.  Your use of `copy` restores the contiguity, and the fast method.  I wonder if there's a bug issue about this.
Comment: If I use `b = a.view(float)[:, ::2]` I get the same times as `b = a.real`.  It's not the access time itself that's the problem, but the decision within `matmul` to use an alternative evaluation method.
Comment: It is correct that accessing `real` and `imag` parts are not what takes longer time. It is that you pass them to `@` vs. passing a `.copy()`. I am guessing the way `@` accesses arrays would be different (and that is what I meant by accessing). If you run the same code without `.copy()` it takes longer time. I will try to edit the writing. Thank you.
Comment: @hpauljI have tried several different cases. Suppose x and y are two complex square matrices of the same size. Then, in the following multiplications:
x@y, x.T@y, firstname.lastname@example.com, x.real@y, firstname.lastname@example.com, firstname.lastname@example.com, firstname.lastname@example.com, only the last one, i.e., firstname.lastname@example.com, that the '@' operator will take a much longer time than np.dot. Since matrix transpose also makes the array non C-contiguous, I am supposing '@' has something wrong when both sides have .real or .imag.
Comment: @Ehsan Can you explain what makes you believe that the first method in your code should still be slightly faster? Thanks.
Comment: @GeorgeC Please checkout my edit on the post. Let me know if it answers your question. Thank you.
Comment: @Ehsan I now understand why you think the first implementation will be somehow faster. Thanks. But for the results of raveling, I am not sure if the comparison is fair, because the new c2 is a scalar, while in my original problem the output should be a matrix.


How to set up a Drupal 7 forum

Question: I have installed the core Forum module in Drupal 7.  When I go to:
<code>http://www.mysite.com/?q=forum
</code>
The forum list is displayed, however the links that allow me to post are not being displayed.
I'm surprised that I haven't been able to find a tutorial on the net on how to set up a Drupal 7 forum.
What am I doing wrong?
Answer: Your theme is probably not presenting the new action links in D7. In a default install of D7 and forum (using Bartik theme) I can see them. See http://definitivedrupal.org/suggestions/action-links for an explanation.
Comment: You're probably right. But I took the forums.tpl.php template from the Forum module directory and I have not modified it.  How do I make Drupal display the $action_links?
Comment: i personally use the omaga tools module http://drupal.org/project/omega_tools which expses these elements as block, so I can easily place them where i need. (you can also use http://drupal.org/project/blockify to get the blocks)

How to set up a Drupal 7 forum


Create sub-components in angular?

Question: I would like to know what are the possibilities to create little components in angular, which can be shown up when the data will be parsed. Let's say that we have a file (for example in json):
[{
  "name":"John",
  "surname:"Doe",
  "references":[{
     "surname": "One"},{
     "surname": "Two"}]
}]

So, I would like to create a component which targets the "surname" node, despite its depth into the tree.
Can you suggest a way to implement it? Thanks in advance!
Comment: Could you be more specific on the purpose of this component? Should it display every surname inside the given Array or else? Also, you should show what you tried already to implement this component.
Comment: Thanks Federico,
What I am trying to achieve is to create -let's say- a `surname` component, that should target the relevant json node, despite of the depth.
So let's say that inside the `app-component` the `surname-component` should display that node with the same template.
Tell me please if it isn't too clear.
Comment: So if you have a JSON with 3 surnames (wherever they are and doesn't matter how deep they are), you should display 3 surname components, right?
Comment: Or is just one surname components which get as Input the whole JSON and search for the surnames inside it?
Comment: Wow this is a wonderful question.
For now I would like to solve it as in the first way you described (3 surnames wherever they are), but I admit that also the second could be a very interesting way.
Thanks a lot for your efforts, could you please elaborate how to get these 3 surname components?
Comment: The solution I found is more complex, but I think it's also more useful, if you wish to reuse this logic.
Answer: To solve this problem I created a component which works with any key you need (not only surname).
key.component.ts
import {
  Component,
  ContentChild,
  Input,
  OnChanges,
  TemplateRef
} from "@angular/core";

@Component({
  selector: "key-component",
  templateUrl: "./key.component.html"
})
export class KeyComponent implements OnChanges {
  @Input() json: Object;
  @Input() key: string;
  @ContentChild(TemplateRef)
  template: TemplateRef<any>;
  items: Array<any>;

  ngOnChanges() {
    // If the key or the JSON change, revaluate items
    if (this.key && this.json)
      this.items = this.getElementsWithSelectedKey(
        this.objectDeepKeys(this.json)
      );
  }

  // Get all the values that has the key given by Input
  getElementsWithSelectedKey(keys: Array<String>) {
    return keys
      .filter((x: String) => x.endsWith(`.${this.key}`) || x === this.key)
      .map(x => {
        let currValue = this.json;
        for (let str of x.split(".")) {
          currValue = currValue[str];
        }
        return currValue;
      });
  }

  // Finds all the keys for every sub-objects in depth
  objectDeepKeys(obj: Object) {
    return Object.keys(obj)
      .filter(key => obj[key] instanceof Object)
      .map(key => this.objectDeepKeys(obj[key]).map(k => `${key}.${k}`))
      .reduce((x, y) => x.concat(y), Object.keys(obj));
  }
}

key.component.html
<ng-container *ngTemplateOutlet="template; context: { $implicit: items }"></ng-container>

This component gets a json to check (in your case the whole array) and a key to seek (in your case "surname").
It checks for each key inside the json and save into the property items an array with all the values it has found, with the given key.
Now you just have to choose your template (you have to write an ng-template between the key.component's tags) and get the context (let-items creates a variable items with the elements from the property items into key.component) to change your view as you wish.
Example:
app.component.html
<key-component [json]="myJSON" key="surname">
    <ng-template let-items>
        <surname-component *ngFor="let item of items" [surname]="item">
        </surname-component>
    </ng-template>
</key-component>

You can see the whole code with a couple of JSON to test on this Stackblitz
Comment: Wow, thank you so much! I will study it. Thanks a lot, it is very useful.
Comment: Dear Federico, thank you so much for your efforts: this code is very useful to me.
Just to ask if I am understanding it correctly: it displays the -let's say- surname key and extract them.
Maybe I wasn't clear enough, while I was searching for a way to create a schema which automatically calls the surname component when the json is parsed. So for example, it will attach a name component on name node, a surname on surname, and so on, without doing it programmatically.
If it is not clear tell me please, and thanks a lot!
Comment: Ok now I understand, this is a more complex problem to solve, cause you need to create components dynamically. In my solution, as you can see, I solve the problem "If there is a property named as key create a precise set of elements that you find inside the ng-template". This kind of problem is "easy" cause you know before running you're code what components you're going to use (in this case just surname). To solve your problem, you don't know how many and what kind of components you need cause that depends on your JSON. In these situations the component factory comes in handy.
Comment: https://angular.io/guide/dynamic-component-loader check this link. Anyway I'll try to show you an example on Stackblitz in the next few days.
Comment: Grazie, Federico. thank you so much. I definitely will study it a lot because it's far more difficult than I expected :)
Thank you for having addressed me in the right direction !
Answer: I don't know what do you mean by ' little components in angular' but if you want to map responses from json file you can use class:
export class People {
    name: string,
    surname: string,
    references: othersurname[]
}

export class othersurname {
    surname: string
}

Create sub-components in angular?


C# Move files from one directory to another on Azure File share

Question: I'm working on a requirement where I need to read and process CSV files on Azure File share via a C# console app. Once the file is processed, I need to move it to Archived folder, and in case of errors move it to Error folder, The fileshare structure is as below:
csvfileshare --> Name of the fileshare on Azure under the storage account. This contains the .CSV files(csvfileshare/demo.csv)
csvfileshare/Archived --> Name of dir/folder under csvfileshare where the files should be moved if successful
csvfileshare/Error --> Name of dir/folder under csvfileshare where the files should be moved if file has errors
Can you please guide me on how this can be achieved in C# console application, I've got to the point where I'm able to read the file from Azure fileshare into the console app and process them, but unable to move it to one of these directories post the processing.
Thanks!
Answer: You may have used this module already to read the file (in that case you have everything you need) but answer is using azure.storage.blob.fileshare package. If you use Visual Studio, go to manage NuGet packages and search for Azure storage.
Following Microsoft Document describes the process to manipulate Azure storage files using the module pretty well.
https://learn.microsoft.com/en-us/azure/storage/files/storage-dotnet-how-to-use-files?tabs=dotnet
By the way, in Azure world, downloading/processing/uploading is not a very scalable model (as the client finally becomes a bottleneck), you may want to explore the possibility of using something like Azure logic apps or function apps, especially if you want to process very large number of files.


dimension inequality for graded versus non-graded polynomial rings

Question: Let $A=k[x_1,\dots,x_n]$ be a polynomial ring over an algebraically closed field $k$. Let $I$ be an ideal of $A$ and $f$ some element of $A$. Then the Krull dimension does not necessarily satisfy the relation
\begin{align}
(*): \, \dim \frac{A}{I+(f)} \ge \dim \frac{A}{I}-1.
\end{align} As an example take $A=k[x,y,z], \, I=(xz,yz), \, f=z-1$.
In that case $\dim A/I = 2$, but $\dim A/(I+(f))=0$.
If however $I$ is a homogeneous ideal and $f$ a homogeneous element, then $(*)$ is true (i deduce this from Theorem 3 of Chapter 9 in Cox et al., Ideals, Varieties and Algorithms).
Question: How can this phenomenon be explained on an abstract level? What is it that we "gain" in terms of Krull dimension by viewing $A$ as a graded ring with its homogeneous ideals that we don't have if we view $A$ as a non-graded ring with arbitrary ideals? Alternatively, why does the graded ring $A$ behave more "smoothly" in terms of dimension than the non-graded $A$? Is it because with the grading $A$ becomes a $^*$local ring?
Comment: I get $\dim A/I = 2$ by $(x z,y z) = (x,y) (z)$.
Comment: I think you gave the best answer to your question: the property holds for local (and *local) rings, but fails for non-local rings.
Comment: @JürgenBöhm: Yes you are right, that was a typo. I fixed it, thanks.
Comment: I'm not so sure. The proof I know for local rings uses the Krull-Chevalley-Samuel theorem on dimension.
Comment: I see what you mean. The Krull-Chevalley-Samuel theorem must be what Matsumura calls "the fundamental theorem of dimension theory".
Answer: Essentially, when you consider $k[x,y,z]$ as an ungraded ring, you are viewing it as affine space $\mathbb A^3$, whereas when you view it as a graded ring, you are considering the projective space $\mathbb P^2$.  The precise reasons for this might not become clear until you study schemes, but you should be used to considering homogeneous ideals when you talk about projective space and considering general ideals when you talk about affine space.
The affine variety $V(xz,yz)$ has dimension $2$, since it is the union of a the plane $\{z=0\}$ with the line $\{x=y=0\}$.  When we intersect it with a hyperplane $V(f)$ (automatically of dimension $2$) we expect the intersection $V(I=(f))$ to have dimension at least $1$, since two varieties of dimension $2$ in $3$-dimensional space should intersect in at least a line.
What goes wrong in the affine case is that the dimension-$2$ part of $V(xy,yz)$ - i.e., $V(z)$ - is parallel to the hyperplane $V(z-1)$, so they don't meet at all!  The only point in the intersection $V(xy,yz,z-1)$ is the intersection of $V(z-1)$ with the line $V(x,y)$ at $(0,0,1)$.
Since projective space is 'the space where parallel lines meet', this phenomenon does not occur in the projective space: two varieties of codimension $d_1,d_2$ always meet in a subvariety of codimension at most $d_1+d_2$.
Comment: Your answer is nice and i am upvoting it. Indeed, Cox et al. give a similar geometric explanation. However, what i am interested in is a general algebraic argument. Why does the graded ring $A$ behave more "smoothly" in terms of dimension than the non-graded $A$?
Comment: I was just reading your algebraic argument but then you deleted it. Anyway, if you re-write it, then please also give a proof of your proposition.
Comment: I would be very interested to see a proof of your proposition, if such exists.
Comment: @Manos Hi!  I removed the algebraic argument because my proposition was false (indeed, it fails when applied to your example).  When I get some time in the next few days I'll work out what the correct statement and proof should be.
Comment: Ok, i look forward to it :)


typescript Object is possibly null when getting files from event

Question: I am trying to make a typescript + react fileinput component.
However I'm getting typescript error 'Object is possibly null'.
I have googled but couldn't find solution for this problem.
How can I fix this problem without disabling typescript null check.
I'm getting errors on e.target.files[0]!
Here is the code below
import React from 'react';

    export default function ImageUpload() {
      const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
      const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();

      const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
        setSelectedFile(e.target.files[0]!);

        const reader = new FileReader();

        reader.onloadend = () => {
          setImagePreviewUrl(reader.result);
        };

        reader.readAsDataURL(e.target.files[0]!);
      };

      const submit = () => {
        const fd = new FormData();

        fd.append('file', selectedFile);
      };

      let imagePreview = (
Please select an Image for Preview
);
      if (imagePreviewUrl) {
        imagePreview = (

            {' '}

        );
      }

      return (

          <input type="file" name="avatar" onChange={fileChangedHandler} />
          <button type="button" onClick={submit}> Upload </button>
          { imagePreview }

      );
    }

Answer: HTMLInputElement has a built-in property files that is typeof FileList | null.

files: FileList | null;

Simply secure the possibility that files is null.
if (!e.target.files) return;

At the beginning of the function.
Answer: Guys this is the proper way of handling this issue:
            e.target.files instanceof FileList
              ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'

Hope this helps. Cheers!
Answer: From the code, I suspect that e.target is nullable. You could modify e.target.files[0]! to e.target!.files[0]!, which will make error go away because you will essentially tell the Typescript compiler that "it will not be null, trust me". But instead, I would advise to handle the null case properly - check for null or undefined and do something appropriate, depending on your app logic.
Comment: Suggestion a null assertion where there is a high probability of `null` is a bad taste.
Comment: Agreed, that's what my answer is essentially saying as well.
Answer: if (!e.target.files || e.target.files.length === 0) {
      // you can display the error to the user
      console.error("Select a file");
      return;
    }

Answer: In my code it worked like this: I created a variable that received the HTML event, then created a variable that received all the event files and used the 'item' functionality at index 0, and then I was able to access the file
const handleSetFileName = (event: ChangeEvent<HTMLInputElement>) => {
  const files = event.target.files;
  setFileName(files?.item(0)?.name);
};

Comment: I get a TS error on `ChangeEvent`: `Cannot find name 'ChangeEvent'.ts(2304)
type ChangeEvent = /*unresolved*/ any`
Answer: const fileChangedHandler = (e) => {
  const sellectFile = e.target.file ? e.target.files[0] : null;

  if (selectfile) {
    setSelectedFile(selectfile);
  }
};

Comment: Add some code to explain your answer.


Why aren't the outputs of the softmax and logistic function the same in this example?

Question: I am trying to understand the equivalence between the logistic function and the softmax function, when k = 2. My understanding is that the following code should output the same values. Where is my mistake?
<code>def sigmoid(x):
    x = np.asarray(x, dtype=np.float)
    x = 1 / (1 + np.exp(-x))
    return x

def softmax(x):
    x = np.asarray(x)
    x = np.exp(x)/np.sum(np.exp(x))
    return x

x = .5
b1 = 1
b2 = -1
sigmoid(x*b1), sigmoid(x*b2), softmax([x*(b1-b2), x*(b2-b2)])
---
Output> 0.6224593312018546, 0.3775406687981454, array([0.73105858, 0.26894142])
</code>
Is it because I am assuming that the softmax optimization would find the same betas?
Comment: Also: https://stats.stackexchange.com/questions/233658/softmax-vs-sigmoid-function-in-logistic-classifier/254071#254071
Comment: I see no reason why these two functions should return the same values, because they appear to use different denominators.  Could you explain why you think they are equivalent?
Comment: @whuber The two links above show why the two are theoretically linked, and the answer below shows what is the relationship between the coefficients that I was missing.
Answer: The assumption for two class logistic regression and softmax to have the same values is the follows
beta ( logistic regression ) = -(beta1 - beta2)
Following code gives the matching numbers
<code>    def sigmoid1(x):
        x = np.asarray(x, dtype=np.float)
        x = 1 / (1 + np.exp(-x))
        return x

    def sigmoid0(x):
        x = np.asarray(x, dtype=np.float)
        x = np.exp(-x) / (1 + np.exp(-x))
        return x

    def softmax(x):
        x = np.asarray(x)
        x = np.exp(x)/np.sum(np.exp(x))
        return x

    x = .5
    b = -2
    b1 = 1
    b2 = -1
    sigmoid0(x*b), sigmoid1(x*b), softmax([x*b1, x*b2])

(0.7310585786300049, 0.2689414213699951, array([0.73105858, 0.26894142]))
</code>


I'm new to programming and I successfully installed XAMPP but when I run the Admin on MySQL, local host refuses to connect

Question: This site can't be reachedlocalhost refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
This is the message that popped up
Comment: Have you tried checking for a used proxy or whether your firewall is up as stated in the error message?
Answer: Please check the port first. Is your port is listening correctly or there may be a firewall preventing you to connect to that port.
You can use the following command to check the open ports
sudo netstat -tulpn | grep LISTEN
To check the specific port use
sudo lsof -i:22 see a specific port such as 22


Cardinality of sets of natural functions, with conditions

Question:
Convention: $0\in\mathbb{N}$. Find the cardinality of
a) $A=\{f:\mathbb{N}\to \mathbb{N}\mid \forall n, f(n)=f(n+1)+f(n+2)\}$
b) $B=\{f:\mathbb{N}\to\mathbb{N}\mid\forall n, f(n)\ge f(n+1)\}$

My attempt:
a) We have $|A|\le |\mathbb{N}^{\mathbb{N}}|=2^{\omega}$. Now, I'm looking for some set $C\subseteq A$ with $C=2^{\omega}$, but seems to be tricky.
b) Again, $|B|\le 2^{\omega}$. All constant functions are contained in $B$ as well, so $\omega\le |B|$, but this does not help. I believe $C=\{f:\mathbb{N}\to \{0,1\}\mid f(0)=1\}\subseteq B$. Again, $|C|\le 2^{\omega}$. Define $\phi: \{0,1\}^{\mathbb{N}}\to C: f\mapsto \phi(f)$, where $\phi(f)(n)=f(n)$ if $f(0)=1$ and $\phi(f)(n)=1$ otherwise. This function is not injective if the latter assignment is defined. How can I change that?
Thanks.
Comment: Yes. I will add it to the question.
Answer: It is true that $|A|\leq |\mathbb{N}^\mathbb{N}|=2^{\aleph_0}$, but it is possible to have smaller cardinality.
Notice that the condition given for a function $g$ in the set $B$ implies that the function is non-increasing. So, each of these functions is completely determined by the first value ($g(0)$) and the inputs where it changes value for something smaller (i.e., the values $n$ where $g(n)>g(n+1)$. Therefore, the functions $g$ is completely determined by a finite sequence of natural numbers, and again there are only $\aleph_0$ such sequences, thus $|B|\leq\aleph_0$. Also, the choice for $g(0)$ can be any natural number, so we have $|B|\geq \aleph_0$, and by Cantor-Bernstein, $|B|=\aleph_0$.
The set $A$ is a bit trickier. Note that the condition given for a function $f$ in the set $A$ implies that every value $f(n)$ is completely determined by $f(n-1)$ and $f(n-2)$, via the equation $$f(n+2)=f(n)-f(n+1).$$
Hence, $f$ is completely determined by the values $f(0)$ and $f(1)$, because we then have:
$$\begin{align*}f(2)&=f(0)-f(1)\\ f(3)&=f(1)-f(2)=f(1)-(f(0)-f(1)\\
&=-f(0)+2f(1)\\
f(4)&=2f(0)-3f(1)\\
f(5)&=-3f(0)+5f(1)\\
\vdots\ \  &=\vdots\ \ \end{align*}$$
Since there are at most $\aleph_0$ possible pairs of natural number that can be equal to $f(0),f(1)$, we then have $|A|\leq \aleph_0$.
There is still one more question. Notice that the equations given above may be negative depending on the choice of $f(0)$ and $f(1)$. Since a function $f\in A$ has domain $\mathbb{N}$ and codomain also $\mathbb{N}$, we have to make sure that $f(n+2)$ is always non-negative.
The value $f(n+2)$ can be calculated as:
$$f(n+2)=(-1)^{n+2}(F_n\cdot f(0)- F_{n+1}\cdot f(1))$$ where $F_n$ is the $n$-th term in the Fibonacci sequence. [It can be shown by induction, but I am not explaining this here]
So, if for any large even number $n$ we have $f(n+2),f(n+3)\geq 0$, this implies
$$\begin{align*}
f(n+2)&=F_n\cdot f(0)-F_{n+1}\cdot f(1)\geq 0\\
f(n+3)&=-F_{n+1}\cdot f(0)+F_{n+2}\cdot f(1)\geq 0\end{align*}$$
obtaining
$$\begin{align*}
F_n\cdot f(0)\geq F_{n+1}\cdot f(1)\ , & &F_{n+2}\cdot f(1)\geq F_{n+1}\cdot f(0).\end{align*}$$
Dividing respectively by $f(0)$ and $f(1)$, we obtain that for every even number $n$,
$$\begin{align*}\dfrac{F_n}{F_{n+1}}\geq \dfrac{f(1)}{f(0)}\geq  \dfrac{F_{n+1}}{F_{n+2}} & &\text{and}& &\dfrac{F_{n+2}}{F_{n+1}}\geq \dfrac{f(0)}{f(1)} \geq \dfrac{F_n}{F_{n+1}}.\end{align*}$$
This is a contradicton since both sequences $\{F_n/F_{n+1}:n\in\mathbb{N}\}$ and $\{F_{n+1}/F_{n}:n\in\mathbb{N}\}$ are monotone and non-constant.
Hence, the only possibility for the condition $f(n)=f(n+1)+f(n+2)$ to hold for every $n\in\mathbb{N}$ is to have $f(0)=f(1)=0$, and so the set $A$ consists only of one element, the constant function $f(n)=0$. Therefore, $|A|=1$.
Comment: Why does $A$ consist of constant functions? Clearly $f(n)=1$ does not satisfy the hypothesis.
Comment: @Koro My bad. I missread and taught there were two equalities!
Comment: I have edited my answer.
Answer: I think $A$ only has the zero sequence because if you write it as a recurrence relation $f(n+2)=f(n)-f(n+1)$, you can't have an infinite sequence like that without eventually going negative, and I assume $\mathbb{N}$ is only non-negative (or positive).
For $B$, Dario G's answer is right.
Comment: This question assumes $0\in\mathbb{N}$.


Can Reaper be use for beat creation like that in FL studio?

Question: I used FL studio for easy beat creation. See here:
http://www.metacafe.com/watch/1376781/fl_studio_tutorial_how_to_make_a_simple_beat_in_fl_studio/
Now i heard about Reaper which is awesome and low-cost:
http://www.reaper.fm
I downloaded test and manual but couldn't find anything to make beats as easy as on fl studio.
Isn't this featured in reaper?
which "cheap but good" software (under 100$) features the onscreen beat creation?
Thanks
Answer: I have a few options for you.
http://tutorialsforreaper.com/2010/08/03/drums-as-click-gtg-synth-drums-midi-drums-as-click-basic-beat-creation/
This is free and you can create beats to the depth of your beat knowledge with this and the built in tools that come with reaper.
Reaper is fairly robust in the midi department so you could use just about any VST/DXI instrument you wanted to play the beats from midi.
As far as software for under a 100 why not stick with what you know http://www.musiciansfriend.com/pro-audio/image-line-fl-studio-10-fruity-loops/h74334000000000.
You can record from FL studio into reaper.
http://www.ustream.tv/recorded/6891224


How to fix the error message that says "this version of Cosmos SDK is no longer supported" when running starport scaffold commands?

Question: Using starport version v0.17.1 darwin/amd64 -build date: 2021-07-27T13:10:21Z, the starport scaffold commands gives an error saying "this version of Cosmos SDK is no longer supported"
Answer: This error only occurs when you are trying to starport chain serve a chain scaffolded with SDK v0.39.x. Also check if you are using the latest go version by running go version :)


How can I tell whether it is a call to a static method or an instance method?

Question: If the below code is the only  provided information, how Can I determine whether it is a Static or an instance methods?
foo.bar(x, y, z);
Comment: Not possible ..
Comment: @Alan "Normal" is subjective. IntelliJ definitely highlights it as a problem (although, that may also be a plugin). Also, compiler warnings are shown at compile time, not any specific IDE
Comment: Even if you had `Foo foo = new Foo()`, still not possible because that would show up as a compiler warning and `static void bar()` could still be called
Comment: It does not do that on my normal system with normal Eclipse 2021-06, @OneCricketeer
Comment: The IDE chooses what level to apply to a problem that the compiler finds.  One level is "ignore".  By normal all I meant was that I had updated Eclipse and I had not applied any changes that would block reporting of such a warning if one got issued by the compiler, or any extreme changes; not many changes to preferences at all.  Yes, the compiler finds them at compile time, but the IDE might not show it.
Answer: By convention, it would be an instance call, because foo starts with a lower case letter.
But convention is broken often and so can't be depended on for certainty.  So there could be a class accessible to the code call foo instead of Foo.
So there is no definitive answer.
Comment: You can also call static methods on an instance.
Answer: The way to tell is if this is a static or instance method call is to do the following:

Find the declaration of the foo variable (or class) to determine its compile time type.
Examine that type's code to find the matching method bar methods.
Perform the method overload resolution based on the static types of the argument expressions.
Finally, check if the resolved bar method is static.

An typical IDE can do this automatically, assuming that the respective definitions are available.
A Java compiler will also do this, so you could use javap -c to examine the compiled bytecodes for the class; see @rzwitteserloot's answer.  However, you then have the problem of figuring out which INVOKE... instruction corresponds to that method call.  (And there is the binary compatibility issue that he notes.)

However, if you only have that 17 character snippet of source code, it is not possible to distinguish static and instance method calls.
We cannot be sure that foo is a variable.  (It could be the name of a class ... where the programmer has ignored Java style conventions!)
Even if we know foo is a variable, we still don't know if this is invoking an instance method, or invoking a static method via an instance reference.  The latter is allowed by the JLS1 but it is definitely bad style.

1 - For example, see JLS 22.214.171.124: "if the invocation mode is static ...".
Answer: When writing code, you know. The compiler can't compile the code without knowing this. A method is encoded in a class file as an INVOKESTATIC or INVOKEVIRTUAL bytecode instruction, and the instruction includes the so-called fully qualified binary name of the method, which includes not just bar, but also the type bar is from, its (erased) param types, as well as its return type. It's something like:
INVOKESTATIC #1, #2

where 1 2 and 3 are refs to the constant pool, which are then refs to constant strings, which contain something like:
#1: com.whatever.Foo
#2: bar(IZLjava/langString;)V

That last thing isn't gobbledygook and also isn't the result of a cat walking over a keyboard. That's bytecode-ese for void bar(int, boolean, String). (I = int, Z = boolean, V = void, L = object type).
Clearly then the compiler has no idea what strings it should put in the constant pool unless it already knows, at compile time, what bar actually is. This works out: If you don't have the type that foo belongs to on the classpath, it just doesn't compile.
Contrast to languages like python or javascript, where you can just roll your face over the keyboard pretty much and it won't fail until you get to that line. Java doesn't work that way.
So, how would you know? You'd know.
If it's just a convenience thing, well, get an IDE. They'll tell you. For example, eclipse renders static calls in italics and non-static calls without italics.
If you're worried that the method is static today but you're intrigued if it ever becomes non-static tomorrow, well, um, I guess don't worry, in the sense that if you don't recompile, the code won't work. The INVOKESTATIC is baked into that class file, if the target type does have a bar method but is updated to a newer version and there the bar method is all of a sudden no longer static, the INVOKESTATIC call will fail at runtime with an Error. In general, if you mix and match versions that aren't backwards compatible, code won't run. That's by design, pretty much.


Hershey kiss Christmas handbell commercial

Question: This is something I've wondered for a long time but could never get a straight answer... There's a famous TV commercial for Hershey Kisses where the kisses are handbells, playing we wish you a merry Christmas. You can see it here:

My question: is it consistent? As in, when a given kiss rings, does the same note sound each time? My ear isn't good enough to tell, but visually, it looks reasonable (it seems like each heard note corresponds to one shaking kiss, but I can't tell if the notes change). I've never found anybody who could answer but this seems like the place. Thanks.
Answer: Of the 10 kisses, seven of them are consistent. I've labeled these pitches below, with numbers for the non-consistent bells:

      A♭
    F   G
  C   D  E♭
B♭  8   9  10

The remaining three, however, switch pitches for various harmonic and bass support. As one example, on "Christ" of the first "Christmas," bell 8 plays an A♭. (Also note that, on the succeeding "wish," there's an A♮ that doesn't seem to be represented by any bell.) On the very last "we" of "we wish," bell 8 now suddenly plays a D, which is obviously different from its prior A♭.
Comment: I agree with the consistent vs. non-consistent bells. Toward the end, there seem to be a number of chord notes in the harmony that are not played consistently by any bell (or by any bell at all, aside from the A-natural you specifically mention). Also, I think we get an unheard ring of bell 10 (that is, the bell appears to "ring" but there's no sound corresponding to it) around the D-Bb end of the second phrase.
Comment: I agree completely. Once they begin to flesh out the harmony, it becomes more of a visual effect than one of pitch consistency.
Comment: Fast and thorough. I'm very impressed with how quickly pros can answer this (I'm a serious amateur guitarist) and also the fact that the ad agency was pretty close to consistent with this ad.


How to test difference between times series - does "time series ANOVA" exist?

Question: Description: Temperature if six objects (obj_A, obj_B,...obj_F) was measured in 1 hour intervals (1,2...10)
Objects were under the influence of two treatments (A and B). Treatment A = obj_A, obj_B, obj_C; treatment B = obj_D, obj_E, obj_F.
Problem is that measured values of each object are serially correlated, therefore I can not use classical
ANOVA. How to take into account such fact?
# example data
my.data <- data.frame(object = rep(c("obj_A","obj_B","obj_C",
                                     "obj_D","obj_E","obj_F"),
                                      each = 10),
                      time = rep(c(1:10), times = 6),
                      treatment = rep(c("A","B"), each = 30),
                      value = c(4,4,7,8,8,10,8,12,14,12,
                                8,8,12,12,10,12,10,11,12,16,
                                12,12,11,13,12,16,16,14,16,20,
                                11,20,23,27,31,29,31,32,28,30,
                                12,16,17,23,22,24,33,31,31,32,
                                14,13,19,20,24,26,24,28,25,23))

# converting values to time series object
obj_A <- ts(my.data$value[my.data$object=="obj_A"],
            start = 1, end = 10, frequency = 1)
obj_B <- ts(my.data$value[my.data$object=="obj_B"],
            start = 1, end = 10, frequency = 1)
obj_C <- ts(my.data$value[my.data$object=="obj_C"],
            start = 1, end = 10, frequency = 1)
obj_D <- ts(my.data$value[my.data$object=="obj_D"],
            start = 1, end = 10, frequency = 1)
obj_E <- ts(my.data$value[my.data$object=="obj_E"],
            start = 1, end = 10, frequency = 1)
obj_F <- ts(my.data$value[my.data$object=="obj_F"],
            start = 1, end = 10, frequency = 1)

# plot -> blue = treatment A; red = treatment B
ts.plot(obj_A, obj_B, obj_C, obj_D, obj_E, obj_F,
        col=c("deepskyblue","deepskyblue1","deepskyblue2",
              "darkred","indianred","indianred1"),
        lwd = 2.5, lty = 2, xlab = "time", ylab = "temperature")

How to rigorously test whether temperature of objects differ according to used treatment, but without ignoring serial
 correlation?
Comment: You can't do it here because there is no one clear way to define if  they "differ". Are you interested in the trajectory, or the final value after a set period of time, or something else?
Comment: In your case a t-test even on a single time-point will show significant difference between groups (for several different time points).
Comment: Hi @ssdecontrol and @amoeba! Let say that each curve is generated by some hidden process. Is it possible to test whether "red curves" are generated by different process than "blue curves"?
Answer: You notice correcly that usual ANOVA cannot handle this type of very heteroskedastic and highly dependent time point data. But also, other repeated measures or multivariate procedures would fail because you have only 6 replications but 10 time points, so called high dimensional data. In the end, it is proven that there cannot be an exact test for data like that.
However, there is a good approximative test, it's the Huynh-Feldt-procedure, see this technical report for references and for a generalization to possibly unequal covariance matrices that you may use. It is defined even for your very small data set. There are no assumptions on the variances and covariances. It is intended for normally distributed data, but I think you're fine with it.
You can test if the curves differ (set T = diag(10)) and if there is an interaction between treatment and time point (set T = diag(10) - 1/10). It's too simple for an extra R-package. Check this:
Tmat <- diag(10) # or Tmat <- diag(10)-1/10
Y1 <- t(matrix(my.data[my.data$treatment=="B","value"],10,3)) %*% Tmat
    Y2 <- t(matrix(my.data[my.data$treatment=="A","value"],10,3)) %*% Tmat

Mean1 <- apply(Y1,2,mean)
Mean2 <- apply(Y2,2,mean)
S1 <- cov(Y1)
S2 <- cov(Y2)

F <- sum((Mean1-Mean2)**2) / (sum(diag(S1/3 + S2/3))) # see eq. 3.18
trS1sq <- 3/2 * ( (sum(diag(S1)))**2 - 2/3 * sum(S1**2)) # see eq. 3.26
trS2sq <- 3/2 * ( (sum(diag(S2)))**2 - 2/3 * sum(S2**2))
trS1S1 <- 3/2 * ( sum(S1**2) - (sum(diag(S1)))**2/2)  # 3.27
trS2S2 <- 3/2 * ( sum(S2**2) - (sum(diag(S2)))**2/2)  # 3.27

f <- (trS1sq + trS2sq + 2*sum(diag(S1))*sum(diag(S2))) /
    (trS1S1+trS2S2+2*sum(S1*S2))  # see p. 16
f0 <- (trS1sq + trS2sq + 2*sum(diag(S1))*sum(diag(S2))) /
    (trS1S1/2 + trS2S2/2)

p.value <- 1-pf(F,f,f0)

Answer: I believe your problem is a textbook case of longitudinal data analysis for which there is an extensive statistical methodology developed. In particular, analysis of response profiles is an approach that I would employ in this case.
To motivate this, I will provide some background from Applied Longitudinal Analysis by G.M. Fitzmaurice:

1.2 Longitudinal and clustered data
The defining feature of longitudinal studies is that measurements of
  the same individuals are taken repeatedly through time, thereby
  allowing the direct study of change over the time. The primary goal of
  a longitudinal study is to characterize the change in response over
  the time and the factors that influence change. (...)
A distinctive feature of longitudinal data is that they are
  clustered. In longitudinal studies the clusters are composed of the repeated measurements obtained from a single individual at different
  occasions. Observations within a cluster will typically exhibit
  positive correlation, and this correlation must be accounted for in
  the analysis. Longitudinal data also have a temporal order; the first
  measurement within a cluster necessarily comes before the second
  measurement, and so on. The ordering of the repeated measures has
  important implications for analysis.

and regarding analyzing response profiles choice:

Methods for analyzing response profiles are appealing when there is a
  single categorical covariate (perhaps denoting different treatment or
  exposure groups) and when no specific a priori pattern for the
  differences in the response profiles between groups can be specified.
  When repeated measures are obtained at the same sequence of occasions,
  the data can be summarized by the estimated mean response at each
  occasion, stratified by levels of a group factor. At any given level
  of the group factor, the sequence of means over time is referred to as
  the mean response profile.

The nlme R library contains a glm function to evaluate such model, giving you a longitudinal "equivalent" of Anova:
library(nlme)

# Model assuming the same variance for each time point
gls.fit <-
  gls(value ~ factor(time) + treatment,
      data = my.data,
      corr = corSymm(form = ~ 1 | object),
      control = glsControl(tolerance = 0.01, msTol = 0.01,
                           maxIter = 1000000, msMaxIter = 1000000))
summary(gls.fit)

# Model allowing for different variance structure for each time point
gls.fit.diff.var <-
  gls(value ~ factor(time) + treatment,
      data = my.data,
      corr = corSymm(form = ~ 1 | object),
      weights = varIdent(form = ~ 1 | factor(time)),
      control = glsControl(tolerance = 0.01, msTol = 0.01,
                           maxIter = 1000000, msMaxIter = 1000000))
summary(gls.fit.diff.var)

Unfortunately, in this case model estimation does not coverage (even though I changed control parameters for more convenient). I am afraid there is just too few cases in your data set to estimate parameters.
Comment: Why didn't you try `corr = corSymm(from= ~1 | treatment)`? I assume that among the groups with the same treatment, all experimental units are identically distributed, so have the same covariance matrix. Yet it still won't converge: You have more parameters in your 10x10 covariance matrices than experimental units. But you can use `corr = corAR1(from=~1|treatment)`. Then it will converge, becaus you'll only have two parameters each. But is it reasonably? It assumes some kind of equal spacing of the time points wrt. correlation; this "ordering of the repeated measurements" from your reference.
Comment: I assume that data is correlated within each of the subjects (values for the same subject are correlated thorough time), thus I define **correlation structure** in relation to a subject (here: `object`).
Comment: "I assume that among the groups with the same treatment, all experimental units are identically distributed" <- please note we are not talking about a cross-sectional study (data observed in one particular time point); our concern here is not assuming different settling for subjects from different groups at given time point, but assuming that thorough the study tim, observations within a particular subject are correlated (and there is nothing in this point about being from different / same treatment groups).
Comment: OK, it was misleading terminology. "Group" usually means the factor the independent replications are nested within (i.e. samples). The subjects within the same sample are iid. For the `corSymm` help, a "grouping factor" is the replication itself.
Comment: Dear @MartaKaras I am very thankful for your answer, however solution given by HorstGrünbusch seem to be more suitable for my data (data provided in example are fabricated). Thank you Marta.
Comment: No problem! Good luck with your analysis! :)


Uniform continuity of $f(x) = \frac{x}{|x|+1}$

Question: $f : \mathbb{R} \rightarrow \mathbb{R} \\ f(x) = \frac{x}{|x|+1}$
Is uniform continuity?
We can not use derivative because at $x=0$ function $|x|$ is not differentiable. I attempted prove that $f$ is Lipschitz continuity but inequality is difficult.
Any hints?
Comment: Note that |f| < 1 in the uniform norm.
Comment: The function $g(x) = \sin(x^2)$ has that same property, but it's not uniformly continuous on the reals.
Answer: $$f(x)=\begin{cases}\dfrac{x}{1+x},&\text{ if }x\ge0\\\dfrac{x}{1-x},&\text{ if }x<0\end{cases}$$
So for $x>0,~f'(x)=\dfrac{1}{(1+x)^2}<1~\forall~x>0$ and for $x<0,~f'(x)=\dfrac{1}{(1-x)^2}<1~\forall~x<0.$
$f'$ also exists at $0$ since
$$Rf'(0)=\lim_{x\to0+}\dfrac{f(x)-f(0)}{x-0}=\lim_{x\to0+}\dfrac{1}{1+x}=0\\Lf'(0)=\lim_{x\to0-}\dfrac{f(x)-f(0)}{x-0}=\lim_{x\to0-}\dfrac{1}{1-x}=0$$are equal.
Consequently $f'(0)=1$ and hence $f'$ is bounded on $\mathbb R.$
Thus $f$ being a differentiable function having a bounded derivative on $\mathbb R,~f$ is uniformly continuous on $\mathbb R.$
Comment: Lovely, except that the limits are both 1 rather than 0, so $f'(0) = 1$. Everything else is spot on.
Comment: Suggestion appreciated. Thanks.
Answer: I believe that $f$ satisfies a Lipschitz condition with $M = 1$. It certainly does on the positive reals. So if I were you, I'd prove uniform continuity by picking $\delta = \epsilon$, or perhaps $\delta = \epsilon / 2$ if you want a little breathing room.
Answer: You can use derivatives, although $| x |$ is not differentiable at $0$,  $\,f (x)$ yes it is
$$\lim_{h \rightarrow 0} \dfrac{f(h)-f(0)}{h}=\lim_{h \rightarrow 0} \dfrac{1}{|h|+1}=1$$


Get all objects from severall models that share the same foreign key - Is it possible?

Question: I am facing a problem designing a database with Django framework that i can't seem to solve. Say i have the following models:
class Report(models.Models):
    equipment = models.ForeignKey(Equipament)
    category = models.ForeignKey(Category)
    date = models.DateField()
    user = models.CharField(max_length=100)

class TestA(models.Model):
    report = models.ForeignKey(Report)
    lasers = models.FloatField()
    table = models.FloatField()
    dose = models.FloatField()
    pass_fail = models.NullBooleanField()

class TestB(models.Model):
    report = models.ForeignKey(Report)
    ctdi = models.FloatField()
    pass_fail = models.NullBooleanField()

class TestC(models.Model):
    report = models.ForeignKey(Report)
    pass_fail = models.NullBooleanField()

My question is: Is it possible to get all objects from Tests B, C and D that share the same oject from Report? I do not wish to query each model (TestB, TestC or TestD) individually because in reality i have many more Test models.
Any help is much apreciated.
Comment: Are you saying you have one ModelA object, and you want to get the related ModelB, C, and Ds? This seems like it may be related to your question as well http://stackoverflow.com/a/2315053/4974980
Comment: @JensAstrup Thanks. That is exactly what i want to do. I will give it a look.
Comment: @JensAstrup Thanks for the tip. Although it was a similar problem i wasn't able to solve it. It seems that "get_all_related_objects()" method used as a solution has been deprecated. It seems like a "doable" thing. I am seeking to query a ModelA object and get all the related ones from the other models...
Comment: What do all these related models look like (in terms of fields contained). And rather than using ABC, can you post a good sample. Thanks
Comment: @e4c5 Updated my post. I am performing tests to equipment. Each test has different values to be saved so i created different models for each one of them. I though to relate all of the tests by giving them a foreign key to the same report object so i could actually present a report with all the test. Thought it would be easy but can't seem to work this out.
Answer: Why do you have three different models that are essentially the same thing? Try this:
class Report(models.Models):
    equipment = models.ForeignKey(Equipment)
    category = models.ForeignKey(Category)
    date = models.DateField()
    user = models.CharField(max_length=100)

class Result(model.Model):
    report = models.ForeignKey(Report)
    status = models.BooleanField(default=False)
    lasers = models.FloatField(blank=True, null=True)
    table = models.FloatField(blank=True, null=True)
    ctdi = models.FloatField(blank=True, null=True)
    dose = models.FloatField(blank=True, null=True)
    title = models.CharField(max_length=200)

Just give each report a title, such as 'TestA' / 'TestB' instead of creating an entirely new model.
To get all results for a report:
r = Result.objects.filter(report=Report.objects.get(pk=1))

Comment: You mean give each result a title...I didin´t do it like this because each test to be performed to equipments is different. TestA doesn't have all those fields...
Comment: That's why all those fields are optional and default to `NULL`. So you only have to enter the fields that make sense for the kind of test you are doing.
Comment: @BurhanKhalidi It does make things easier to relate. Is there a way to automatically load only some fields based on a FK choice? for example If i select category in the Report to load only some fields? Otherwise everything would be hardcoded in the html when i would render the form.
Comment: You can easily take care of this in the view.
Comment: Thank you. I will give it a try although it doesn´t seem very realistic.


How to attach custom CSS to a Views output?

Question: I created a View to list a custom entity content.
I'd like to add my custom CSS file to the generated page.
I tried to use a Text Area in the footer with <code>{{ attach_library('amap/yyy') }}</code> where amap is my custom module and yyy is my custom library.
And of course, the CSS is not loaded...
Any idea why?
Comment: Because text area IS NOT TWIG. When it's get displayed it will go through twig, but your "content" will be "escaped". You can't use twig expressions from database. (and that's where it's coming from). Always think of hooks / events first. Drupal is a heavily hook based framework.
Answer: You will need hook_views_pre_render().
And here is an example:
<code>/**
 * Implements hook_views_pre_render().
 */
function base_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'this_is_my_view_with_no_css' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'base/test';
  }
}
</code>
Comment: I have this error:`Recoverable fatal error: Argument 1 passed to amap_views_pre_render() must be an instance of ViewExecutable`
Comment: Yes. If you used a normal IDE (phpstorm, eclipse) it would already give you at least a WARNING, that it has absolutely no idea where "ViewExecutable" is coming from. (how should it now it?..).
You have to use: "use Drupal\views\ViewExecutable;" at the top of the file. (but above <?php). I suggest you to read this: http://stackoverflow.com/questions/10542012/php-namespaces-and-use
Comment: indeed, it works better that way ;-)
Comment: awesome, I removed the condition about display because I want it on all pages of my view. Works great! thanks.
Answer: Is your custom css loaded with you theme? I might be misunderstanding you question, but if you trying to apply your custom CSS to your view's result and your CSS is loaded with your theme then, in editing the view, click on the field you want to edit. Click 'Style Settings' and you'll see options for adding HTML and CSS to the field. Click 'Create a CSS class'. Enter a new CSS class name. Set the class names to those in your custom theme CSS file you want to use. Clear your cache and check the view. note: the preview will not show CSS changes.
If you are not loading your custom css with your theme, I suppose you could include it in the .info for Views. Though you would have to redo that each time views updated.
Comment: No, my custom css is not loaded with the theme.
Comment: I think you misunderstood him. He wants to attach his own Library to a View page.
Comment: Exactly! It's why I tried to add `attach_library` in a text area of the footer using twig syntax...


Get paragraph id in field template

Question: I have a paragraph template where I print a field, for instance :
{{ content.field_products }}

In this template, I can get the paragraph id with :
paragraph.id()

I need to pass this paragraph id in the field template. What is the cleaner and simple way to do this ?
I found a solution like this :
{{ content.field_products|merge({666:paragraph.id()}) }}

and then I get the value in field template like this :
{% set paragraphId = items[items|length-1].content %}

But this is dirty and generate a warning "Message d'erreurUser error: "4" is an invalid render array key in Drupal\Core\Render\Element::children() (line 99 of core/lib/Drupal/Core/Render/Element.php)." that I can understand giving that it's a dirty hack and drupal try to render my "666" array.
I'm probably gonna get the array with "666" key I added in a preprocess_field(), create a new variable for the field template et delete this diabolic hack from $variables to remove the warning due to a tentative to render this fake array, but I guess there is a better way to do ? I want simply to pass a variable from a template to its child...
thanks !
Answer: The clean solution is template preprocessing: In yourtheme.theme create something like
function yourtheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  $parentEntity = $element['#object'];
  //might be useful for if-clause: $variables['field_name'] and $variables['field_type']
  if ($parentEntity && $parentEntity->getEntityTypeId() == 'paragraph' ) {
    //whatever logic you need goes here, e.g. something like
    //$variables['attributes']['data-from-parent-paragraph'] = $parentEntity->getYourStuff();
  }
}

Comment: Yes, in preprocess this is easier to find, but once you know where to look you can do this in TWIG as well: `{{ element['#object'].id }}`

Get paragraph id in field template


Getting all the combinations of a list of lists of values (or array of arrays) [Cartesian Product]

Question: I have a list of lists of parameters and I want to combine them in all possible combinations.
I don't know before the execution the number of lists and the values specified in each list.
This problem is defined and discussed in Cartesian_Product.
A problem input can be stored in array of arrays of values (or list of lists). An example could be two decks of cards. There are two decks [Red, Blue], each deck has 4 card suits [♠, ♥, ♦, ♣] and for each suit there are 13 cards [Ace, King, Queen, Jack, 10, 9, 8, 7, 6, 5, 4, 3, 2].
The Cartesian product of these arrays returns a 104-element set consisting of 2 decks of 52 possible playing cards:
[[Red, ♠, Ace], [Red, ♠, King], ..., (Red, ♠, 2), (Red, ♥, Ace), ..., (Red, ♣, 2),
[Blue, ♠, Ace],[Blue, ♠, King], ..., (Blue, ♠, 2), (Blue, ♥, Ace), ..., (Blue, ♣, 2)]

So how generate all possible combinations of a list of lists of values?
Answer: Here, a solution written in Javascript.
A possible input of the problem:
var parameterList = [ [ 'Red', 'Blue' ],
                [ '\u2660', '\u2665', '\u2666', '\u2663' ],
                [ 'Ace', 'King', 'Queen', 'Jack', 10, 9, 8, 7, 6, 5, 4, 3, 2 ] ];

Calculate the number of combinations
var num_comb = 1;
for ( var i = 0; i < parameterList.length; i++)
    num_comb *= parameterList[i].length;

Generation of all possible combinations:
// index used to store the positions of the combination just generated
var index = new Array(parameterList.length);
for ( var i = 0; i < parameterList.length; i++)
  index[i] = 0;

//array of arrays that will store the final result (i.e., all possible combinations)
var combinationsList = [];

do {
  var temp = [];
  for ( var i = 0; i < index.length; i++)
    temp[i] = parameterList[i][index[i]];
  combinationsList.push(temp);
} while (nextIndex());

function nextIndex() {
  var carryover = true;
  for ( var i = parameterList.length - 1; i >= 0 && carryover; i--) {
    index[i] = (index[i] + 1) % parameterList[i].length;
    if (index[i] != 0)
      carryover = false;
  }
//if 'carryover' is true and 'i' is equal to zero means that all possible combinations
//have been generated. In this case 'nextIndex' is equal to the first combination.
  return !carryover;
}

var allCombString = printCombinationsList();

For printing all the combinations:
function printCombinationsList() {
  var ret = "";
  for ( var i = 0; i < combinationsList.length; i++) {
    for ( var j = 0; j < combinationsList[i].length; j++)
      ret += ((j == 0) ? "[" : "") + combinationsList[i][j] + ((j == combinationsList[i].length - 1) ? "]": ", ");
    ret += "
";
  }
return ret;
}


LSTM Output Structure

Question: import tensorflow as tf
import numpy as np
from tensorflow.python.ops import rnn_cell, rnn

data = np.random.randint(0, 10, size = (1000, 18))
batch_size = 10
chunk_size = 6
n_timesteps = 3
rnn_size = 128

x = tf.placeholder('float', [batch_size, n_timesteps, chunk_size])
y = tf.placeholder('float')

def neural_network(x):
    x = tf.transpose(x, [1,0,2])
    x = tf.reshape(x, (-1, chunk_size))
    x = tf.split(x, n_timesteps)

    lstm = rnn_cell.BasicLSTMCell(rnn_size)
    outputs, states = rnn.static_rnn(lstm, x, dtype = tf.float32)
    print("Number of outputs: ", len(outputs))
    print("Last output: ", outputs[-1])
    print("LSTM Cell: ", lstm)
    print("Input Data: ", x[0])
    return outputs[-1]

prediction = neural_network(x)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    p = sess.run(prediction, feed_dict = {x:data[:batch_size].reshape((batch_size, n_timesteps, chunk_size))})

Running the code gives me the following output:
('Number of outputs: ', 3)
('Last output: ', <tf.Tensor 'rnn/rnn/basic_lstm_cell/mul_8:0' shape=(10, 128) dtype=float32>)
('LSTM Cell: ', <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x7fc57f5ec390>)
('Input Data: ', <tf.Tensor 'split:0' shape=(10, 6) dtype=float32>)

It makes sense that the number of outputs is 3 because the number of timesteps is 3. What I don't understand is how the last output of the LSTM has a shape of (batch_size, rnn_size).
Answer: First of all, tf.nn.static_rnn documentation states:

Returns:
A pair (outputs, state) where:

outputs is a length T list of outputs (one for each input), or a
  nested tuple of such elements.
state is the final state

Like you already said, in your example, there are T=3 cells, i.e., outputs is a list of 3 outputs of each BasicLSTMCell.
Now, let's have a look at what tf.contrib.rnn.BasicLSTMCell outputs:

Returns:
A pair containing:

Output: A 2-D tensor with shape [batch_size x self.output_size].
New state: Either a single 2-D tensor, or a tuple of tensors matching the arity and shapes of state.

If you look at the classical LSTM picture, it makes perfect sense:

When you pass a single sequence $x_t$, the output of each cell is the vector $h_t$, which has the shape (rnn_size,). Naturally, feeding the mini-batch of length batch_size to the LSTM would produce the mini-batch of outputs, each of (rnn_size,) shape. Hence the result shape (batch_size, rnn_size).

LSTM Output Structure


How to limit the size of dbcontext on large datasource bound to winforms controls

Question: I have a winforms app with a detail form, datagridview, and bindingnavigator all bound to the same datasource.  I'm using entity framework (database first).  The user works with groups of records in the datagridview; hundreds but possibly thousands at a time.  The bindingnavigator shows how many records are currently loaded into memory.
The details form is disabled until they hit an "Edit" button.  Is there a practical way to limit the dbContext to a single record when they decide to edit?  In my mind the dbcontext is tied to the datasource, which is bound to the controls.
Examples I have found such as msdn.microsoft.com/en-us/data/jj682076.aspx explain how to use dbcontext to select the *entire list of entities, bind them to a datagridview, and use context.SaveChanges() to update the database. I have yet to find a good example of how to limit the context to a single record when working with multiple records in winforms.
Answer: you shouldn't be binding EF objects to a dbContext when simply loading for view purposes.  The dbContext should *only be used when you need to perform your CRUD operations.  The context should not be opened for long periods of time either.
You should post where you create your dbContext, you should be closing your context after loading your data.
Comment: yes, that is the cost of doing things right.  =)  learning is painful and we've all been there my friend
Comment: That makes sense.  When the user chooses a record to edit, I can call the db and get the single record using the context.  But I'm not understanding how the context will recognize changes made in the details form, since the form is already bound to the larger group of records.  Does my question make sense?
Comment: yes, that is for simple grids... if you are going to do large scale updates on huge data sets then that would be a serious performance issue.  in general you do NOT need and should not use the dbcontext like that.  But if you have a simple page with a simple grid then I guess use it.  MS Examples are overly simplistic, they also show code where they access the DB from the view...  another no no for high performing systems.
Comment: Agreed.  Just need to find an example of how it's done the right way :-)
Comment: close your context after loading... as no changes should have occurred.  Then when you edit add the object/source for that row into a list... upon save create a new context and iterate through your list, save through that.
Comment: @T McKeown I load the records and dispose context (with using statement).  When it comes time to save changes, I create a new context and use context.Add to add the current record (from BindingSource.Current) - but then EF tries to insert rather than update.  Thanks for sticking with me on this.
Comment: it tries to INSERT because you issued an .Add(), instead use .Attach().  Attach will tell the dbContext that this record should be updated, but you should **ONLY** do that if there are changes.  IF you don't know if there are changes then I guess you would attach every row in the grid... it's possible but not a good idea.  You should Add/Remove/Attach only if there is some change you want to persist.
Comment: Checked as answer (appreciate the help!).  I added an event for bindingsource.CurrentChanged.  When that happens I create a new context and .Attach the bindingSource.Current item.  (also dispose context from prior record if needed).  Then when user saves I simply call context.SaveChanges.  This works fine; however now some other functions are failing that relied on other entities related to this record.  They were included when using the dbcontext but are no longer available in the bindingsource datasource since the original context (which loaded all the records) has been disposed.
Comment: if you wanted to allow changes and then update DB upon a button click etc.. then instead of attaching upon the CurrentChange event you could add to a list... then when the Save button is clicked you could loop thru and attach all of them there.  I however like the way you are doing now but that is just a preference.


Realloc not expanding my array

Question: I'm having trouble implementing realloc in a very basic way.
I'm trying to expand the region of memory at **ret, which is pointing to an array of structs
with ret = realloc(ret, newsize); and based on my debug strings I know newsize is correctly increasing over the course of the loop (going from the original size of 4 to 8 to 12 etc.), but when I do sizeof(ptr) it's still returning the original size of 4, and the things I'm trying to place into the newly allocated space can't be found (I think I've narrowed it down to realloc() which is why I'm formatting the question like this)
I can post the function in it's entirety if the problem isn't immediately evident to you, I'm just trying to not "cheat" with my homework too much (the code is kind of messy right now anyway, with heavy use of printf() for debug).
[EDIT] Alright, so based on your answers I'm failing at debugging my code, so I guess I'll post the whole function so you can tell me more about what I'm doing wrong.
(You can ignore the printf()'s since most of that is debug that isn't even working)
 Booking **bookingSelectPaid(Booking **booking)  {
     Booking **ret = malloc(sizeof(Booking*));
     printf("Initial address of ret = %p\n", ret);
     size_t i = 0;
     int numOfPaid = 0;
     while (booking[i] != NULL)
     {
         if (booking[i]->paid == 1)
         {
             printf("Paying customer! sizeof(Booking*) = %d\n", (int)sizeof(Booking*));
             ++numOfPaid;
             size_t newsize = sizeof(Booking*) * (numOfPaid + 1);
             printf("Newsize = %d\n", (int)newsize);
             Booking **temp = realloc(NULL, (size_t)newsize);
             if (temp != NULL)
                 printf("Expansion success! => %p sizeof(new pointer) = %d ret = %p\n", temp, (int)sizeof(temp), ret);
             ret = realloc(ret, newsize);
             ret[i] = booking[i];
             ret[i+1] = NULL;
         }
         ++i;
         printf("Sizeof(ret) = %d numOfPaid = %d\n", (int)sizeof(ret), numOfPaid);
     }
     return ret; }

[EDIT2] --> http://pastebin.com/xjzUBmPg
[EDIT3] Just to be clear, the printf's, the temp pointer and things of that nature are debug, and not part of the intended functionality. The line that is puzzling me is either the one with realloc(ret, newsize); or ret[i] = booking[i]
Basically I know for sure that booking contains a table of structs that ends in NULL, and I'm trying to bring the ones that have a specific value set to 1 (paid) onto the new table, which is what my main() is trying to get from this function... So where am I going wrong?
Comment: What exactly is the question here?  (I don't see a question-mark anywhere...)
Comment: I guess the question is: "What am I doing wrong?"

Basically, I've allocated '**ptr = malloc(sizeof(my_structure*))'
without knowing how many instances of the structure will be in my array, and then based on a loop, I'm incrementing a size variable and using that in 'ptr = realloc(ptr, newsize)' but I'm not able to place any more structs into the array...

I can post the whole code even at the risk of failing my course if I'm being too ambiguous, haha.
Comment: @user1478361 : Next time, use 'code sample' for code instead of 'blockquote' (it's in the editing toolbar). I fixed it for you for now.
Answer: I think the problem here is that your sizeof(ptr) only returns the size of the pointer, which will depend on your architecture (you say 4, so that would mean you're running a 32-bit system).
If you allocate memory dynamically, you have to keep track of its size yourself.
Comment: I've updated my initial post to include the code from the problem area. (And since I don't understand how to bring the control characters with me onto stackoverflow, I posted it on pastebin as well)

[EDIT] Hm... And now it's properly formatted all of a sudden -- oh well, you don't need to look at pastebin now I guess
Comment: It looks like your `i` could get bigger than `numOfPaid`, which means that `ret[i]` and `ret[i+1]` could run over.
Comment: Even when the table provided by main only has 4 entries, including the NULL pointer? (I can post a screencap of the stdout print in the console if that would give more insight -- even though my debug is partly false)
Comment: Well.. I just tried modifying the malloc() directly to `4 * sizeof(Booking*)` and even then it's not printing more than the first entry, so clearly it's not going wrong where I thought it was... I guess that means I've mis-titled the whole question
Comment: so here's the function without debug crap in it: http://pastebin.com/SACkET8M

and this is the main() calling it: http://pastebin.com/sfcBCTWT
Comment: The main() is provided by the assignment so that's correct... I was tasked with implementing the rest of the functionality myself, including the definition of the structure

Actually.. considering I've probably already failed this course anyway, I'll just post the bulk of this assignment... I just want to  know what I'm doing wrong so I can finally get some sleep.

main: http://pastebin.com/TzabvU0V
header file: http://pastebin.com/m1mAuXsc
my implementations: http://pastebin.com/MFg0KyJi
Comment: As I said, you should replace `ret[i]` with something like `ret[numOfPaid-1]` and `ret[i+1]` with `ret[numOfPaid]`. Even better, pre-iterate bookings to figure out how much memory you need (also much faster).
Comment: So obviously I've made at least one idiotic mistake somewhere (lack of understanding + sleep deprivation => the above), and right now I'd be incredibly relieved to at least understand this one thing.

Apologies for making everyone debug bad code, but I've done all I can to the best of my understanding based on the materials available to me currently. =S
Comment: Oh, I see...  Was the indexing the only thing really badly wrong? That already fixed it but I guess I'll try and do the pre-iteration as well... (I can't believe how long I've spent on this already)

Thanks, though.
Answer: Because sizeof(ptr) returns the size of the pointer, not the allocated size
Answer: Yep, sizeof(ptr) is a constant. As the other answer says, depends on the architecture. On a 32 bit architecture it will be 4 and on a 64 bit architecture it will be 8. If you need more help with questions like that this homework help web site can be great for you.
Good luck.

Realloc not expanding my array


Admin Access for Webform Entries

Question: The following problem has occurred:
A client fills in a reservation form, but the time requested is already fully booked. The clerk and the client negotiate a different time, and the clerk wants to change the requested time (f.e. 18:00) to the negotiated time (f.e. 20:00) -- but as the same form has a date restriction (one cannot reserve on the same day) the clerk can't save the form at the day of the appearance.
Is there any way to give a role the permission to change every webform, without any restrictions? I.e. any changes made by role "Trusted User" will not be checked in any way.
Answer: Webform for Drupal 8 allows you to give a role (or specific user) access to view and update submissions of a SPECIFIC webform to accomplish what you need
Goto Settings > Access of the webform in question and assign VIEW ANY SUBMISSIONS and  UPDATE ANY SUBMISSIONS to your Trusted user role

Than you have to give this user the URL to view and edit/update all the submissions.  For example for the contact form they should visit <code>/admin/structure/webform/manage/CONTACT/results/submissions</code> and they would be able to see all submissions and edit them.
Comment: Nope, this doesn't work. The field restriction still get checked, even for the Admin / SuperUser with all access rights. The form you showed is just a "by form" override of the system wide webform access rights, and is in no way different to these. Been there, did that drill, no avail. But still thanks for your time and effort.
Comment: @NorbertFürst I have actually tested what I posted and it works I am not sure what might be different in your installation, so you might want to try posting more detail or perhaps try it on a clean install.

Admin Access for Webform Entries