Por que não consigo usar module export para exportar variável

Question: Explicação:
Bom galera no meu arquivo app.js tenho muitas linhas de códico ... Algumas funções ... Mais acho que isso não importa muito, então o que eu quero fazer é exportar uma variável que preciso usar em outro arquivo já tentei de tudo mais não vai, tentei até das maneiras mais simples.
O que quero fazer:
//app.js
token = 'Teste' //Variável que quero exportar
module.exports = {
 token:token
}

E no arquivo account.js
//account.js
x = require("./app.js");
console.log(x.token);

Problema: Galera se eu testar esse códico funciona, porém no meu projeto não tem só isso, eu tenho outras funções e importações de lib ... Porém não funciona ... Sempre dá undefined.
Outra solução que encontrei:
//app.js
token = 'Teste'
exports.token = token

//account.js
x = require("./app.js")
console.log(x.token)

Enfim, funcionou mas porque não funcionou do jeito que eu queria ? Não quero usar desta forma só porque funciona, até porque do jeito que queria fazer funciona em um arquivo que contenha só esse trecho, porém no meu arquivo não tem só isso, tem mais algumas funções ... E não sei se isso afeta a forma que quero fazer a exportação da variável.
O cenário em que quero aplicar a primeira forma que quero fazer:
async function verify(req,res,username,password){
 db.serialize(async function (){
  const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
  db.all(query,[username, password],async function(err,rows){
   try{
    if(rows.length == 1){
     console.time("time1")
     await console.log(rows);
     console.log("Correct user");
     res.render(__dirname + "/View/Home/index.handlebars");
     module.exports = {
      rows:rows //Desta forma era pra funcionar
     }
     console.timeEnd("time1")
    }
    else{
    console.log("Incorrect user!")}}
   catch{
    console.error("\x1b[31m","Problema com a função de autenticação, erro: \n", err);
   }
  })
})}

Porém no meu arquivo account.js:
const express = require('express');
const app = express();
const router = express.Router();
const rows = require("./app.js")
const io = require('socket.io')
const handlebars = require("express-handlebars");
const multer = require("multer");
const path = require("path");

app.engine("handlebars", handlebars({defaultLayout:false}));
app.set("view engine","handlebars");
app.get('/',(req,res) => {
 res.render(__dirname + "/View/Account/account.handlebars")
 console.log(rows.rows);
 //Quando eu entrasse nessa rota eu queria que aparecesse o valor da variável da forma que eu queria exportar como havia explicado
});

module.exports = app

Tipo de erro: Undefined
Tem mais coisas no meu arquivo app.js mas só coloquei a função onde quero usar o módulo export.
Comment: Não tem nada de errado com nenhum dos seus códigos. Todos funcionam corretamente (exceto as aspas no final de `x.token`), mas creio que tenha sido um acidente durante a pergunta. Enfim, tente criar um [mcve] e trazer para cá. Não precisa incluir _todo_ o seu arquivo, somente tentar **reproduzir** o que não está dando certo (porque atualmente a pergunta está "ok").
Comment: Sim foi acidente vou editar, porém também vi que não tem problema quando você testa só desta forma porém meu códico app.js e account.js é bem maior do que mostrei e talvez isso interfira você acha que devo postar todo o códico dos arquivos aqui? Porque o códico original é grandinho
Comment: Eu editei como recomendou :)
Comment: @Guilherme você está dando o export dentro da função verify que nem está sendo chamada, talvez realizando a chamada dela no final do arquivo dê certo, mas você está fazendo no minimo algo peculiar, chamando o export dentro de uma função assincrona, talvez não fosse melhor exportar a função que retorna esse dado e então usar no account.js?
Comment: Ela está sim sendo chamada só mostrei onde tentei usar, mas o problema é que quando eu chamo a função da undefined não era pra acontecer isso.
Comment: E não posso exportar a função pq não vou usar a função só a variável.
Answer: O contexto está um tanto confuso, mas acredito que o erro está na função assincrona.
A função verify que você criou é uma função assincrona, mas a palavra reservada await está no inicio do console.log(...).
Assim, quando você exporta as variaveis, elas podem não ter tido tempo de ser geradas.
o await deve vir antes de uma Promise, como por exemplo antes de db.all(....) que fará uma consulta no banco de dados.
Comment: console.log não é assíncrono,
Answer: Aparentemente, oque você deseja é manter algumas variáveis para um usuário em especifico entre as requisições, se este for o caso, você deve usar sessões.
de uma olhada no pacote npm express-session, talvez lhe satisfaça:
https://www.npmjs.com/package/express-session
exports é uma variável equivalente a global no escopo da função que você executa...não é recomendado usar variáveis globais para guarda variáveis que dependem de usuário para usuário, elas iram sobrescrever umas as outras
ou
se a questão não é está, mas simplesmente retorna a valor de ROW, de dentro da função verify
aconselho que refatore-o para usar Promise, resolvi refatorar e deixei alguns comentarios:
//removi o parametro req pós não é utilizados
function verify(res,username,password){
    return new Promise((resolve,reject)=>{
        //não precisa de async, pós não há await dentro
        db.serialize(function (){
            const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
            //não precisa de async, pós não há await dentro
            db.all(query,[username, password],function(err,rows){
                try{
                    if(rows.length == 1) {
                        console.time("time1");
                        //console.log não é uma função assincrona, não precisa de await
                        console.log(rows);
                        console.log("Correct user");
                        res.render(__dirname + "/View/Home/index.handlebars"/*, objeto com variaveis para o handlerbars*/);
                        //não retorne a variavel pelo exports, exports é um globlal
                        //em um ambiente com varias requisições, passar as respostas de varias requisições por uma global não é nada recomendado, pós entre o tempo de definila e finalizar e retorna, ela já pode ter sido sobreescrita por outra requisição
                        //isso ira retorna pelo await...;
                        resolve(rows);
                        console.timeEnd("time1")
                    } else {
                        console.log("Incorrect user!");
                        //adicionei um res.send, pós se a requisição nunca chamar res.send, o browser ira aguarda até gerar um erro "timeout" pós, nenhuma respostas foi enviada
                        res.send("Incorrect user!");
                    }
                } catch (e){
                    res.send("Problema com a função de autenticação");
                    console.error("\x1b[31m","Problema com a função de autenticação, erro: \n", err);
                }
            }
        });
    });
}

*obs.: por não conhecer a API de DB utilizada, não adicionei os casos em que a query da errado (que também pode ser um motivo de row nunca ser definido)...
Comment: Então ...a variável pode ser sobrescrita por outra requisição, porém o que quero fazer é exportar a variável rows para meu arquivo account.js que vai percorrer o array e pegar o id do usuário, pra buscar uma foto que tem esse nome (que vai ser o id do usuário) e carregar essa foto na página account, porém pra isso preciso exportar a variável assim que fazer login só que preciso resolver isso na questão da variável ser sobrescrita, poderia me dar um guia ? Porque já tô com esse problema a um tempo
Comment: @Guilherme, você vai passar por parâmetros de funções/retorno se puder fazer isso em única requisição (que é o recomendado)..., e se você vai buscar por usuário em especifico, também é recomendado fazer isso na query, fazer isso no node js, vai aumentar o consumo de RAM e Rede bastante, desnecessariamente
Comment: @Guilherme a função verify como está na resposta retorna o rows; obs: o "res.send" só pode ser chamado uma vez, recomendo que você o-faça na apenas na narrow function que está no get, para evitar varios "res.send" espalhados por varios arquivos...que podem deixar o código mais difícil encontrar bugs; ah, pra pegar o retorno da função verify no get, você usar then().catch, ou mudar a declaração da narrow function, de "(req,res) => {" para "async (req,res) => {", e usar await verify(...
Comment: @Guilherme quanto a foto de perfil do usuario, se não precisar ser privada, você pode simplesmente salva-la em uma pasta publica de conteúdo estático, e usar algum propriedade unica como id do usuario como nome...; ah e se você está fazendo um sistema com logins; você vai precisar de sessões; olhe o link do express-session; e pesquise sobre logins e sessões no node-js, é bem comun tutoriais sobre sessões/logins pela internet, para qualquer plataforma
Comment: Sim, eu salvo o id do usuário como nome da foto, porém preciso carregar determinada foto para determinados usuários, porém quando eu faço login e vou pra Index, e a foto que deve ser carregada deve ser carregada na página account, porém como vou saber qual foto deve ser carregada a determinado usuário? Por mais que eu tenha salvado o id como nome da foto eu preciso do id do usuário que está acessando a rota para buscar a foto dele, e como conseguir o id do usuário se não for exportando? Porque minha página account é acessada na rota account.
Comment: Pensei na seguinte solução para meu problema, o usuário logar, eu salvar esse id no cookie e quando acessar a rota account, crio uma função para ler o valor do cookie capturando o id, e sabendo o id então buscar a foto e carregar, porém está solução não é tão elegante já que vi um post com uma maneira diferente de fazer porém lá é só passo a passo na teoria não tem prática e era usando banco de dados então não sei aplicar e se é possível de outro jeito a não ser este.
Comment: @Guilherme, você precisa de sessões, sessões são como cookies do lado do servidor! leia sobre sessões/logins...como recomendei, sessões é um "assunto" trivial para logins em servidores
Comment: como seu ultimo comentario sugeriu, você vai salva no "cookie", mas no "cookie do servidor", na sessão... é assim que se faz normalmente, boa sorte
Answer: se seu Node JS não suporta ES6 (versão anterior a 10), o erro é este:
module.exports = {
 token:token
}
//que pode ser
module.exports = {
 token
}
//ou
module.exports = {
 'token':token
}

ao fazer token:token, vocé ele cria um objeto com uma váriavel que tem tanto o nome quanto o valor igual a 'Teste', se você não deseja colocar um novo nome a variável, coloque apenas ela, se deseja dar um novo nome dentro do objeto, para evitar que o valor de outra variável seja usada como chave, use uma string, para evitar que o valor de outra variável seja utilizado como nome dentro do objeto
'novoNome':token,

isto é um dos recursos que antes do ES6 tornava Java script fácil de escrever e difícil de quebrar..., que as vezes pode lhe deixar confuso.
OBS.: se o nome da variável dentro do objeto, não fosse uma variável definida funcionaria...
Comment: Na verdade isso não está errado, essa forma mais simplista foi introduzida no ES6 e é chamada de "Object Property Value Shorthand", caso queira saber mais pode ver aqui: https://alligator.io/js/object-property-shorthand-es6/
Comment: @VictorNogueira, mas até o node js 10, o ES6 não existe ou é experimental, e até final do ano passado, o node js 8 ainda era usado em produção, pelo google por exemplo (firebase), que tirou o suporte do node js 8 e adicionou o suporte ao 12, versões mais recentes do node JS ficam fora...


how to add data to array using for loop in php?

Question: I am making a mysql query . I want to add  result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
    {
        $row = mysql_fetch_array($query);
        //echo ($row);
         $num=mysql_num_rows($query);
        echo ($num);
        for ($i=1; $i<=$num;$i++){

        //here I want to save all name to an array.

        }

Please help.
Comment: read any basic PHP MySQL tutorial on the web. This is pretty basic thing.
Answer: You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
    $rows []= $row;
}

Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()
Answer: $num = mysql_num_rows($query);

if($num > 0)
{
    while($row = mysql_fetch_array($query)
    {
        $names[] = $row['name'];
    }
}

That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.


Sort an array that are merged together

Question: I have 2 strings that I made into an array to sort then to convert back into a string. But, in my test in my response.body The given string is sorted differently. I have a method that takes 2 strings and removes the headers from both and mergers the array and sorts it. But getting different results. How can I get the desired results of the below response.body string
string1 = "Category Name,Code,Enabled?,Category Hidden?\nPRESENT AVAIALBLE,PRESENT AVAILABLE,No,No,\nBUG AVAILABLE,BUG,No,No,\nBUG,BUG,No,No,\nPRESENT,PRESENT,No,No\n"

string2 = "Category Name,Code,Enabled?,Category Hidden?\nBUG,BUG,No,No,\nBUG AVAILABLE,BUG,No,No,\nEXAMPLE 1,EXAMPLE 1,Yes,No,\nEXAMPLE 2,EXAMPLE 2,Yes,No,\nPRESENT AVAIALBLE,PRESENT AVAILABLE,No,No,\nPRESENT,PRESENT,No,No\n"

how would I get that array to be sorted as the response.body string before inserting the header "Category Name,Code,Enabled?,Category Hidden?"
response.body string
"Category Name,Code,Enabled?,Category Hidden?
BUG,BUG,No,No,
BUG AVAILABLE,BUG,No,No,
EXAMPLE 1,EXAMPLE 1,No,No,
EXAMPLE 2,EXAMPLE 2,Yes,No,
PRESENT,PRESENT,No,No"
PRESENT AVAIALBLE,PRESENT AVAILABLE,No,No"

My output from method
"Category Name,Code,Enabled?,Category Hidden?
BUG AVAILABLE,BUG,No,No,
BUG,BUG,No,No,
EXAMPLE 1,EXAMPLE 1,No,No,
EXAMPLE 2,EXAMPLE 2,Yes,No,
PRESENT AVAIALBLE,PRESENT AVAILABLE,No,No,
PRESENT,PRESENT,No,No"

method I wrote
def merge(string1, string2)
  string1 = string1.split("\n") # Split into array.
  headers = string1.first # Get headers.
  string1.shift # Remove headers.
  string2 = string2.split("\n")[1..-1] # Remove headers.
  final = (string1 + string2).sort.unshift(headers).join("\n") + "\n" # Create merged sorted string.
end

desired result wanted
"Category Name,Code,Enabled?,Category Hidden?
BUG,BUG,No,No,
BUG AVAILABLE,BUG,No,No,
EXAMPLE 1,EXAMPLE 1,No,No,
EXAMPLE 2,EXAMPLE 2,Yes,No,
PRESENT,PRESENT,No,No"
PRESENT AVAIALBLE,PRESENT AVAILABLE,No,No"

Comment: also include your desired result in question
Comment: @Dave I updated with the desired result wanted
Comment: You desired result appears to be the same as your given string.
Comment: the output from my method is not the same as the response.body string.
Comment: You say you are given two strings but you only show one. I am guessing that the two strings are `"Category Name,Code,Enabled?,Category Hidden\nBUG,BUG,No,No,\nEXAMPLE 1,EXAMPLE 1,No,No,\nPRESENT,PRESENT,No,No"` and `"Category Name,Code,Enabled?,Category Hidden?\nBUG AVAILABLE,BUG,No,No,\nEXAMPLE 2,EXAMPLE 2,Yes,No,\nPRESENT AVAIALBLE,PRESENT AVAILABLE,No,No"`. Correct? If so you need to include that in your question.
Comment: @CarySwoveland apologies, I updated the question with the 2 strings
Answer: Here are three ways to do that.
I assume you are given two strings:
str1 = "Category Name,Code,Enabled?,Category Hidden?\nBUG,BUG,No,No\nEXAMPLE 1,EXAMPLE 1,No,No\nPRESENT,PRESENT,No,No"

str2 = "Category Name,Code,Enabled?,Category Hidden?\nBUG AVAILABLE,BUG,No,No\nEXAMPLE 2,EXAMPLE 2,Yes,No\nPRESENT AVAILABLE,PRESENT AVAILABLE,No,No"

Then
header, *body1 = str1.split("\n")
  #=> ["Category Name,Code,Enabled?,Category Hidden?",
  #    "BUG,BUG,No,No",
  #    "EXAMPLE 1,EXAMPLE 1,No,No",
  #    "PRESENT,PRESENT,No,No"]

so
header
  #=> "Category Name,Code,Enabled?,Category Hidden?"
body1
  #=> ["BUG,BUG,No,No",
  #    "EXAMPLE 1,EXAMPLE 1,No,No",
  #    "PRESENT,PRESENT,No,No"]

and
_, *body2      = str2.split("\n")
  #=> ["Category Name,Code,Enabled?,Category Hidden?",
  #    "BUG AVAILABLE,BUG,No,No",
  #    "EXAMPLE 2,EXAMPLE 2,Yes,No",
  #    "PRESENT AVAILABLE,PRESENT AVAILABLE,No,No"]

so
_ #=>  "Category Name,Code,Enabled?,Category Hidden?"
body2
  #=> ["BUG AVAILABLE,BUG,No,No",
  #    "EXAMPLE 2,EXAMPLE 2,Yes,No",
  #    "PRESENT AVAILABLE,PRESENT AVAILABLE,No,No"]

We may then compute the desired string.
str = [header].concat(body1.zip(body2).flatten).join("\n")
  #=> "Category Name,Code,Enabled?,Category Hidden?\nBUG,BUG,No,No\nBUG AVAILABLE,BUG,No,No\nEXAMPLE 1,EXAMPLE 1,No,No\nEXAMPLE 2,EXAMPLE 2,Yes,No\nPRESENT,PRESENT,No,No\nPRESENT AVAILABLE,PRESENT AVAILABLE,No,No"

which when displayed appears as follows.
puts str
Category Name,Code,Enabled?,Category Hidden?
BUG,BUG,No,No
BUG AVAILABLE,BUG,No,No
EXAMPLE 1,EXAMPLE 1,No,No
EXAMPLE 2,EXAMPLE 2,Yes,No
PRESENT,PRESENT,No,No
PRESENT AVAILABLE,PRESENT AVAILABLE,No,No

See Array#concat, Array#zip, Array#flatten and Array#join.
The variable _ in _, *body2 = str2.split("\n") is so-named to tell the reader that it is not used in subsequent calculations. Sometimes might write _header, *body2 = str2.split("\n") to convey the same message.

Here is a second way of doing that by treating the strings as comma-delimited CSV strings.
require 'csv'

arr1 = CSV.parse(str1)
  #=> [["Category Name", "Code", "Enabled?", "Category Hidden?"],
  #    ["BUG", "BUG", "No", "No"],
  #    ["EXAMPLE 1", "EXAMPLE 1", "No", "No"],
  #    ["PRESENT", "PRESENT", "No", "No"]],

arr2 = CSV.parse(str2)
  #=> [["Category Name", "Code", "Enabled?", "Category Hidden?"],
  #    ["BUG AVAILABLE", "BUG", "No", "No"],
  #    ["EXAMPLE 2", "EXAMPLE 2", "Yes", "No"],
  #    ["PRESENT AVAILABLE", "PRESENT AVAILABLE", "No", "No"]]

Then
str = CSV.generate do |csv|
  csv << arr1.shift
  arr2.shift
  until arr2.empty? do
    csv << arr1.shift
    csv << arr2.shift
  end
end
  #=> "Category Name,Code,Enabled?,Category Hidden?\nBUG,BUG,No,No\nBUG AVAILABLE,BUG,No,No\nEXAMPLE 1,EXAMPLE 1,No,No\nEXAMPLE 2,EXAMPLE 2,Yes,No\nPRESENT,PRESENT,No,No\nPRESENT AVAILABLE,PRESENT AVAILABLE,No,No\n"

puts str
Category Name,Code,Enabled?,Category Hidden?
BUG,BUG,No,No
BUG AVAILABLE,BUG,No,No
EXAMPLE 1,EXAMPLE 1,No,No
EXAMPLE 2,EXAMPLE 2,Yes,No
PRESENT,PRESENT,No,No
PRESENT AVAILABLE,PRESENT AVAILABLE,No,No

See CSV::parse and CSV::generate.

This can also be done without converting the strings to arrays, manipulating those arrays to form a single array and then converting the single array back to a string.
arr = [str1, str2]
str_indices = 0..str1.count("\n")
arr_indices = 0..arr.size-1
idx_begin = Array.new(arr.size, 0)

puts str_indices.each_with_object("") do |i, str|
  arr_indices.each do |j|
    idx_end = arr[j].index(/(?:\n|\z)/, idx_begin[j])
     s = arr[j][idx_begin[j]..idx_end]
     s << "\n" unless s[-1] == "\n" || (i == str_indices.last && j == arr_indices.last)
     str << s unless i.zero? && j > 0
     idx_begin[j] = idx_end + 1
  end
end
Category Name,Code,Enabled?,Category Hidden?
BUG,BUG,No,No
BUG AVAILABLE,BUG,No,No
EXAMPLE 1,EXAMPLE 1,No,No
EXAMPLE 2,EXAMPLE 2,Yes,No
PRESENT,PRESENT,No,No
PRESENT AVAILABLE,PRESENT AVAILABLE,No,No

The regular expression /(?:\n|\z)/ matches a newline character (\n) or (|) the end of the string (\z).
See the form of String#index that takes an optional second argument that specifies the string index where the search is to begin.

Sort an array that are merged together


Is one Marathon per season more unhealthy than three Marathon per season?

Question: Although it seems rather counter-intuitive to me, I have heard multiple times that running just a single Marathon per season is more unhealthy than 3-4 Marathons per season.
The reasoning seems to be that it should be rather stressful to the body to get in shape for the first Marathon, but keeping fit between runs shouldn't so bad.
I have looked for some materials on the web to clarify the issue, but to no avail. Can anybody clarify the issue for me?
Comment: Hi Tonny! You should ask Joergen Pedersen, your former colleague! :)
Answer: Last year I ran two ultras and four marathons, all quite slowly, all but one with negative splits, and it feels very good. I completed two marathons on two consecutive weekends, and enjoyed them both.
Before that, I was trying to improve my speed, running 1-2 races per year, and that definitely was less healthy for me. I did not like tapering - last week before the race just felt terrible. I hated the recovery - I'd rather work out than rest because of sore muscles.
So, for me trying to run one marathon per year with full effort was not healthy and not enjoyable at all. Running multiple ones with enjoyable speed, not hitting the wall ever, with negative splits, and no pain is a lot of fun. I am just staying in shape all the time, and enjoying a good scenic race whenever I feel like it.
We are all different. What works for me might not work for others. I am not cut out for fast running: I do not look like a lean gazelle. On the other hand, having considerable muscles and thick and strong tendons allows me to run injury-free, even though it prevents me from running fast.
I have lean friends who have real chances to qualify for Boston, (1-2 minutes short), but keep spending considerable time every year limping. They are much faster but more prone to injuries.
Answer: It would seem there are so many variables involved that are independent of the number of marathons you run to make any such conclusion meaningless.
For example:

personal fitness
training schedule
injuries
genetics (how you handle running)
Racing vs running the marathon

Clearly for an ultra marathoner who has spent decades training, running one or three marathons a month even may not make a difference.
At the other extreme a newbie who is working towards their first marathon, should probably find three marathons in a season a really bad plan.
However in between is where the interesting bits happen.
There is value in keeping your base training for longer, and just using the marathons along the way as long training runs, perhaps at a faster pace.
I notice the question did not ask, Racing 3 marathons vs 1.  I think that is a key distinction as well.  If you race the marathons, then that is very different than just running them.
I suspect this is one of those 'it really depends' answers.
Comment: I should think that many of the people that _run_ Marathon - opposed to _racing_ the same Mathon - might feel they are in fact racing... or at least going as fast as they possibly can :-)
Comment: @TonnyMadsen Interestingly enough, I would define Racing vs Running as totally personal.  I.e. My racing is what many would consider jogging.  I am slow, however, if I am running at a pace that takes me to my goal, then that is racing.  I make no value claims on speed.  It is all personal.
Comment: So racing is when you run as fast as you possibly can.
Comment: @TonnyMadsen Not quite.  I would argue it is when you pace yourself for a time you consider racing.  I.e. In a marathon your pace would differ from a 5K and therefore you could try to run a 5K pace, but it will kill you over the marathon distance, so you need a different pace for different distances.
Answer: It's not actually running the marathons that's more healthy, it's staying in marathon shape for the whole time, as opposed to building up to a marathon, then letting yourself go for the rest of the season, then having to build up for the next marathon, etc.  Building up is where you are most likely to injure yourself, so staying in shape between marathons is the important thing, not running more of them.
Answer: I don't think these long runs are a healthy or natural activity for the human body, so the fewer the better. If you are interested in health rather than marathon performance, mix up your exercise types, include high intensity and weight bearing activities as well.
Comment: I agree... Almost everything we discuss on this site, is not healthy when done in the competitive manner... And Marathon running is likely very unhealthy for my body. But it is extremely healthy for my mind! But my question was comparative: is one more unhealthy than three?


How $\det(AB)=\det(A)\cdot \det(B)$, when $A, B$ not square matrixes but $AB$ square

Question: If $A$ is a matrix of order $m\times n$, and $B$ is a matrix of order $n \times m$. So $AB$ is a square matrix and $\det(AB)$ therefore, exists.
By $\det$ properties:
$$\det(AB)=\det(A)\cdot \det(B)$$
But $\det A$ and $\det B$ cannot exist, as $A, B$ are not square matrixes.
How can it be?
Thank you.
Comment: "By det properties: detAB=detA*detB" - true only if $A$ and $B$ are square.
Comment: So every time i use this rule i must prove or assume that A,B are square, thanks
Comment: Yes, the rule only holds in that case.
Comment: What is the determinant of a non-square matrix?
Comment: I'm sure that is not what Alon is looking for in an intro linear algebra class.
Comment: It is undefined?
Comment: @ElliotG , I hope this helps, http://static.bsu.az/w24/pp.163-175.pdf
Comment: So undefined on my level?
Answer: The Cauchy-Binet formula is one generalization of the multiplicative property of determinants to when $A$ and $B$ are not square but whose product is square. If $A$ and $B$ are matrices with dimensions $m \times n$ and $n \times m$, where $m \le n$, the formula states that:
$$\det(AB) = \sum_{1 \le i_1 < i_2 < \ldots < i_m \le n} \det{A_{[i_1,\ldots, i_m]}}\det{B_{[i_1,\ldots,i_m]}}$$
where $A_{[i_1,\ldots,i_m]}$ is the $m \times m$ matrix formed by taking the $i_1$th through $i_m$th columns of $A$ and $B_{[i_1, \ldots, i_m]}$ is the $m \times m$ matrix formed by taking the $i_1$th through $i_m$th rows of $B$.
In the case where $m = n$, there's only one possible choice of indices $i_1 = 1, i_2 = 2, \ldots, i_m = m$ and we recover the standard multiplicative property of square matrices.
Comment: I didnt ubderstand the formula, but mybe it will help  someone else, thanks.
Answer: The definition is as follows:
"The determinant of a matrix product of square matrices equals the product of their determinants" (Wikipedia)
We must have $A$ and $B$ be $n \times n$.
We cannot have $A$ as $n\times n$ and $B$ as $s\times s$, because then their product is not defined.
You are assuming that just because the product is square, that the initial two matricies are square. This is not true, as you have shown in your example.
Comment: Ok, i understand, thanks


Entity Framework 6: Problema no gerenciamento de contextos

Question: Tenho o objeto Agenda e o crio da seguinte forma:
public class Program
{
    public static void Main(string[] args)
    {
        var clienteDAO = new ClienteDAO();
        var treinoDAO = new TreinoDAO();
        var agendaDAO = new AgendaDAO();

        var treino1 = treinoDAO.ObterTreino(1);
        var treino2 = treinoDAO.ObterTreino(2);

        var agenda = new Agenda();
        agenda.Data = new DateTime(2017,12,11);
        agenda.Horario = "14:00";
        agenda.Observacoes = "";
        agenda.Treinos.Add(treino1);
        agenda.Treinos.Add(treino2);

        agendaDAO.Cadastrar(agenda, 2);
    }
}

Ao cadastrar, o EF da erro dizendo que há vários contextos gerenciado o mesmo objeto (nesse caso, o objeto treino). Isso porque utilizei outro contexto para buscar os treinos. Então tento 'desatachar' e adicionar ao contexto novamente, porém o problema persiste:
public class AgendaDAO
{
    private PJContext _db = new PJContext();

    public void Cadastrar(Agenda agenda, int clienteId)
    {
        agenda.ClienteId = clienteId;

        foreach (var treino in agenda.Treinos)
        {
            _db.Entry(treino).State = EntityState.Detached;
            _db.Entry(treino).State = EntityState.Added;
        }

        _db.Set<Agenda>().Add(agenda);
        _db.SaveChanges();
    }
}

System.InvalidOperationException: 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'

Quando faço o "Detached" não adianta nada, pois acho que somente o outro contexto que o está observando pode fazer isso.
Há alguma forma de tirá-lo do contexto?
Comment: O contexto fica observando suas entidades em busca de alterações. Quando você instância um novo DbContext ele desconhece essas alterações (pois elas estão em outro DbContext). Trabalhar em EF com múltiplos DbContext acaba ficando complicado. Talvez a melhor solução seja utilizar [singleton pattern](https://msdn.microsoft.com/en-us/library/ff650316.aspx).
Comment: Você esta dando Dispose no seu Contexto após você consultar?
Comment: Ah, não fiz isso :|
Comment: Faça o teste se vai arrumar o problema e compartilhe com a comunidade, se arrumar eu respondo a pergunta.
Comment: Engraçado, eu busco o objeto, armazeno numa variável depois dou o disposed e retorno o mesmo, mas ele da erro falando que não da para buscar o objeto pq dei o dispose.
Comment: Esse objeto é IQueryable? Enquanto ele for IQueryable ele não vai estar na memória e você vai dar dispose antes de ele ser colocado. Faça a conversão utilizando o ToList() e veja se resolve.
Comment: Vishe, não sei muito trabalhar com IQueryable. Tentei tirar o List da Agenda para IQueryable e criar um método de adicionar treino e dentro desse método converter o IQueryable para List. Mas o problema é que dá erro no mapeamento fluent api, pois ele não aceita IQueryable.
Comment: Depois de buscar o objeto, desatachei ele e retornei, deu certo. Mas não sei se essa é a melhor forma a se fazer.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/68810/discussion-between-gabriel-coletta-and-raphael).
Answer: Você precisa fazer o dispose da conexão com o banco. Quando você não faz isso, a sua primeira consulta faz com que o Entity Framework faça o tracking desse objeto (Utilizar o .AsNoTracking() ajuda isso não acontecer). Depois quando você tentava adicionar ele, você estava fazendo novamente o track desse objeto, logo fazia duas vezes, isso não pode acontecer.
O problema com o IQueryable é que ele constroi uma árvore de expressões da consulta no banco, enquanto você não chamar o .Execute() ou fazer a conversão, ele não fez a consulta dos valores.
Você estava fazendo o dispose (ação de liberar a conexão com o banco) antes do IQueryable realmente ser executado e trazer o resultado da consulta, logo quando você tentar retornar ele, ele vai ver que a conexão com o banco foi liberada e  o erro acontecer.


How to create a menu navigation on a Views page that uses contextual filters?

Question: I have a projects content type and I want there to be a menu for each project that would have Project Overview, Project Details & Team Members.
So in Views I created a page at projects/ which would be the overview page that filters based on project title.
Then I have a page at projects/%/details, and another at projects/%/people.
So how would I either create a menu that I could put in the sidebar or somewhere that would work for any project, or maybe use tabs instead? Whichever is fine, but if you could teach me how to do both that would be cool.
I tried using the menu settings under Page Settings in Views, but I couldn't get it to work.
Answer: Open the view where you had created the pages at projects/%/details or projects/%/people.
Under page settings where you had the path filled, add these additional settings to create a Menu tab or a Contextual link.
Go to Menu and select Menu tab as the type and fill in the title. If you want the link to be present as a contextual link, check the box which says context.
You can also set access permissions on who can see this tab depending upon the permission type you had selected.


I'm a singer struggling with tempo and time

Question: I'm a singer with a decent voice and technique, I also used to play the violin so I can read classical sheet music and sight-read pretty well. However, I've always struggled with counting.
I have no problem when I sing or play in a choir or orchestra, if I know a song well I can sing along with no problem, but singing solo with no sheet music to look at is always a challenge.
I'm a visual learner, I memorize things in pictures, so if I have classical(treble clef) sheet music to look at I can memorize the piece by visualising the tempo and remembering the notes that comes before I have to start singing, it also makes it easier for me to hear the notes and count when I have a visual idea. When there's no sheet music however, I can get a sense on when to sing and a good idea of the tempo by feel but tend to start singing either a few seconds too soon or a few seconds too late. Currently I'm trying to learn a song, there's no sheet music for it so I have to rely purely on my ear, I know when to start and stop, but often goes off beat in the middle. I can sing along with the original version with perfect ease, when I sing on my own with just the melody it sounds good, but as soon as I match my recording with the original I hear myself going off beat either starting too early or too late.
Here's the original version:

My recording:
https://drive.google.com/file/d/1YkVsJPwYgKvJblAhyXRVT8QDv8B6HE4m/view?usp=drivesdk
Sound pretty good right? Until I put it with the original:
https://drive.google.com/file/d/1HV--Hxq6TlaylZUKv9_e-eTG0Jmyl3NS/view?usp=drivesdk
As you can see I get a good sense of when to sing, except I either start off good but goes off beat in the middle, or I start or stop a few seconds too soon or too late.
Would really appreciate some advice on what to do.
Comment: Does this answer your question? [I am a singer who has problems with tempo](https://music.stackexchange.com/questions/30051/i-am-a-singer-who-has-problems-with-tempo)
Comment: If you listen to only the background music, with no singer, can you accurately walk to the beat? If yes, can you sit and clap to the beat?
Comment: Other questions that address this kind of problem: [what can someone who have challenges singing along with beat do?](https://music.stackexchange.com/q/36331/70803); [I am a singer who has problems with keeping rhythm and beat](https://music.stackexchange.com/q/58794/70803); [How to learn to keep time while singing?](https://music.stackexchange.com/q/57696/70803).
Comment: Finding it very difficult to understand what's actually happening in the second recording. If you panned the backing to one side, and you to the other, it'd be easier to determine.
Comment: @Tim The second recording is just me singing the song, not sure what you mean by it's difficult to understand what's happening.
Answer: I would suggest some counting exercises that should help with feeling the down beat.

Turn on a metronome on a phone, and set it to a very slow tempo—something like 50bpm. For about 20 seconds, count the beats along with the metronome. Without stopping the metronome, mute your phone, and continue counting each beat in your mind. After about 30 seconds, turn up the volume on your phone, and see if you are still in sync with the metronome. If you are still in sync, increase the amount of time the metronome is muted. If you're out of sync, this exercise should help you determine if you are naturally too fast or too slow.

Try the same exercise again, but this time replace the metronome with the song you're learning. Instead of counting the beat, count the first beat of every measure.

Lastly, I would try it again, but instead of counting, sing along with the original recording. Try to mute the song while you keep singing, and see how long you can stay on beat.
Answer: If the song has a constant tempo you can easily set a metronome and sing with it going, or tap your foot to the time.  However, if the song doesn't have a constant tempo because it is being played live, then it is liable that one of the instruments, at least, is being played along as the singer sings.  This technique means that the instrument and the singer and reading each other (or the instrument following the singer).  in this case it may be best to sing with the present singer, recording each little phrase at a time, practicing the small sections, and recording, as you go, when u get each one right.  However, with timing, tapping your foot is very often the answer, when you can get use to doing that as you perform.
Answer: Overall the recording is not terribly bad. When interpreting a song typically your goal isn't to replicate the original performance (well, unless you really want to study someone's individual style), so small differences are normal.
It seems to me that in several places you start your phrases too early. It's worth to note that later you come back on track and fix it. This makes me think that you don't have a problem with feeling the beat, but rather with understanding the rhythm in these particular places. The rhythm is syncopated and I imagine it might be confusing.
Two ways to fix it: one would be to sing these places with the original recording, trying to replicate that rhythm. Second, perhaps giving you a better understanding of what's going on, would be to count the exact rhythm in the recording, and then count it in your head while singing.
It may help you to speak the words, or even some meaningless syllables (like "la la la"), or just tap the rhythm with your hands, so that you can focus on it entirely, without being bothered with vocal technique.


Apache LIMIT directive does not allow to see localhost project over LAN

Question: I want to allow to see my localhost project over the LAN using Apache LIMIT directive in .htaccess
my localhost project URL is http://220.127.116.11/myproject
below is the .htaccess part which cause problem
<Limit POST PUT DELETE>
 order deny,allow
 deny from all
 allow from 192.168.0.0/255
 Satisfy any
</Limit>

but it gives error

Server error!
The server encountered an internal error and was unable to complete
  your request. Either the server is overloaded or there was an error in
  a CGI script.
Error 500
192.168.0.123   Apache/2.4.10 (Unix) OpenSSL/1.0.1i PHP/5.5.15 mod_perl/2.0.8-dev Perl/v5.16.3

my error_log is

[Fri Dec 26 11:18:36.183915 2014] [core:alert] [pid 4752] [client
  192.168.0.123:38795] /opt/lampp/htdocs/myproject/.htaccess: The specified network mask is invalid.

my work around

If I set allow from 192.168.0.123  it works only for my IP not over LAN
If I set allow from 192.168.0-5.0-255 then it works fine (expected)
but only the main page is coming, after login it gives Access forbidden!403

whereas it was advised to use / on this blog and many other SO answers
Does this (/ to -) changed into apache 2.4 ?
someone kindly explain the differences of these and proper valid syntax, I didn't find it on Apache documentation.

another issue
When add GET in LIMIT option
<Limit GET POST PUT DELETE>
 order deny,allow
 deny from all
 allow from 192.168.0.0-255
</Limit>

then it gives error everywhere

Access forbidden!
You don't have permission to access the requested directory. There is
  either no index document or the directory is read-protected.
Error 403 Access forbidden!

errro_log is

[Fri Dec 26 11:34:05.840880 2014] [access_compat:error] [pid 4752]
  [client 192.168.0.123:39012] AH01797: client denied by server
  configuration: /opt/lampp/htdocs/myproject/
Answer: I got the solution from this article
change the line
allow from 192.168.0.0-255
to
allow from 192.168.0.2/255.255.0.0

will lock Apache down to my internal LAN i.e. address range
  192.168.0.2 to 192.168.0.255 only with subnet mask of 255.255.0.0

and it works with GET also, here is my final .htaccess
<Limit GET POST PUT DELETE>
 Order deny,allow
 Deny from all
 Allow from 127.0.0.1 ::1
 Allow from 192.168.0.2/255.255.0.0
</Limit>

Answer: The satisfy directive is intended to combine multiple requirements i.e. both from your subnet and a valid-user .
Leave that option out and you should have a more valid  configuration.
Also it is better to use your apache configuration file rather than .htaccess files.
Comment: already checked with removal of `satisfy` but error remains. And do not have access to Apache log on server that's why I used it on `.htaccess`


Programmatic imageview and picasso

Question: I'm fairly new to Android development but I have the following problem. I am trying to create several ImageViews programmatically and use Picasso to load the image and I stumbled on the following problem.
EDIT: What I am trying to achieve is I want the ImageView to be created with width=FILL_PARENT and height=WRAP_CONTENT
See the code extracts below:
This example works but is not what I want (loads the images)
LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
ImageView articleTitleImageView = (ImageView) findViewById(R.id.articleTitleImageView);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300,300);
params.gravity= Gravity.CENTER_HORIZONTAL;
[...]
ImageView iv = new ImageView(this);
setImage(iv, imageURL);
articleBodyLL.addView(iv, params);
[...]
private void setImage(final ImageView imageView, final String imgURL) {
Picasso.with(ArticleProvider.getContext())
.load(imgURL)
.fit().centerCrop()
.error(R.drawable.default_image)
.into(imageView);
}

This example does not work (images are not shown)
LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
ImageView articleTitleImageView = (ImageView) findViewById(R.id.articleTitleImageView);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity= Gravity.CENTER_HORIZONTAL;
[...]
ImageView iv = new ImageView(this);
setImage(iv, imageURL);
articleBodyLL.addView(iv, params);
[...]
private void setImage(final ImageView imageView, final String imgURL) {
Picasso.with(ArticleProvider.getContext())
.load(imgURL)
.fit().centerCrop()
.error(R.drawable.default_image)
.into(imageView);
}

Comment: what is the problem exactly that you are facing?
Comment: Is there a reason you want to use the version that does not work, or is this just curiosity about why it doesn't work?
Comment: The problem is that the image is not shown at all.What I am trying to do is  for the image to be loaded and fill the parent and not just be shown as a fixed size.
Answer: Take a look at this code. this works fine. A suggestion is that if you are trying to form some kind of list take a look at RecyclerView to avoid Exceptions(many exceptions :p).
LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity= Gravity.CENTER_HORIZONTAL;
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
setImage(iv, "http://square.github.io/picasso/static/sample.png");
                  articleBodyLL.addView(iv, params);

        //////////////////////////////////////////////
    private void setImage(final ImageView imageView, final String imgURL) {
        Picasso.with(this)
            .load(imgURL)
            .error(R.mipmap.ic_launcher)
            .into(new Target() {
              @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Log.e("loaded", "onBitmapLoaded: loaded" );
                imageView.setImageBitmap(bitmap);
                imageView.invalidate();
              }

              @Override public void onBitmapFailed(Drawable errorDrawable) {
                Log.e("loaded", "onBitmapFailed: load failed" );
              }

              @Override public void onPrepareLoad(Drawable placeHolderDrawable) {

              }
            });
      }

Answer:     myLinearLayout = new LinearLayout(this);
    myLinearLayout.setOrientation(LinearLayout.VERTICAL);

      for (int z = 0; z < zCont.length; z++) {
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
                params.gravity= Gravity.LEFT;//CENTER_HORIZONTAL
                params.setMargins(-20, 0, 0, -10);
                ImageView iv = new ImageView(this);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                setImage(iv, "http://sait.ru/fotota/rua.jpeg");
               myLinearLayout.addView(iv, params);
        }

    private void setImage(final ImageView imageView, final String imgURL) {
                Picasso.with(this)
                        .load(imgURL)
                        .fit().centerCrop()
                        .error(R.mipmap.ic_launcher)
                        .into(imageView);
            }

Programmatic imageview and picasso


"Arrays = Pointers" *mind blown*. Many years later: "Actually, they don't" *mind blown again*

Question: Context:
I programmed in C on and off for about 2 years before discovering that a[i] is just syntax sugar for *(a + i) and was therefore equivalent to *(i + a) and i[a]. My reality was turned upside down and many a "AHA!" revelationary moment followed in the following few days of study and reading up ("So THAT's why arrays are always passed by reference!" etc). Since then I've internalised the pointer/array equivalence and held it close to my heart, so imagine what a rude shock it was when I stumbled upon this thing called "Array decay". Here's the typical example:
Code:
#include <stdio.h>

int Length(int*);

int main () {
  int arr[100];
  printf("Length of array: %d\n",(int)(sizeof(arr)/sizeof(arr[0])));
  printf("Length of array: %d\n",Length(arr));
  return 0;
}

int Length(int arr[]) {
   return sizeof(arr)/sizeof(arr[0]);
}

Result:
Length of array: 100
Length of array: 2

Question:
So it turns out that C has some recognition of arrays after all! In main where the array was declared, the program is able to correctly report on it's size. Now I'm wondering just how much of array syntax is only syntax sugar for pointer operations (previously I had assumed: All of it). C actually does have arrays, what are their limitations? The example shows that it is possible to get their length as long as you're in the same function, what other cool stuff can you do? How far can you go before this decay thing kicks in?
Comment: Syntax error in title: Surely that should be "Arrays == Pointers"?
Comment: Try passing `int arr[10][10]` as an argument to a function ;)
Comment: BTW, `int* p = NULL; p = p;` vs. `int a[1]; a = a;` is one of many examples that show that arrays and pointers aren't equivalent.
Comment: Does http://en.wikipedia.org/wiki/Sizeof#Using_sizeof_with_arrays not answer this?
Comment: The C FAQ has a whole section about this stuff - have you read it?
Comment: SO is not a blog site. Please read other questions here to see the preferred style and content.
Comment: http://stackoverflow.com/help/dont-ask
Answer: There are two operators in "old" C language that do not trigger array type decay: sizeof operator and unary & operator. sizeof evaluates to the size of the entire array (not to pointer size), while & returns a pointer of pointer-to-array type (not of pointer-to-pointer type). C99 added _Alignof, as Eric noted in the comments.
One more context is mentioned sometimes as well: initialization of char array with string literal (i.e. string literal does not decay to pointer).
One can also put it that way: in object contexts (AKA lvalue contexts) arrays retain their "arrayness", while in value contexts (AKA rvalue contexts) they immediately decay to pointers.
P.S. As a historical remark: one of the ancestors of C language - B language - did actually implement arrays as physical pointers, meaning that each array in B was actually a pointer pointing to an independently allocated memory block. Originally it was assumed that this implementation will carry over to C as well. However, C had to have struct types. And B-style arrays created unnecessary complications with having arrays as members of struct objects. They would've made initialization of struct objects non-trivial, struct object would become non-copyable by raw memcpy etc. This was deemed unacceptable in C. So, arrays were redesigned into their current form. C arrays are not pointers, but they still emulate the pointer-like behavior of their grandparents from B language, which often confuses people learning C.
(See here http://cm.bell-labs.com/cm/cs/who/dmr/chist.html for the full story.)
Comment: @Jim Balter: That's not true. The language explicitly states that string literal is an unnamed object of `char [N]` type with static storage duration (where `N` is the number of characters between the `""` plus 1).
Comment: @Jim Balter: You simply show that the term "string literal" is used to refer to a *lexical element*. However, the term has never been restricted to that usage only. The static array object created in response to that lexical element is also formally referred to as "string literal". 6.5.1/4 clearly states that "A string literal is a primary expression. It is an lvalue with type as detailed in 6.4.5.".
Comment: @Jim Balter: Absolutely not, again. You are trying to impose an arbitrary restriction on the scope of the term "string literal". A restriction that clearly does not exist in the language specification. As I quoted above, 6.5.1/4 states that string literal is an object.
Comment: @Jim Balter: "... but a string literal used to initialize a char array is not such an lvalue ..." - you will have to substantiate this statement by something. At this point it is completely baseless. Quite the opposite, 6.5.1 does not make any exceptions. A string literal is such an lvalue.
Comment: @Jim Balter: Needless to add, the non-decaying contexts I provided in my answer above are a direct quote from 220.127.116.11/3, which lists the same three contexts :)
Comment: If it's needless then don't do it.
Answer: The size of an array is "lost" when it is passed to a function.  As you point out, sizeof, being a compile-time thing, sees the "real" size.  This can work because sizeof is not a function at all, as you can demonstrate by using it without parentheses (e.g. sizeof arr, though bizarrely sizeof some_type is not legal C).
Comment: `sizeof` isn't necessarily compile-time, too.  VLAs work properly, for example.
Comment: That's not bizarre ... sizeof expr is straightforward to parse whereas sizeof type is not, e.g., `sizeof long int`
Answer: Saying that arrays and pointers are "equivalent" means neither that they are identical nor even interchangeable. What it means is that it's pointer arithmetic and array indexing that are equivalent in C, pointers and arrays are different.
A reference to an object of type array-of-T which appears in an expression decays into a pointer to its first element; the type of the resultant pointer is pointer-to-T.  That is, whenever an array appears in an expression, the compiler implicitly generates a pointer to the array's first element, just as if the programmer had written &a[0].
sizeof or & operator are the exceptions to this rule.
Also, I recommend the book Expert C Programming, which uses a whole chapter to explain the difference and confusions about pointers and arrays.
Answer: Declaring an array as a local or global variable is where it differs from pointers. int arr[100]; allocates 400 bytes of space, whereas int *p only allocates 4. You can use an int *p local variable similarly to an array if you malloc some space for it, like
int *p = (int *)malloc(100 * sizeof(int));

You also have to remember to free that memory later, of course. You can also feel free to pass a local variable that was declared as int arr[100] to a function whose formal parameter has type int *. When it comes to function arguments, arrays and pointers are a little more equivalent.
i[a]

No, that won't work, if i is an int. But the other three forms are equivalent.
Comment: `i[a]` does work, for `i` an integer and `a` an array or pointer.
Comment: "No, that won't work, if i is an int" -- Of course it will, and the OP told you why. Beyond that, this "answer" has nothing to do with the OP's question ... -1.


Users can post new node but ONLY Unpublished status

Question: As the title says, users are able to create new node (type QUESTION), but they can not publish it. The node is saved when the user hits save, but the status is set to unpublished under Admin > Content.
I have checked a few permissions the authenticated user which has:

Question: Create new content
Question: Edit own content
View published content
View own unpublished content

This content is NOT using workflow moderation.
Answer: The obvious thing is that the "published" option is unticked on the content type. So if you go to "structure > content types > question" (/admin/structure/types/manage/question) and then click "Publishing option" is the published ticked? That controls the default status
If its not that then you must have some other module/code doing it. Without knowing your sites setup I dont think people can help much further
Comment: Leigh...thanks for the quick reply. That was it. Now I am laughing at myself.


On order of $5$ dozen boxes of a product, a retailer receives extra dozen free. What is the equivalent discount for offer?

Question: On an order of $5$ dozen boxes of a consumer product, a retailer receives an extra dozen free. This is equivalent to allowing him a discount of:

$15\%$
$\frac{97}{6}\%$
$\frac{50}{3}\%$
$20\%$
Answer: So, for every 5 dozen he orders, he gets 1 dozen free. This is equivalent of paying for only $\frac{5}{6}$ of your order, therefore, $\frac{1}{6}$ discount.
To convert this to percentage we multiply by 100 to get $\frac{1}{6} \times 100 = \frac{50}{3}$.
So the answer is 3.


Designing my first database schema: suggestion needed

Question: This is my first database schema design. I am trying to develop a small web application for my department which will be used for food cost management. And I am doing this for my learning purpose.
How the food cost management works in my department:

Total members: 15
One admin to keep record of all the cost. he will update the database on a daily basis.
Each member can order only once a day. If anyone has guest on any specific day he can order multiple number of meal.
Usually members pay their bill for a week or two in advance.
one or two persons are responsible for bringing the food from outside and they don't  need to pay for their lunch. Transportation cost is also given to them. their food cost+ transportation cost is distributed equally to other 15 members expenses.

Database queries:
From admin perspective:

he will manage/add the daily order. (Table: orders)
he will add the payments for all the members which will be credited against respective member's "Balance" (Table: payments)
he will be able to see an overview of all members' order/cost history and their current balance in a chart for one month at a time.
If any member has negative balance or less than a specific amount of money, it will be notified to admin dashboard.

From member perspective:

he will be able to see his current balance and order/cost history for last one month at a time.
he will be able to see last x number of payment history he made.

Based on the queries I mentioned above I tried to design a database schema which looks like the diagram below:

Elaboration of some attributes:
EPlatenum: Number of extra plate of food brought besides number of plate ordered.
Eplatecost: cost for extra plate of food. this cost is distributed equally among 15members individual cost.
EPersonnum & EPersoncost: Number of extra person involved in bringing the food and their total cost. the cost will be distributed equally among 15members individual cost.
TransCost: transportation cost. the cost will be distributed equally among 15members individual cost.
Questions:

what are the mistakes I have made and how can I overcome them?
For my DailyList table I have used "date" as the primary key.Is it OK to use date as primary key? IF not OK, what can be the primary key here instead?
when I am going to populate a chart overview for 30 months cost/order history the database query will be huge I assume. what approach should I take to optimize the query?

I am looking forward to getting your suggestions on improving the database schema. Please help me correcting my design mistakes and overcome them. Thank you for your patience.
Comment: From quickly looking at your schema, you should **never** store money as float as they have limited precision and may not be accurate (e.g 0.99 instead of 1). I would suggest changing the data type of any column that stores money as DECIMAL or NUMERIC as they are fixed point numbers.
Answer: My first impression:

I think payment should be related to order (because user pays for specific order).
I don't know what DailyList is, but if there may be more than two with the same date (and as I can image it may be) you shouldn't use it as a primari key.
Password should be encoded with e.g. SHA (so varchar 15 is to less).
Comment: OK, so that is fine. Another clue, do not use "float" for prices. You should use decimal format (just a good practice, because of floating point precision problems).
Comment: 2. Daily list is actually DailyCostList for other expenses i.e number of extra persons and total cost for their food, number of extra plate of food and their cost are included here. there will be one record for each date and not more than that.
Comment: So it's perfectly fine to be a primary key
Comment: 1. Payments are paid in advance for one week or two. These amount will be added to their respective balance field in "user" table. for tracking individual meal cost there is one attribute "OrderCost" in "orders" table


Find certain character and substring in Objective-C

Question: I have a string..
NSString* string = @"%B999999^PDVS123456789012^PADILLA L.                    ^0X0000399           ?*;999999554749123456789012=00X990300000?*

What I want is to get the name PADILLA L. and 999999554749123456789012=00X990300000?*
Answer: Use NSString componentsSeparatedByString: to split the string up. First use @"^". The name will be at index 2. Then split the substring at index 3 using @";". The string at index 1 will give you the 2nd piece you want.
NSArray *substrings = [string componentsSeparatedByString:@"^"];
NSString *name = substrings[2];
name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *lastpart = substrings[3];
NSArray *moresubstrings = [lastpart componentsSeparatedByString:@";"];
NSString *secondPiece = moresubstrings[1];

Answer: Without more specifics here is a brute force way:
NSString* string = @"%B999999^PDVS123456789012^PADILLA L.                    ^0X0000399           ?*;999999554749123456789012=00X990300000?*";
NSRange nameRange = {26, 10};
NSString *name = [string substringWithRange:nameRange];
NSRange numRange = {80, 39};
NSString *num = [string substringWithRange:numRange];

The documentation is your friend: NSString Class Reference
Comment: Keep in mind that this solution is only valid if the data is guaranteed to be fixed length.
Comment: yes. exactly. I mean I appreciate your answer but hardcoding the range would not be very wise. But nevertheless thank you for your answer. :)
Answer: Without knowing what the exact input pattern is (we have your n-of-1 example only), it's going to hard to say exactly how you might parse this properly; but NSRegularExpression offers what you need (in addition to other suggested approaches):
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSString *sampleText = @"%B999999^PDVS123456789012^PADILLA L.                    ^0X0000399           ?*;999999554749123456789012=00X990300000?*";
        NSError *regexError = nil;
        NSRegularExpressionOptions options = 0;
        NSString *pattern = @"^%\\w+\\^\\w+\\^([A-Za-z\\s]+\\.).+\\?\\*\\;(.+)\\?\\*$";
        NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:&regexError];

        NSTextCheckingResult *match = [expression firstMatchInString:sampleText options:0 range:range];
        if( match ) {
            NSRange nameRange = [match rangeAtIndex:1];
            NSRange numberRange = [match rangeAtIndex:2];

            printf("name = %s ",[[sampleText substringWithRange:nameRange] UTF8String]);
            printf("number = %s\n",[[sampleText substringWithRange:numberRange] UTF8String]);
        }
    }
}

This little Foundation application prints the following to the console:
name = PADILLA L. number = 999999554749123456789012=00X990300000

The regex used to analyze the input string may need to be tweaked depending on how the input string varies.  Right now it is (unescaped):
^%\w+\^\w+\^([A-Za-z\s]+\.).+\?\*\;(.+)\?\*$


$S^1 \times S^1$ is homeomorphic to torus

Question: The question is asking to show $S^1 \times S^1$ is homeomorphic to a torus. I have read some other posts in here but most of them are proving it with "lattice" which I haven't learn. Here is what I did, write down a function $f: T/\sim \text{}\rightarrow S^1 \times S^1$
where $T= [0,1] \times [0,1]/\sim$ whit relation $(0,a)\sim(1,a)$, $(b,0)\sim(b,1)$ for $a,b \in [0,1]$
and
$$f(x,y)=(\cos(2\pi x),\sin(2\pi x),\cos(2\pi y),\sin(2\pi y))$$
And I wish to show that $f$ is a homeomorphism. (Recall from lecture, I need to show $f$ is a continuous bijection with continuous inverse $f^{-1}$.)
How do I show $f$ is a bijection and what is $f^{-1}$? Is that $f^{-1}(x,u,y,v)=(\mid \frac{1}{2\pi}\arccos(x)\mid,\mid \frac{1}{2\pi}\arccos(y)\mid)$
Comment: The problem is that $\arccos$ picks a single value of amulti-valued function. In particular, it never picks a value in $[\pi,2\pi]$.
Comment: Far better, therefore, is to use "atan2", a slight generalization of arctan: for $x > 0$, $atan2(x, y) = arctan(y/x)$, and for other quadrants, it differs from $arctan(y/x)$ by a constant. It's discontinuous on the non-positive $x$ axis. You can recover $x$ from $(p,q,r,s)$ by $x = atan2(q, p)$, and simmilarly $y = atan2(s, r)$.
Comment: Note that since the torus is compact and $S^1 \times S^1$ is Hausdorf, you actually only need to show that $f$ is a continuous bijection; the rest is [automatic](https://proofwiki.org/wiki/Continuous_Bijection_from_Compact_to_Hausdorff_is_Homeomorphism).
Answer: For what it's worth, I probably wouldn't use the Cartesian coordinates for $S^1$, but a polar coordinate,
$$f(x,y) = (2\pi x, 2\pi y)  \mod 2\pi$$
Then the inverse is slightly easier, $f^{-1}(\alpha, \beta) = (\alpha/2\pi, \beta/2\pi)$
Comment: isn't $f(x,y)=(1,2\pi x,1,2\pi y)$, since $f:T/\sim$ $\to S^1 \times S^1$.
Comment: I don't understand the $1$ and the image having three ordinates. My thinking is that $S^1 \times S^1$ has two ordinates.
Comment: $S^1 \times S^1 \subset \mathbb{R}^4$, so I expect the image has 4 components. Am I wrong ?
Comment: Six of one, half a dozen of another. If you have a definition of $S^1 \subset \mathbb{R}^2$ without other homeomorphic representations, stick with it. If that is the case, my solution is perhaps a bit of a 'cheat' as it de facto uses $[0, 1]/\sim  \ \cong S^1$.


Is it safe not to close an Environment or EntityStore?

Question: I want to ask if it's safe not to close an environment?
<code>    final PersistentEntityStore entityStore = manager.getPersistentEntityStore(xodusRoot, instance);
    final List<User> users = new LinkedList<>();
    try {

    } finally {
       //entityStore.close
    }
</code>
The reason behind not closing the environment is that this example code here is used in a Servlet environment in which we implemented a sort of Sigleton lookup table (map) to hold the Environments and EntiyStores and if we close it the next HTTP POST request will get a "Environment already closed" error, thus we don't close it.
And the reason we implemented the Lookup table (map) here is to prevent the servlet requests from getting Database lock issues, especially on multiple concurrent requests.
Is this safe to do? Or is this even the correct approach?
Answer: Generally, it's safe not to close an Environment or EntityStore. In most cases not closed database will be opened without data loss if JVM exits. In worst case, the database would recover to most recent valid snapshot like it does after system/hardware failures. However not closed database can consume some additional physical space (GC would be affected) which results in a worse performance. You can close all Environments/EntityStores in the lookup table on destroying your servlet.


Explicit image of elements in completion of $\mathbb{Q}(i)$

Question: Let $K = \mathbb{Q}(i)$ and consider a rational prime $p$ such that $p$ splits in $\mathcal{O}_K = \mathbb{Z}[i]$. We then now that if $K_p = K \otimes \mathbb{Q}_p$, we have $K_p \cong \frac{\mathbb{Q}_p[X]}{(X^2+1)} \cong \mathbb{Q}_p \times \mathbb{Q}_p$. My question is if there is any way to know the explicit image of elements in $K_p$ under this isomorphism. For example, if $p = \pi \overline{\pi}$, what would $\pi$ be as an element of $\mathbb{Q}_p \times \mathbb{Q}_p$?
Answer: Let $c$ be a square root of $-1$ in $\Bbb{Q}_p$
Then the map $$\Bbb{Q}(i) \to\Bbb{Q}_p\times\Bbb{Q}_p$$ is
$$a+ib\mapsto (a+bc, a-bc)$$
Any element of $\Bbb{Q}(i) \otimes_\Bbb{Q} \mathbb{Q}_p$ is of the form $1\otimes a+i\otimes b$ with $a,b\in \Bbb{Q}_p$ and the map $\Bbb{Q}(i) \otimes_\Bbb{Q} \mathbb{Q}_p\to\Bbb{Q}_p\times\Bbb{Q}_p$
stays $1\otimes a+i\otimes b\mapsto (a+bc, a-bc)$.


Space in IE7 due to h1 tag

Question: In IE7, there is an extra spacing created between the question and the options, but only for the first question. If I remove the
 title, the gap disappears. It doesn't happen in IE8. What is the cause and how do I make it work in IE7?
<!DOCTYPE HTML>

Survey

1)

Question 1:

            <input type="radio">Option 1

            <input type="radio">Option 2

            <input type="radio">Option 3

            <input type="radio">Option 4

2)

Question 2:

            <input type="radio">Option 1

            <input type="radio">Option 2

            <input type="radio">Option 3

            <input type="radio">Option 4

Answer: put this style:
h1{
margin:0;
padding:0;
}

Note: You are using html5 DOCTYPE. HTML5 was not supporting lower version ie.
Comment: The HTML5 doctype is irrelevant here.
Comment: Ok, it is the margin (specifically, the margin-bottom). Have to set margin to 0 and use padding for the spacing. This works for my case, but out of curiosity, what should I do if I cannot set the margin to 0 for any reason? Tried a bit with line-height as suggested on the other post, but it doesn't seem to work.
Answer: It's floating that causes the problem. Remove float:left from the declarations for .questionText.
Comment: I see, this is probably a more accurate answer. Should I just think of of it as IE7 bug, then? What if I want to use `float:right` there?
Answer: Reset your styles on the h1, it's probably line-height pushing it down.
h1 {
line-height:0;
margin:0;
padding:0;
}

I'd suggest using a reset stylesheet as it will save you debugging headaches down the road
http://meyerweb.com/eric/tools/css/reset/
Answer: Reset your styles on h1. Just like this
h1 {
  padding: 0;
  margin: 0;
  display: block;
  clear: both;
}

I think it might help you. Just try it.
Comment: When you say line-height: 0, am I supposed to really set it to 0, or can I set it some other value? Setting it to 0 really messed up the layout. Am I missing something?
Comment: just remove the line-height: 0 and check it.Other thing will be the same.

Space in IE7 due to h1 tag


Ruby function list file recursively

Question: i need a recursive function to list files in a folder:
def procdir(dirname)
  data = ''
  Dir.foreach(dirname) do |dir|
    dirpath = dirname + '/' + dir
    if File.directory?(dirpath) then
      if dir != '.' && dir != '..' then
        #puts "DIRECTORY: #{dirpath}" ;
        procdir(dirpath)
      end
    else
      data += dirpath
    end
  end
  return data
end

but the result: is null
Comment: possible duplicate of [One-liner to Recursively List Directories in Ruby?](http://stackoverflow.com/questions/2370702/one-liner-to-recursively-list-directories-in-ruby)
Comment: Could you tell me the filesystem? Does `dirname` contains multiple directories itself within it?
Answer: Stdlib Dir#glob recurses when you give it the ** glob.
def procdir(dir)
  Dir[ File.join(dir, '**', '*') ].reject { |p| File.directory? p }
end

Comment: Thank for your responses, i understand my problem.

dbenhur, your code is great!

here is my code if it can help someone

    def procdir(dir)
      Dir[ File.join(dir, '**', '*') ].reject { |p| File.directory? p }
    end

    file = procdir('mypath')
    #puts file
    file.each do |filename|
    #puts filename
    test = filename.scan(/SomeRegex/).flatten
    puts test
    (..)
    end

Thank you all
Comment: Nice this is exactly what I was looking for
Answer: Use the find module:
require 'find'

pathes = []
Find.find('.') do |path|
  pathes << path unless FileTest.directory?(path)
end

puts pathes.inspect

Answer: Old thread but perhaps someone might find it useful:
array_of_all_files = Dir
  .glob("**/*")
  .reject { |file_path| File.directory? file_path }
Comment: Why did you repeat an answer nearly identical to the one I [posted eight months earlier](http://stackoverflow.com/a/15503079/1074296)? [`Dir::[]`](http://ruby-doc.org/core-2.0/Dir.html#method-c-5B-5D) is the same as `Dir.glob`. `File.join('**', '*')` is a more portable way to say `"**/*"`.
Comment: @dbenhur: I agree that it can be a problem when using those paths with other programs. But `File.join` doesn't change anything : `File.join("a","b")` is `"a/b"`, even on Windows.
Comment: I am sorry, I didn't know they were identical. And I felt this was more readable (probably, since I used it a bunch of times and never knew another representation of it).
Comment: @dbenhur : Just curious, why would `File.join('**', '*')` be more portable than `"**/*"`. It works on Linux/Windows/MacOs as far as I know.
Comment: @EricDuminil Because there are more operating systems than that.  [`File::join`](https://ruby-doc.org/core-2.2.0/File.html#method-c-join) will join on `File::SEPARATOR` and not assume the underlying OS understands `/`.
Comment: @dbenhur do you have any concrete example where `/` wouldn't work?
Comment: @EricDuminil In the context of `Dir.glob`, slash will always work because the ruby lib is doing the actual globbing.  It's a bad habit to get into though if you want your ruby to be broadly portable. In DOSish systems (Windows), the OS calls usually understand either \ or / but not every program does, so you may construct file paths which will not be understood in that system. Basically, any non-POSIX OS may give you trouble if you assume `File::SEPARATOR == '/'`
Answer: It looks like there are a couple of problems with the recursion:

The else clause appears to associated with the wrong if.  It needs to be associated with the first if.
The result of the recursive procdir call should be added to data.

If you indent the code a little more cleanly, it would probably be easier to spot problems like that.  The following contains the two fixes:
def procdir(dirname)
  data = ''
  Dir.foreach(dirname) do |dir|
    dirpath = dirname + '/' + dir
    if File.directory?(dirpath) then
      if dir != '.' && dir != '..' then
        #puts "DIRECTORY: #{dirpath}" ;
        data += procdir(dirpath)
      end
    else
      data += dirpath
    end
  end
  return data
end

Comment: Thank for your responses, i understand my problem.
Answer: If you know the file extensions you will have just use this:
Dir[Rails.root.join('config/locales/**/*.{rb,yml}')]

Ruby function list file recursively


Saving an captured image to the local folder

Question: I am taking pictures and would like to save them  according to the time they were exactly taken.
I would also like to create a folder named /pictures in the current directory and save the pictures in that folder. This is done in C# & WPF.
This is my code:
Image newimage = new Image();
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();

newimage.Source = Capture(true) // Take picture

myBitmapImage.UriSource = new Uri(@"c:\" +
           string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + ".jpg");
// Gives error: Could not find file 'c:\2013-05-26_04-40-25-AM.jpg'

myBitmapImage.EndInit();
newimage.Source = myBitmapImage;

newstackPanel.Children.Add(newimage);

Results in:
ERROR   Could not find file 'c:\2013-05-26_04-44-59-AM.jpg'.
Why is it trying to find a file VS just saving the file on the c:\ drive?
Comment: It's the other way around, but have a look at http://www.codeproject.com/Questions/313384/Convert-image-to-Bitmap-Image-in-WPF-in-Csharp . It may help.
Comment: Thanks, I looked at that already but I still don't get how to fix the error.
Comment: What about `var newimage = new BitmapImage(...` (remove your 1st line)
Comment: @xterminal0 update question with full code how you get image and how you save image
Comment: @xterminal0 Please don't drastically change your question. The original question was about how to save an image to disk which you have answers to. If you have a new question, please create a new one instead of overwriting this. People looking at this question now will be confused because the question and answers doesn't match.
Comment: @xterminal0 I went ahead and reverted back to an earlier state. I'll be happy to help you with your other question if you create it as a new question (you can even put a link to it here)
Answer: If all you want to do is to save the image to disk, then you should use the BitmapEncoder class
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
var image = Capture(true); // Take picture
encoder.Frames.Add(BitmapFrame.Create(image));

// Save the file to disk
var filename = String.Format("...");
using (var stream = new FileStream(filename, FileMode.Create))
{
  encoder.Save(stream);
}

The above example creates a JPEG image, but you any encoder you want - WFP comes with Png, Tiff, Gif, Bmp and Wmp encoders built in.
Comment: +1, but as OP obviously wants to write a JPEG image, why not just write the sample code straightforward with JpegBitmapEncoder?
Comment: It may also be a bit confusing why the declarations of `encoder` and `image` are inside the using block, but `filename` is outside. I guess it would be easier to understand if only the Save call would be there.
Comment: I get the cannot convert from 'System.Windows.Controls.Image' to 'System.Uri'
Comment: @xterminal0 Why arent't you doing it as shown in this answer? Instead you assign the captured image to the `Source` property of an Image control. Are you also showing the image in your UI? If not, there is no need at all for an Image control. Anyway, if you assign to `newimage.Source`, you should also pass that to BitmapFrame.Create: `encoder.Frames.Add(BitmapFrame.Create(newimage.Source));`
Comment: @Clemens: (re: where variables are declared) Well, filename obviously *has* to be outside but I agree about the others.. I've updated my answer
Comment: @IsakSavo Yes of course, that's what I meant. Thanks for editing.


One Wordpress install (multisite) or multiple installs?

Question: I manage a server for a client who has several Wordpress blogs. They all precariously balance on PHP/FastCGI/nginx and it all works at the moment, just using a little more RAM than I'd normally be comfortable with.
Since setting this all up, Wordpress 3 came out and (with a plugin to maintain domain mapping) allows me to import all the blogs into one central blog. So I know I can achieve a desirable operating outcome... I'm just not sure if I want to sink hours into doing it.
The client now wants to add a couple more blogs to the server. We're clearly at a crossroads where it would make sense to act now if I'm going to go down the multisite road.
I don't really care about the clear administrative benefits rather the performance and the amount of free RAM.
Do you think I would be correct in assuming one codebase in RAM would cost less than having half-a-dozen single sites? Are there any other performance pros (or cons) that I'm missing?
Answer: The short answer is you are better off going with a single Wordpress 3 install rather than maintaining separate databases, servers, configs, etc. for the sites individually. The key piece of information to understand here is that Wordpress 3 contains most of the core code that runs the multi-million site/blog wordpress.com, minus some obvious mass-scaling optimizations.
The only challenge you may run into in the future is if one of your sites wants to branch off / go somewhere else - you will need to define a migration process (which ultimately should not be that difficult :) ).
Comment: that challenge is easy to fix: don't let them leave! j/k :)
Answer: I'm not sure how you would save system resources assuming your databases are still separate ones for each site.
I would do it anyway being it only for improved usability and less maintenance windows.
Answer: 1) Yes
2) Simply determine whether the benefit of saving some RAM is worth the man-hours of conversion you'll be doing. Potential downtime, data loss, etc. are all things to watch out for. Would it be cheaper to just add more RAM?
Answer: I doubt you'd be saving much on memory, if any. It's not as if there are three or five persistent wordpress processes constantly running on the server. Sure nginx and mysql are running, but the extra threads are only started once browser requests are made and scripts start calling functions and making database calls.
If you want to save resources you should be more concerned with the wordpress theme and plugins the client is running. Many free themes and plugins make a lot of unnecessary database calls. I personally am of the school of thought that it's best to 'hard code' as much as possible into the theme as it's not really hard coding at all, it's just PHP and easily editable. Also do look into cacheing (wp super cache), and a PHP accelerator.
I have several wordpress sites running on the same VPS and haven't bothered to combine them together. They don't all use the same plugins so I am able to save there (I think - I haven't checked to see if you can enable/disable plugins per site in 3.0), and I like to hope that if one gets hacked, the others are still somewhat isolated due to different DB credentials.
If the additional ease of management isn't a draw for you or your client, I don't see the benefits.
Answer: If you are using PHP in FastCGI, with a different cgi pool for security reason: yes, you will save a bunch of ram.
If you are using PHP in FastCGI with a single pool, you will probably only benefits in performances if you are using some opcode cacher like APC.
Concerning security, most attacks are done regardless of DB credentials, so it's probably superfluous. If someone gives away his own password, the problem is elsewhere.


Piano chords with an octave in them

Question: I rarely see people playing chords on the piano the way I learned in school, but they more often play chords with an octave in them.
For example, instead of playing C major as C E G, they play it something like C G C.
Can someone explain the reason for this?
I can't find those chords when checking chord inversions.
Comment: @phoog - yes, l.h. I  quite often play C-G-E, but that's maybe a different story than playing just C-G-C - at least there's an M3 in there.
Comment: Well, the main reason to play chords like that, at least in music without chord symbols, is that the sheet music literally has those chords on it (e.g. Bar 1, Beat 1.0 actually has C-G-C in quarter notes sharing a stem in the left hand). **Somehow, I don't think this is what you're looking for.**
Comment: Can't believe it's a true statement. Maybe left hand, but generally, piano players will omit the G out of CEG in favour of CE (or maybe CEC). Main reason is that doubling *something* always makes a chord sound fuller.
Comment: @Tim but people commonly play CEGC, which could be a source of confusion.
Comment: @Tim Are you thinking of certain genres of piano playing? Classical and romantic piano works are replete with octaves on the left hand and four note chords on the right hand where the top note is an octave above the lowest right-hand note. I'm not able right now to think of a classical or romantic piano work that I've worked on in years that doesn't have a lot of octaves.
Comment: I had always heard that you should avoid closed for triads to far in the bass under the name of "Avoid muddy voicings".
Answer: Chords on the piano are frequently distributed between both hands. While one hand is playing C-G-C, the expected E is played by the other hand.

Complicating matters, the E in the "other" hand might not occur simultaneously with the rest of the chord; nevertheless, it's still considered part of the chord.

With piano music, always remember to consider both hands when analyzing/interpreting chord.
Answer:
I can't find those chords when checking chord inversions.

Theoretically speaking, the inversion is determined by the bass note played by the left hand or by a bass instrument.  So if you have C/E on a lead sheet, it doesn't much matter how you play the pitches with your right hand.  The term for the various possibilities in the right hand is usually voicing rather than inversion.
And in fact, in the classical style, a major triad in the first inversion, such as C/E on a lead sheet, usually falls under the rule that you don't double the third.  This means that only the bass instruments (or the keyboard player's left hand or the organist's feet) play E.  Everyone else, including keyboard players' right hands, plays only C and G.  This is one possible explanation for the phenomenon you have observed, though it's a more likely explanation for some musical styles than for others.
Just to drive the point home a bit, as long as you're playing C in the bass, your C major chord is in root position regardless of where the right hand is playing E and G and, optionally, doubling the C.  (As Tim notes in a comment, it's fairly unexceptional to omit the fifth as well.)
<code>X: 1
M: C
L: 1/2
K: C
%%staves {1 2}
V:1 clef=treble
[EG] [Ge] |[CGe] [CEG] |[CEGc] [EGce] |[Gceg] [Gce] |[E2G2c2]|]
V:2 clef=bass
C, C, |C, C, |C, C, |C, C, |C,2|]
</code>
Answer: The "great" composers of the Baroque, Classical, and Romantic eras frequently wrote such chords into their piano compositions. One excellent example is the "Promenade" from Pictures at an Exhibition, by Modest Mussorgsky (public domain excerpt):

Right on the first line, we see the left hand is playing mostly in octaves. By the third line, both hands are almost entirely playing either octaves or chords containing octaves.
The reason for writing and playing chords like this is for the sound and sonority of these chord voicings (a voicing is a particular selection of which notes of a chord to play and which notes to double and which octaves to play the notes in).
In the first line of this excerpt, we can see that the melody starts as single notes and then the melody is repeated, but in the repetition, the melody is accompanied by right hand chords and a left hand bass line. This makes the difference between chords and single notes completely obvious. What is less obvious, but becomes clear if you listen to the piece, is that the more notes we add to a piano chord, the "bigger" it sounds. So we can take our music from small and quiet single notes all the way to large and majestic four (or five!) note chords in both hands.
The piano composers of the last four hundred years knew this and used variations in chord voicings constantly throughout their works. Today, piano players in pop, rock, and jazz also understand this and often use "big" chord voicings.
The reasons why big voicings are almost always bracketed by octaves is twofold. First, octaves are a comfortable distance apart on the piano to be played by the thumb and fifth finger of almost every pianist. Second, octaves have a sound that effectively accentuates either the top melody notes or the bass line without sounding muddy or unclear. Some musical theatre piano parts have baselines that are entirely or almost entirely octaves. It's a very effective and popular sound.
If you prefer a non-classical example, "You'll Be Back" from Hamilton has a gradual change from chords without octaves, to octave bassline, to chords with octaves and octave bassline for the big ending.
Answer: In textbooks, chords tend to look like this.

It's a bit of an exaggeration to say they're rarely voiced like that in real music, but there are certainly lots of other possibilities!
What you (hopefully) won't find too much is this sort of 'melody in the right hand, block chords in the left hand' thing.  It might be a simple way of indicating the harmonies in a textbook, but it sounds muddy.

Piano chords with an octave in them


Acessar nested JSON com AngularJS

Question: Tenho um arquivo .json e preciso listar os itens dele da seguinte forma.

Empresa 1

Valor 1

Empresa 1

Valor 2

Empresa 2

Valor 1

Empresa 2

Valor 2

Abaixo segue a estrutura do meu arquivo .json
{
"market": {
    "company": [
        {
            "name": "Petrobras",
            "logo": "https://s29.postimg.org/lnt4mtp2f/petrobras.png",
            "stock": [
                {
                    "name": "PETR4",
                    "openingvalue": "22.45",
                    "actualvalue": "22.54"
                },
                {
                    "name": "PETR3",
                    "openingvalue": "28.10",
                    "actualvalue": "28.05"
                }
            ]
        },
        {
            "name": "VALE",
            "logo": "https://s29.postimg.org/u8mgdzz8n/vale.png",
            "stock": [
                {
                    "name": "VALE4",
                    "openingvalue": "17.65",
                    "actualvalue": "17.32"
                },
                {
                    "name": "VALE3",
                    "openingvalue": "21.11",
                    "actualvalue": "21.32"
                }
            ]
        },
        {
            "name": "ITAU",
            "logo": "https://s29.postimg.org/jul61dxk7/itau.png",
            "stock": [
                {
                    "name": "ITUB4",
                    "openingvalue": "8.7",
                    "actualvalue": "8.89"
                },
                {
                    "name": "ITUB3",
                    "openingvalue": "12.73",
                    "actualvalue": "12.91"
                }
            ]
        },
        {
            "name": "BRADESCO",
            "logo": "https://s29.postimg.org/58u5d50rr/bradesco.png",
            "stock": [
                {
                    "name": "BBDC4",
                    "openingvalue": "6.29",
                    "actualvalue": "6.08"
                },
                {
                    "name": "BBDC3",
                    "openingvalue": "8.37",
                    "actualvalue": "8.42"
                }
            ]
        },
        {
            "name": "AMBEV",
            "logo": "https://s29.postimg.org/tmsfkrxuv/ambev.png",
            "stock": [
                {
                    "name": "ABEV4",
                    "openingvalue": "7.65",
                    "actualvalue": "7.43"
                },
                {
                    "name": "ABEV3",
                    "openingvalue": "9.78",
                    "actualvalue": "10.02"
                }
            ]
        },
        {
            "name": "OI",
            "logo": "https://s29.postimg.org/ejbbdsht3/oi.png",
            "stock": [
                {
                    "name": "OIBR4",
                    "openingvalue": "3.94",
                    "actualvalue": "3.67"
                },
                {
                    "name": "OIBR3",
                    "openingvalue": "5.09",
                    "actualvalue": "5.01"
                }
            ]
        },
        {
            "name": "GOL",
            "logo": "https://s29.postimg.org/8478k04rr/gol.png",
            "stock": [
                {
                    "name": "GOLL4",
                    "openingvalue": "11.26",
                    "actualvalue": "11.07"
                },
                {
                    "name": "GOLL3",
                    "openingvalue": "16.70",
                    "actualvalue": "16.93"
                }
            ]
        },
        {
            "name": "AMERICANAS",
            "logo": "https://s29.postimg.org/69ue29hrb/americanas.png",
            "stock": [
                {
                    "name": "LAME4",
                    "openingvalue": "1.85",
                    "actualvalue": "1.88"
                },
                {
                    "name": "LAME3",
                    "openingvalue": "2.57",
                    "actualvalue": "2.59"
                }
            ]
        },
        {
            "name": "SMILES",
            "logo": "https://s29.postimg.org/hfyce2nmv/smiles.png",
            "stock": [
                {
                    "name": "SMLE4",
                    "openingvalue": "15.33",
                    "actualvalue": "15.12"
                },
                {
                    "name": "SMLE3",
                    "openingvalue": "18.64",
                    "actualvalue": "18.78"
                }
            ]
        }
    ]
  }
}

Abaixo segue a estrutura do meu HTML
<uib-accordion close-others="oneAtATime">

      <uib-accordion-heading>

          {{lista.name}} - {{subLista.name}}

          {{isOpen ? 'Ocultar' : 'Ver'}} detalhes da ação

      </uib-accordion-heading>

          Abertura: {{subLista.openingvalue}}

          Atual: {{subLista.actualvalue}}

          <button type="submit" class="btn btn-default pull-right" ng-click="$ctrl.open('md')">Vender</button>

  </uib-accordion>

Da forma como eu fiz os 2 valores de cada empresa estão aparecendo dentro dessa empresa, da seguinte forma.

Empresa 1

Valor 1
Valor 2

Preciso fazer com que o nome da empresa repita e com os valores diferentes.
Answer: Na verdade o seu código tem um erro relacionado a essa tag:

    <button type="submit" class="btn btn-default pull-right" ng-click="$ctrl.open('md')">Vender</button>

que ng-controller="ModalController as $ctrl", por algum motivo não foi mencionado na pergunta. Retirando essa parte, funcionou, sendo que o resto está praticamente correto.
Vejo o código rodando logo abaixo:

var app = angular.module('app', [])
  .controller('ctrl', ['$scope',
    function($scope) {

      $scope.main = {
        listas: {
          "market": {
            "company": [{
              "name": "Petrobras",
              "logo": "https://s29.postimg.org/lnt4mtp2f/petrobras.png",
              "stock": [{
                "name": "PETR4",
                "openingvalue": "22.45",
                "actualvalue": "22.54"
              }, {
                "name": "PETR3",
                "openingvalue": "28.10",
                "actualvalue": "28.05"
              }]
            }, {
              "name": "VALE",
              "logo": "https://s29.postimg.org/u8mgdzz8n/vale.png",
              "stock": [{
                "name": "VALE4",
                "openingvalue": "17.65",
                "actualvalue": "17.32"
              }, {
                "name": "VALE3",
                "openingvalue": "21.11",
                "actualvalue": "21.32"
              }]
            }, {
              "name": "ITAU",
              "logo": "https://s29.postimg.org/jul61dxk7/itau.png",
              "stock": [{
                "name": "ITUB4",
                "openingvalue": "8.7",
                "actualvalue": "8.89"
              }, {
                "name": "ITUB3",
                "openingvalue": "12.73",
                "actualvalue": "12.91"
              }]
            }, {
              "name": "BRADESCO",
              "logo": "https://s29.postimg.org/58u5d50rr/bradesco.png",
              "stock": [{
                "name": "BBDC4",
                "openingvalue": "6.29",
                "actualvalue": "6.08"
              }, {
                "name": "BBDC3",
                "openingvalue": "8.37",
                "actualvalue": "8.42"
              }]
            }, {
              "name": "AMBEV",
              "logo": "https://s29.postimg.org/tmsfkrxuv/ambev.png",
              "stock": [{
                "name": "ABEV4",
                "openingvalue": "7.65",
                "actualvalue": "7.43"
              }, {
                "name": "ABEV3",
                "openingvalue": "9.78",
                "actualvalue": "10.02"
              }]
            }, {
              "name": "OI",
              "logo": "https://s29.postimg.org/ejbbdsht3/oi.png",
              "stock": [{
                "name": "OIBR4",
                "openingvalue": "3.94",
                "actualvalue": "3.67"
              }, {
                "name": "OIBR3",
                "openingvalue": "5.09",
                "actualvalue": "5.01"
              }]
            }, {
              "name": "GOL",
              "logo": "https://s29.postimg.org/8478k04rr/gol.png",
              "stock": [{
                "name": "GOLL4",
                "openingvalue": "11.26",
                "actualvalue": "11.07"
              }, {
                "name": "GOLL3",
                "openingvalue": "16.70",
                "actualvalue": "16.93"
              }]
            }, {
              "name": "AMERICANAS",
              "logo": "https://s29.postimg.org/69ue29hrb/americanas.png",
              "stock": [{
                "name": "LAME4",
                "openingvalue": "1.85",
                "actualvalue": "1.88"
              }, {
                "name": "LAME3",
                "openingvalue": "2.57",
                "actualvalue": "2.59"
              }]
            }, {
              "name": "SMILES",
              "logo": "https://s29.postimg.org/hfyce2nmv/smiles.png",
              "stock": [{
                "name": "SMLE4",
                "openingvalue": "15.33",
                "actualvalue": "15.12"
              }, {
                "name": "SMLE3",
                "openingvalue": "18.64",
                "actualvalue": "18.78"
              }]
            }]
          }
        }
      };
    }
  ]);

  <uib-accordion close-others="oneAtATime">

        <uib-accordion-heading>

            {{lista.name}} - {{subLista.name}}

            {{isOpen ? 'Ocultar' : 'Ver'}} detalhes da ação

        </uib-accordion-heading>

            Abertura: {{subLista.openingvalue}}

            Atual: {{subLista.actualvalue}}

            <button type="submit" class="btn btn-default pull-right" ng-click="$ctrl.open('md')">Vender</button>

  </uib-accordion>

Possar ser a falta da imprementação do controller ModalController que esteja faltando no seu código, ou falta da inclusão do javascript que contenha esse código.

Acessar nested JSON com AngularJS


The convolution of functions in the Schwartz Space lies in the Schwartz Space

Question: I'm reading Fourier Analysis by Rami Shakarchi and Elia.M.Stein. When I started reading the chapter about Fourier Transform on R I came across very difficult inequalities. One of them take me a long time to prove it. Now I am with one of these. I have tried a lot of things like triangule inequality, Newton's Binomial, etc. I would appreciate some help. The problem is the following:
In the context of prooving that the convolution of two functions in the Schwartz Space lies again in the Schwartz Space it is neccesary to demonstrate that if a function $g$ belongs to the space then the following inequality holds:
$$|x|^l |g(x-y)| \leq A_l(1 + |y|)^l \ \forall \ l \geq 0$$ Remember, $S(\mathbb{R})$, the Schwartz Space, is the set of functions $f$ such that $sup |x|^l|f^{(k)}(x)| < \infty \ \forall \ k,l$
The book gives a hint, it says that consider the cases $|x|> 2|y|$ and $|x|<2|y|$.
Thanks
Comment: In addition to the direct inequality in the answer below, the fact that Fourier transform converts convolution to multiplication (under various mild hypotheses), and the somewhat easier (?) assertion that _products_ of Schwartz functions are Schwartz...
Comment: Yeah but for prove the fact that Fourier maps convolutions to multiplication you need to show before that te convolution lies in S (R).
Comment: well, there are many possible logical lines here, for sure, but just showing that the convolution is in $L^1$ is sufficient for existence of Fourier transform, etc. Anyway, yes, _some_ inequalities must be proven...
Answer: Recall the following trivial inequality;
$$\lvert x\rvert ^{l} \leq \left(\, \lvert x-y \rvert \, + \lvert y \rvert \, \right)^{l}\leq (2\max(\, \lvert x-y\rvert, \, \lvert y \rvert \, )\, )^{l} \leq\,  2^{l} \, \lvert x-y\rvert^{l} + 2^{l}\,  \lvert y \rvert ^{l} \qquad  \forall l\geq 0$$
Set $$C_{l} := \sup_{x\in\mathbb{R} } \, \lvert x\lvert ^{l} \,\lvert g(x) \, \rvert <\infty \qquad \forall l\geq 0$$
Now using the above estimate, we get $$\lvert x \rvert^{l} \, \lvert g(x-y) \rvert \leq 2^{l} \, \lvert x-y\rvert^{l} \, \rvert g(x-y)\rvert + 2^{l}\,  \lvert y \rvert^{l} \, \lvert g(x-y) \rvert \leq \\ 2^{l}\, C_{l}+ 2^{l} \, C_{0} \, \lvert y \rvert^{l} \leq \underbrace{2^{l}(C_{l}+C_{0})}_{=A_{l}}\, (1+\lvert y\rvert)^{l}$$
This establishes the desired inequality. To finish off the proof entirely we may write $$ \lvert x \rvert^{l} \, \lvert (g\ast f)(x) \rvert \leq \int _{\mathbb{R}} \lvert x \rvert^{l} \, \lvert g(x-y) \rvert \, \lvert f(y) \rvert \, dy \leq A_{l} \int_{\mathbb{R}} (1+\lvert y \rvert )^{l+2} \, \lvert f(y) \rvert \frac{dy}{(1+\lvert y \rvert)^{2}} \leq \\ A_{l} \, C_{l+2} \,\int_{\mathbb{R}} \frac{dy}{(1+\lvert y \rvert)^{2}}< \infty $$
Since the bound is independent of $x\in \mathbb{R}$, the claim now follows.
Comment: Ooooh! I get it!!!
Comment: I am not too sure about some of the inequalities.
Comment: Firstable, thanks for the help. I do not understand why $(2 max (|x-y|,|y|)^l \leq 2^l |x-y|^l + 2^l |y|^l$.