How to export QTable to .csv?

Question: How can I export values from a QTableWidget to .csv file or Excel file?
The program should collect values of three variables from a PLC. This PLC belongs to my company and have functions to do this collect.
Inserting items to QTableWidget .cpp:
void MainWindow::on_pushInsert_clicked()
{
/*
the program already is connected to plc,
so I just have to choose the address inside of the plc.
*/
    WORD wAddress = 50001;
    WORD value1 = 0;
    WORD value2 = 0;
    WORD value3 = 0;
    CollectVariables(wAddress,wValue);
    int ID = 0;
    string Name = "";
    int Age = 0;
    QTableWidget *table = ui->tableWidget;
    for(i=0;i<10; i++) {
        //id
        CollectVariables(wAddress+i, value1);
        table->setItem(i, 0, new QTableWidgetItem(value1));

        //name
        CollectVariables(wAddress+10+i, value2);
        table->setItem(i, 1, new QTableWidgetItem(value2));

        //age
        CollectVariables(wAddress+20+i, value3);
        table->setItem(i, 2, new QTableWidgetItem(value3));
        tabela->selectRow(i);
    }
}

Comment: The simplest way is to create a csv file. Excel will read this.
Comment: Here is a code example: [https://stackoverflow.com/questions/4487799/export-data-from-qtablewidget-to-csv](https://stackoverflow.com/questions/4487799/export-data-from-qtablewidget-to-csv)
Comment: Another option would be to create a tab-separated text and write this into the [QClipboard](https://doc.qt.io/qt-5/qclipboard.html). (With only one column per row like exposed in the sample code, there is in fact no tab to write but only `\n` for the end of each row.)
Comment: Ok dear @drescherjm, but how can I do this?
Answer: The way I used to "export" QTableWidget to .csv file (I can't export do excel) was to store the value of each space on the table to an array while inserting items to the table.
QFile was used to create the .csv file and QTextStream to insert values on it.
To improve the code I created a button to select the directory where this .csv file should be save.
Select Directory .cpp:
void MainWindow::on_pushSelectDir_clicked()
{
    QFileDialog directory;
    ui->lineEditDir->setText(directory.getSaveFileName(this,"Choose an directory"));
    dir_name = ui->lineEditDir->text();
}

Create .csv file .cpp:
void MainWindow::on_pushExportCSV_clicked()
{
    QFile data(dir_name+".csv");
    if (data.open(QFile::WriteOnly | QIODevice::Append)) {
     }
    QTextStream output(&data);
    output <<"ID"<<","<<"Name"<<","<<"Age"<< '\n';
    for(i=0;i<10; i++) {
        output << ID[i] <<","<< Name[i] <<","<< Age[i] << '\n';
    }
    data.close();
}

How to export QTable to .csv?


Merge an object and $this in PHP

Question: My problem in short is " I want to make a language system and I want to access to the phrases like this $language->fields->username->admin, so I tried to do that by different ways, but I  can't merge a array to the object, I meaning I want to convert an array to an object and add this object that will return to the language object.
class Language
{
   public function __construct(array $array)
   {
       $this += (object) $array;
   }
}

Answer: You can't do that via a simple operator. You need to foreach over the array to assign the properties.
function makeObjectRecursively($array) {
    if (!is_array($array)) {
        return $array;
    }

    foreach ($array as $k => &$v) {
        $v = makeObjectRecursively($v);
    }
    return (object) $array;
}

foreach ($array as $k => $v) {
    $this->$k = makeObjectRecursively($v);
}

Comment: @user3625938 then you need to make the array recursively an object? See my updated answer.
Answer: What you describe sounds a bit like a RecursiveArrayObject:
class Language extends RecursiveArrayObject
{
    public function __construct(array $array)
    {
        parent::__construct($array, ArrayObject::ARRAY_AS_PROPS);
    }
}

$data = ['fields' => ['username' => ['admin' => 'ADMINv']]];

$language = new Language($data);

echo $language->fields->username->admin, "\n"; # prints "ADMINv"

That RecursiveArrayObject is a more concrete form of the ArrayObject:
class RecursiveArrayObject extends ArrayObject
{
    public function __construct(Array $array, $flags = 0, $iterator_class = "ArrayIterator")
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = new static($value, $flags, $iterator_class);
            }
            $this->offsetSet($key, $value);
        }
        $this->setFlags($flags);
        $this->setIteratorClass($iterator_class);
    }
}

Comment: That is what I want. Thanks ^_^

Merge an object and $this in PHP


Large file uploads stop immediately, 404 error

Question: I am having a weird problem with uploading large files in the Drupal admin's file field. I have the size limit set to 500 MB. I also have the php.ini settings for upload size, post size, and memory all set to 500 MB.
When I upload a smaller file like 50 MB everything works perfectly. If I upload a larger file such as 250 MB then the upload fails immediately and I get a 404 error in the Network tab of the Chrome inspector.
The 404 error is on this URL: http://example.com/file/ajax/field_video_file/und/0/form-tpohUDjq_v0b7OcNhtnQl2TaRc5UcFl9zwJQzI3mlwE
The server is running IIS 7.5.
Any ideas what could be causing this?
Thanks!
Comment: can you replicate this on your localhost? with php 5.3, you can use .htaccess to override the system ini settings. This way, it will be specific to your site. These are the two links should help you with it. On your local host, try with unlimited memory_limit by setting it to -1. [http://php.net/manual/en/ini.core.php] [http://php.net/manual/en/configuration.changes.modes.php]
Comment: .htaccess doesn't work on IIS ;)
Comment: I faced similar issue with nginx. Hope this thread helps someone.

https://www.techpond.in/solved-drupal-cannot-upload-large-files
Answer: From: https://www.drupal.org/node/97193

Drupal's limits on upload file size are determined by your server's
  PHP settings (as well as Drupal specified settings that can be set at
  Admin > Site Configuration > File Upload). The default values for PHP
  will restrict you to a maximum 2 MB upload file size.
On the settings page for the upload module, Drupal calculates and
  displays the maximum file size that you can set based upon two PHP
  settings: 'post_max_size' and 'upload_max_filesize'. Since
  'post_max_size' is the limit for all the content of your post, many
  people choose 'post_max_size' to be a multiple of
  'upload_max_filesize' to allow multiple files to be uploaded, but this
  is not essential. The upload module limits the size of a single
  attachment to be less than either post_max_size, or
  upload_max_filesize, whichever is smaller. The default PHP values are
  2 MB for upload_max_filesize, and 8 MB for post_max_size.
Depending on your host, changing these two PHP variables can be done
  in a number of places with the most likely being php.ini or .htaccess
  (depending on your hosting situation).
For example, to increase the limit on uploaded files to 10 MB:
<code>Add the below to the relevant php.ini file (recommended, if you have access). Note that for some hosts this is a system-wide setting.
</code>
However, for hosts running PHP as a CGI script with suexec (for
  example) you may be able to put these directives in a php.ini file in
  your Drupal root directory.
          upload_max_filesize = 10M
          post_max_size = 10M
      Add the below to your .htaccess file in your Drupal root directory.
          php_value upload_max_filesize 10M
          php_value post_max_size 10M
The PHP documentation states that the memory_limit setting also
  affects file uploading. Generally speaking, memory_limit should be
  larger than post_max_size. If this is an issue, see the page on how to
  Increase memory available to PHP (3 methods)
Drupal also allows/enforces its own size limits, independently of what
  PHP allows. These are found in Drupal 6 at "Administer » Site
  configuration » File uploads" ( /admin/settings/uploads ). In Drupal 7
  size limit is controlled on per-field basis. The Drupal settings
  cannot be larger than those permitted by PHP, but may be smaller if
  you haven't updated them, so remember to check there also, after
  updating the php.ini.

Also, make sure your permissions are set correctly from your public/private folders you've set Drupal for file handling. The folders are located at /admin/config/media/file-system
Comment: Thanks, that took me in a good direction. Now the file appears to upload the whole way, instead of stopping immediately, but now I get a 500 error when the upload is finished and the file does not get placed on the server. I wish I could figure out a way to get more details on that 500 error :(
Comment: Check your permissions.
Comment: I'll modify my answer to include of some the content from the article and some issues that may help in a few minutes.
Comment: I'm having the exact issue.  IIS Server with Drupal 7.  Everything worked fine but recently I started getting the 500 error once the upload completes.  We were having network issues and now that those are resolved, I cannot even get the upload to start.  I immediately get the 404 error for form-...


Índices desnecessários no banco são um problema?

Question: Costuma-se adicionar índices para melhorar o desempenho das consultas. Porém normalmente não se recomenda sair adicionando índices em tudo quanto é coluna, apenas onde se identificar a necessidade.
Por que dessa recomendação? Que tipo de problemas índices desnecessários podem causar?
Answer: Basicamente é porque cada novo índice exige mais tempo para atualizar o banco em qualquer alteração que afete estes índices. Já vi gente sugerir fazer índices para tudo. Com apenas 6 ou 7 campos, para todas as combinações são necessários dezenas para centenas de índices e todos precisariam ser atualizados mesmo que altere apenas um campo. O tempo gasto pode afetar a escalabilidade do banco.
Em alguns casos a consulta pode ser prejudicada também. O espaço ocupado prejudicará o cache dos dados/índices que realmente são importantes. Além disto acessar primeiro o índice para depois acessar o dado tem um custo e ele pode ser maior que acessar os dados diretamente em certos padrões. E nem sempre o otimizador do sistema detecta corretamente se ele deve fazer o acesso direto.
Da mesma forma as recomendações automáticas dos sistemas SGDBs para criar índices nem sempre são corretas.
Além disto cada novo índice é um recurso a mais para dar manutenção. Viola o YAGNI. Inclusive dificulta upgrades no modelo de uma base de dados no sistema em produção.
Já vi "especialistas conceituados" dizerem que o ideal é criar índice para tudo e ir tirando os que não precisam. Não consigo imaginar como isto possa fazer sentido. É o pior caso de otimização prematura que já vi. Toda otimização deve ser criada quando você mediu e ficou claro que ela é necessária. Índice existe fundamentalmente para otimizar acesso aos dados.
Os sistemas de banco de dados mais completos possuem muitos recursos para obter as informações necessárias para a decisão correta. Estas informações podem ajudar a identificar índices desnecessários também. E como é um recurso para otimizar é preciso revisar com frequência, o que pode ser bom em um momento pode não ser mais no futuro.
Um exemplo típico de erro em criação de índice é quando ele é usado exclusivamente para geração de relatórios esporádicos. A perda para gerar um relatório esporádico sem a otimização do índice costuma causar menos prejuízo que o índice causará no sistema como um todo.
Mas um dos piores exageros que já vi, e acontece muito, é criar um índice para colA+colB e outro para colA. O primeiro pode ser usado para obter a mesma otimização que o segundo provê, tornando-o desnecessário.
Mas algo que preciso ressaltar sempre: medir é o mais importante. Eu e mesmo profissionais bem mais experientes que eu no assunto vivem tendo surpresas. O que parece ajudar muitas vezes prejudica mais.
Boa referência.

Para evitar entendimento errado da outra resposta (que foi removida mas acho que a informação ainda é relevante) pelas pessoas que estão aprendendo sobre o assunto vou colocar alguns pontos:

A perda de performance causada pela criação de índices desnecessários se dá em qualquer operação que altere um dado contido nas chaves do índice. Não importa se é INSERT, UPDATE e até mesmo DELETE dependendo da implementação. Alterações que não afetam a chave do índice não causam problemas de performance. Em sistemas de banco de dados que usam alguma forma de MVCC qualquer alteração acaba afetando pelo menos o índice da chave primária (que talvez seja clusterizado) já que o dado é copiado para outro local.

A performance do SELECT também pode ser afetada negativamente conforme citado acima na minha resposta. Não ocorre com frequência, principalmente porque o planejador costuma evitar o uso do índice nestes casos, mas pode.

Já a criação do índice beneficia qualquer operação de acesso aos dados que o planejador do banco de dados identifique que seja útil. Normalmente isto ocorre em comparações do WHERE mas não em qualquer comparação (isto é importante). Há casos que o índice não ajuda. Índice não é mágico, ele tem uma organização que otimizam algumas relações, não todas. Ocorre também quando se usa ORDER BY, JOIN e em quando há uso de algumas funções agregadoras. Mas é bom ficar claro que só uma medição pode garantir que haverá ganho. É claro que a experiência pode fazer o desenvolvedor do banco de dados identificar casos simples, mas é preciso ter cuidado. O bom nadador costuma se arriscar e morrer afogado mais que o nadador que tem medo de água desconhecida. Regras gerais, como sempre, podem causar mais mal do que bem. Sempre tem que analisar o caso específico com informações específicas para o caso.
Exemplos onde o índice provavelmente não vai ajudar: WHERE colA = colB / 2 ou WHERE colA LIKE '%Silva%'.

De qualquer forma o ganho ocorre em qualquer das operações de acesso aos dados que tenha algum uso das cláusulas acima. Claro que em UPDATE e DELETE apenas o WHERE e o ORDER BY é relevante.

Está cheio de mitos em desenvolvimento de software e como consequência temos muitos softwares com problemas porque há a leitura de informações ilusórias sobre os assuntos. Deixar margem para entendimento errado causa mais mal do que bem.
Coloquei no GitHub para referência futura.
Comment: Queria entender os negativos. O que tem errado na resposta?
Comment: deve ser alguém com preguiça de ler...
Comment: @bigown Temos dois criadores de indices desnecessários no site (devem ser do pessoal das _boas práticas_ :D )
Comment: Para relatórios que usam muitos `where`'s seria interessante usar algum software de indexação como o ElasticSearch para buscar por exemplo, nome, email, telefone, data inicial, data final. Então pegar os IDs desses documentos (que são os IDs no banco de dados) e posteriormente fazer uma consulta passando somente estes IDs usando `WHERE id IN (1,2,3,7,9,N...)` ? http://pt.stackoverflow.com/questions/77529/usando-elasticsearch-para-fazer-buscas-complexas-e-depois-pegar-os-ids-para-cons
Comment: @bigown Sua citação "um índice para `colA+colB` e outro para `colA`", pelo menos para `Postgresql` vale para o `WHERE colA = 1 AND colB=2` mas não para `WHERE colA = 1 OR colB=2`, no segundo caso o índice criado separadamente para `colA` será usado.
(primeira linha do link)
https://www.postgresql.org/docs/9.1/static/indexes-bitmap-scans.html
No mais, muito boa resposta. +1
Comment: @TiagoOliveiradeFreitas alguns banco de dados fazem algumas otimizações extras mesmo.


UMP for $U(0,\theta)$ (simple x simple hypothesis)

Question: Let $X_1,...,X_n $ be iid $U(0,\theta)$. Find the UMP to test $H_0: \theta = \theta_0$ versus $H_1: \theta=\theta_1$, for $\theta_1 < \theta_0.$ Obtain the power of the test.
My attempt:
We know that $X_{(n)}$ is sufficient for $\theta$ and its distribution is
$$f(x;\theta)=\frac{nx^{n-1}}{\theta^n}I_{(0, \theta)}(x)$$
So, by the Neyman-Person lemma we must have a critical region with the form
$$\{ x; \frac{I_{(0,\theta_0)}(x)}{I_{(0,\theta_1)}(x)}\frac{\theta_1^n}{\theta_0^n} \leq c \}$$
For $0<c<1$
But I can't write it in a better form. What should I do now?
Thanks in advance!
Answer: UMP test is not unique here.
Since the pdf $f$ has monotone likelihood ratio (MLR) in $X_{(n)}$, by Karlin-Rubin theorem a UMP size $\alpha$ test for testing $H_0:\theta=\theta_0$ against $H_1:\theta<\theta_0$ is
$$\phi_0(x_1,\ldots,x_n)=\begin{cases}1&,\text{ if }x_{(n)}<\theta_0\alpha^{1/n} \\ 0&,\text{ otherwise }\end{cases}$$
Now whenever $\theta_1<\theta_0$, we have $$\frac{f_{\theta_1}(x_1,\ldots,x_n)}{f_{\theta_0}(x_1,\ldots,x_n)}=\begin{cases}\left(\frac{\theta_0}{\theta_1}\right)^n &,\text{ if }0<x_{(n)}\le \theta_1 \\ 0&,\text{ if }\theta_1<x_{(n)}\le \theta_0\end{cases}$$
So by NP lemma, a most powerful level $\alpha$ test $H_0$ against $H_1:\theta=\theta_1(<\theta_0)$ is of the form
$$\phi^*=\begin{cases}0 &,\text{ if }\theta_1<x_{(n)}\le \theta_0 \\\text{any value in }[0,1]&,\text{ otherwise }\end{cases}$$
such that $E_{\theta_0}\phi^*=\alpha$.
This yields a non-randomized MP test for $H_0$ versus $H_1:\theta<\theta_0$, namely
$$
\phi_1(x_1,\ldots,x_n)=\begin{cases}0&,\text{ if }\theta_1<x_{(n)}\le \theta_0 \\ 0 &,\text{ if }\theta_0\alpha^{1/n}<x_{(n)}\le \theta_1 \\ 1 &,\text{ otherwise }\end{cases}
$$
The corresponding UMP test is
$$\phi_1(x_1,\ldots,x_n)=\begin{cases}0&,\text{ if }\theta_0\alpha^{1/n}<x_{(n)}\le \theta_0 \\ 1&,\text{ otherwise }\end{cases}$$
Also see Most powerful test of simple vs. simple in $\mathrm{Unif}[0, \theta]$.
Comment: It is a test function (or simply a test); $\phi=1$ indicates rejection of null hypothesis and $\phi=0$ indicates non-rejection.
Comment: Could you please explain the meaning of the $\phi$ or $\phi^*$ notation? My book doesn't use that notation, and I'm finding it extraordinarily confusing.
Comment: Ok, thanks! Appreciate the extra clarity.
Comment: Sorry, another question: can you please elaborate on how the $\alpha^{1/n}$ arises in the intervals for your $\phi_1$ expressions? Is that simply to enforce $E_{\theta_0}(\phi^*)=\alpha?$ Thanks!
Comment: How do you know that $\theta_0\alpha^{1/n}<\theta_1?$ Wouldn't you just want to say that $\phi_a=1$ when $x_{(n)}\le\min(\theta_0\alpha^{1/n},\theta_1)?$
Answer: The likelihood-ratio (LR) test is not terribly useful in this situation.  Your test can be simplified from your specified critical region by looking at possible regions in which the maximum value can fall.  From the ordering in your critical region, it is clear that the p-value function for your test is:
$$p(\boldsymbol{x}) = \begin{cases}
\text{undefined} & & & \text{for } \theta_0 < x_{(n)}, \\
1 & & & \text{for } \theta_1 < x_{(n)} \leqslant \theta_0, \\
(\theta_1 / \theta_0)^n & & & \text{for } 0 \leqslant x_{(n)} \leqslant \theta_1. \\
\end{cases}$$
(In the case where $\theta_0 < x_{(n)}$ both hypotheses are falsified by the data, and your LR statistic is undefined, leading to an undefined p-value.)
We can see that, for any significance level $\alpha < (\theta_1 / \theta_0)^n$ the likelihood-ratio test accepts the null hypothesis under all possible observed outcomes (and is trivially UMP).  For any significance level $\alpha > (\theta_1 / \theta_0)^n$, the test rejects the null if and only if $x_{(n)} \leqslant \theta_1$ (and it is again trivially UMP).
The problem with the LR test in this situation is that the LR is either zero or one, and does not have any gradations inside the range $0 \leqslant x_{(n)} \leqslant \theta_1$.  This leads to a test with a binary p-value.

A better test to apply here (which does not satisfy the conditions of the Neyman-Pearson lemma, but is also UMP) is to impose an additional evidentiary ordering within the range $0 \leqslant x_{(n)} \leqslant \theta_1$ so that smaller values of $x_{(n)}$ are considered to be greater evidence for the alternative hypothesis.  If we add this additional ordering we obtain the smoother p-value function:
$$p(\boldsymbol{x}) = \begin{cases}
\text{undefined} & & & \text{for } \theta_0 < x_{(n)}, \\
1 & & & \text{for } \theta_1 < x_{(n)} \leqslant \theta_0, \\
(x_{(n)} / \theta_0)^n & & & \text{for } 0 \leqslant x_{(n)} \leqslant \theta_1. \\
\end{cases}$$
This latter test has the benefit of avoiding a binary p=value, while maintaining the UMP condition (again trivially).  Intuitively, it involves the specification of a lower observed maximum value being more conducive to a lower upper bound in the sampling distribution.
Comment: (+1) The likelihood ratio (when defined) is either 0 or $\left(\frac{\theta_0}{\theta_1}\right)^n$, not that this materially affects the points you make in the 3rd paragraph. A motivation for the additional evidentiary ordering described in the 4th paragraph might be provided by the *generalized* likelihood-ratio test statistic $\frac{\sup_\theta[f(\vec{x};\theta)]}{f(\vec{x};\theta_0)}=\frac{(1/x_{(n)})^n}{(1/\theta_0)^n}$
Answer: I think you might found the answer for this. But this is what i am thinking.
Define $$\frac{\theta_1^n}{\theta_0^n} = T^n$$
then, reject the null hypothesis if $T^n \leq $ c.
by taking the logarithm of both sides , you can simplify this to ,
 reject the null hypothesis if $$log (T) \leq k$$ .
Comment: The value $T$ is fixed by the hypotheses, and does not depend on the data.  So by this reasoning, your test does not depend on the data at all!
Comment: The uniform in this case depends on the data, through its support.  In the link you have provided, the test also depends on the data.
Comment: In Uniform distribution,  the likelihood function does not depend on data.         Here is a similar kind of  that attempted   , https://math.stackexchange.com/questions/1736322/uniformly-most-powerful-test-for-a-uniform-sample


pandas read_csv() returns duplicate entries with .1 and .2 when CSV contents read as list

Question: I am reading first row of CSV file in to a list using pandas read_csv() method as below.
<code>target_df = pandas.read_csv(file_absoulte_path, nrows=0, engine='python').columns.tolist()
</code>
And comparing the list returned above with another list (expected_columns) as below.
<code>        if(colums_expected==target_df):
            logger.info("Column names are CORRECT, as expected!")
        else:
            logger.error("Column names are NOT CORRECT!, not as expected!")
</code>
imagine, expected_columns=["NewYork","Sydney","Sydney","Sydney"]
Now the target CSV file also have the same columns like "NewYork","Sydney","Sydney","Sydney"
When I read CSV using Pandas read_csv() as said above, it returns the contents of CSV file as "NewYork","Sydney","Sydney.1","Sydney.2"
So, basically read_csv is appending .1, .2 from 2nd duplicate column value and which is making comparison fail. If there are no duplicate columns in CSV all works well. And while displaying CSV contents to log also it is annoying.
Is there any way pandas read_csv() reads duplicate column values without appending .1, .2
I am using python 3.8.
appreciate your help. Thank you.
Answer: Pandas dataframes are based on dictionaries, whereas dictionaries can't have duplicate columns.
As mentioned in the docs:

Dictionaries are mutable unordered collections (they do not record element position or order of insertion) of key-value pairs. Keys within the dictionary must be unique and must be hashable. That includes types like numbers, strings and tuples. Lists and dicts can not be used as keys since they are mutable. Dictionaries in other languages are also called hash tables or associative arrays.

Notice "Keys within the dictionary must be unique and must be hashable.".
Comment: Thank you @U11-Forward, for your response. So how can come out the issue I am facing. Do I have to use normal csv package ? or is there any workaround kind of thing to amend the current code itself ? Thank you.


Como detectar conexão com a internet no ionic?

Question: Estou usando o Ionic 3 junto com o plugin network do ionic, consigo detectar quando esta conectado numa rede de internet pelo plugin mas não consigo verificar se nesta rede conectada esteja com internet ou não, alguém sabe como posso fazer isso?
Answer: Existe o plugin citado na própria documentação: https://ionicframework.com/docs/native/network/ para instalar navegue até a pasta do projeto com cd e execute os comandos, como no exemplo:
cd /home/user/projeto
ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

Então no src/app/app.module.ts adicione aos providers, exemplo:
import { Network } from '@ionic-native/network';

...

@NgModule({
  ...

  providers: [
    ...
    Network
    ...
  ]
  ...
})
export class AppModule { }

Então aonde for usar o módulo faça isso:
import { Network } from '@ionic-native/network';

constructor(private network: Network) { }

...

let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
    console.log('Desconectado da internet');
});

let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('Conectado a internet!');
});

Se quiser parar os observadores use:
disconnectSubscription.unsubscribe();
connectSubscription.unsubscribe();

Note que não é porque você esta conectado a uma rede ou rede móvel que significa que teu provedor esta lhe enviando internet (lhe provendo), um teste mais simples seria usar HttRequest e checar se você consegue acessar qualquer url do serviço que interessa a sua aplicação.
Por exemplo (é em php mas pode adaptar facilmente) criaria uma página simples que retornaria qualquer coisa, por exemplo a palavra success:
<?php
echo 'success';

Então o teste seria algo como:
import { HTTP } from '@ionic-native/http';

constructor(private http: HTTP) {}

...

this.http.get('http://meu-site.com/status.php', {}, {})
  .then(response => {
      if (response.data === 'success') {
          console.log('Serviço disponível');
      }
  })
  .catch(error => {
    console.log('Serviço indisponível');
    console.log("status:", error.status);
    console.log("descritivo:", error.error);
    console.log("headers:", error.headers);

  });

Comment: @JulianoSouza a ideia do request pode ser usada até para checar outros serviços, tipo no lado do servidor checar se o banco de dados esta disponivel, ou até outras dependencias, ai retornaria um `success`, isso já checaria a internet e o teu servidor ao mesmo tempo, veja a edição da resposta.
Comment: Sim, eu já tinha pensando em fazer um request mas achei que poderia ter alguma outra solução, obrigado!


Pointwise convergence of a function

Question: This confused me,
$$\lim_{n \to \infty} x^{1 + \frac{1}{2n-1}} = x \lim_{n \to \infty}x^{\frac{1}{2n-1}}=|x| $$
Which means $$\lim_{n \to \infty}x^{\frac{1}{n}} = \left\{ \begin{array}{lr}
       1 & : x > 0\\
       -1 & : x < 0\\
       0 & : x = 0
     \end{array} \right.$$
Rudin gives an easy proof as to why this works when x is nonnegative, but when x is negative I don't know how to deal with fractional powers of negative numbers. Is this something I simply can't do without further reading or am I being stupid?
Comment: Jonas Meyer: I can see why you would think so. I made a jump in reasoning there and Raymond explains why it was incorrect.
Comment: Fixed. Thanks..
Answer: Note that Rudin was cautious since he had $\lim_{n \to \infty}x^{\frac{1}{2n-1}}$ so that he always considered a $(2n-1)$th (odd!) root of x.
Your inference is wrong : this doesn't mean that $\lim_{n \to \infty}x^{\frac{1}{n}}$ is $1$ or $-1$ depending of the sign of $x$. If $x\lt0$ this last limit doesn't exist because the (2n)-th root is not defined in $\mathbb{R}$.
I think that Rudin's point was that $$\lim_{n \to \infty}x^{\frac{1}{2n-1}} = \left\{ \begin{array}{lr}
       1 & : x > 0\\
       -1 & : x < 0\\
       0 & : x = 0
     \end{array} \right.$$
which is true (keeping the parity of n is vital!).
To understand what's going on just consider an example : $a_n=(-2)^{\frac{1}{2n-1}}$ you'll get a number closer and closer to $-1$ as $n \to \infty$.

Pointwise convergence of a function


Problema com query usando DB where/orWhere Laravel

Question: Boa tarde amigos, estou tendo problemas com uma consulta usando DB no laravel,
coloquei uma clausula where e outra orWhere e um whereBetween, porém não está passando pelo between, e quando tiro o orWhere funciona, alguém já passou por isso?
Código:
<code>$result = DB::table('tb_monitor_laudo_info')
            ->where('usuariox_operador', 'like', $usuariox)
            ->orWhere('id', '=', $usuariox)
            ->whereBetween('data_laudo',[$datainicial, $datafinal])
            ->orderBy('operador')
            ->get();
</code>
Answer: É necessário vc utilizar um Parameter Grouping do laravel, para que a ORM não se confunda na relação entre os operadores, veja abaixo como deve ficar:
<code>$result = DB::table('tb_monitor_laudo_info')
            ->where('usuariox_operador', 'like', $usuariox)
            ->where(function ($query) use ($usuariox) {
               $query->where('usuariox_operador', 'like', $usuariox)
                 ->orWhere('id', '=', $usuariox);
             })
            ->whereBetween('data_laudo',[$datainicial, $datafinal])
            ->orderBy('operador')
            ->get();
</code>
Comment: Funcionou!! vlw cara


capture stream from raspberrry pi using gstreamer in opencv

Question: I'm trying to stream a video from a raspberry pi camera to my PC through a local network.
On the RaspberryPi side, I use gstreamer with the following command:
raspivid -n -t 0 -rot 270 -w 960 -h 720 -fps 30 -b 6000000 -o - | gst-launch-1.0 -e -vvvv fdsrc ! h264parse ! rtph264pay pt=96 config-interval=5 ! udpsink host=192.168.1.85 port=5000

And I use the following command on the PC side:
gst-launch-1.0 -e -v udpsrc port=5000 ! application/x-rtp, payload=96 ! rtpjitterbuffer ! rtph264depay ! avdec_h264 ! fpsdisplaysink sync=false text-overlay=false

In this case, the video gets displayed and everything works fine. However, I would like to capture the stream with OpenCV in a C++ program. I'm trying to do this using OpenCV 3.2 compiled with gstreamer-1.0 32bit.
When I run the following code to try to capture the stream:
#include <opencv2/opencv.hpp>

int main(int argc, char *argv[])
{
    cv::VideoCapture cap("udpsrc port=5000 ! application/x-rtp, payload=96 ! rtpjitterbuffer ! rtph264depay ! avdec_h264 ! appsink");

    return 0;
}

I get the following error:
GStreamer Plugin: Embedded video playback halted; module udpsrc0 reported: Internal data stream error.

OpenCV Error: Unspecified error (GStreamer: unable to start pipeline) in cvCaptureFromCAM_GStreamer, file:\opencv\modules\videoio\src\cap_gstreamer.cpp, line 832

I was able to receive other streams using OpenCV, but I can't get it to work with gstreamer.
I searched for this problem, but I can't find anything helpful, so I would really appreciate some help.
Comment: Thanks for you comment, but adding caps did not seem to matter.
Comment: I think udpsrc might need caps defining the encoding type. Like `application/x-rtp, encoding-name=H264, payload=96` instead of `application/x-rtp, payload=96`.
Answer: I have given this problem another try, and it works now. I'll post how I did it in the hope others will have an easier time.
I followed the instructions by wumpus to make it work.
On the pc side I run:
#include <opencv2/opencv.hpp>
int main(int argc, char *argv[])
{
    cv::VideoCapture cap("udpsrc port=5000 ! gdpdepay ! rtph264depay ! avdec_h264 ! videoconvert ! appsink sync=false");

    return 0;
}

And then I run on the raspberry pi:
gst-launch-1.0 rpicamsrc bitrate=3000000 ! video/x-h264, width=960, height=720 ! h264parse ! queue ! rtph264pay config-interval=1 pt=96 ! gdppay ! udpsink host=192.168.1.85 port=5000

To make this work you need to install gstreamer and rpicamsrc on the raspberry pi.
Also you need to have opencv compiled with gstreamer 32 bit on your pc. First install gstreamer, developer version, and then compile opencv. See this for help on compiling opencv in visual studio.


How do I get more info for 'invalid format' error with onpladm on Windows?

Question: This is my first time trying to use Informix. I have around 160 tables to load, using pipe-delimited text files.  We have an older series of batch files that a previous developer wrote to load Informix data, but they're not working with the new version of Informix (11.5) that I installed. I'm running it on a Windows 2003 server.
I've modified the batch file to execute the onpladm commands for one file, so this batch file looks like this:
onpladm create project dif31US-1-table-Load

onpladm create object -F diffdbagidaxsid.dev
onpladm create object -F diffdbagidaxsid.fmt
onpladm create object -F diffdbagidaxsid.map
onpladm create object -F diffdbagidaxsid.job

When I run this, it successfully creates the project and device array,
but I get an error creating the format.  The only error I get is:
Create object DELIMITEDFORMAT   diffile1fmt failed!
Invalid format!

The diffdbagidaxsid.fmt file is as follows:
BEGIN OBJECT DELIMITEDFORMAT diffile1fmt

PROJECT dif31US-1-table-Load
CHARACTERSET ASCII
RECORDSTART
RECORDEND
FIELDSTART
FIELDEND
FIELDSEPARATOR |
BEGIN SEQUENCE
FIELDNAME agid
FIELDTYPE Chars
END SEQUENCE
BEGIN SEQUENCE
FIELDNAME axsid
FIELDTYPE Chars
END SEQUENCE

END OBJECT

As you can see, it is only 2 columns.  It originally had nothing following the CHARACTERSET.  I've tried it with ASCII, and with the numeric code for ASCII, and still get the same error.
Is there any way to get a more verbose error message?
Also, can anyone recommend a decent (meaning active community) forum for Informix? I've tried the old comp.databases.informix forum, http://www.dbforums.com, the 'official' forum on IBM DeveloperWorks, and here of course. None have very much activity. We have to do this testing because we have customers (or maybe just 1 big one) who uses it, so we have to test our data and API against it.
Comment: The IIUG (International Informix User Group) web site http://www.iiug.org/ allows you to join (free, and you don't get too much obnoxious email from joining) and sign up for the mailing lists.  The email@example.com mailing list is the most active and probably the relevant one to ask.
Comment: thanks for the tip, but I tried to register there and haven't gotten a response after several days
Answer: Succinctly, I don't think there is a way to get much more information out of onpladm.


getting form title

Question: I have a form created by using custom module, I can get all the fields but now how should I get the form title? below is the code to get the specific field in .module file.
$form['name'] = array(
 '#title' => 'NAME',
'#type' => 'textfield',
);

Comment: check $form_state['name']['#title'] ?
Comment: Forms technically don't have a title as such. Do you mean a page title above the form, or you want some text inside the form that looks like a title?
Comment: yes I have a title above my form fields not a page title
Comment: can you be more specific and elaborate by attaching some screenshots ?
Answer: The title of a form is not a form element - you set it depending on where the form is used - e.g. as a 'title' set in hook_menu (docs) or 'info' in hook_block_view (docs).
You can use drupal_get_title and drupal_set_title to get/set it.
Answer: You can either create a fieldset and use the #title property to create a legend tag, you'll need to prefix the form element with the fieldset, e.g.
$form['group'] = array(
  '#title' => t('TITLE'),
  '#type' => 'fieldset',
);

$form['group']['name'] = array(
  '#title' => t('NAME'),
  '#type' => 'textfield',
);

Alternatively, you can use markup to include any HTML you want.

getting form title


como colocar um video dentro de um pdf

Question: Como inserir um vídeo em um pdf gerado usando a biblioteca iTextSharp?
Preciso da biblioteca porque ela também faz união de arquivos e assinatura digitais.
Answer: Utilizando o iTextSharp, faça da seguinte forma:
<code>//cria o documento
var doc = new Document();
//caminho do arquivo gerado
String outfile = "c:/documento.pdf";
//pega instância do objeto PdfWriter
PdfWriter writer=PdfWriter.GetInstance(doc, new FileStream(outfile, FileMode.Create));
//abre o documento para escrita
doc.Open();
//cria uma instância da classe PdfFileSpecification
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, "c:/video.mpg", "video.mpg", null);
//criar e adiciona uma anotação de vídeo no documento
writer.AddAnnotation(PdfAnnotation.CreateScreen(writer, new Rectangle(200f, 700f, 400f, 800f), "Vídeo", fs,"video/mpeg", true));
//fecha o documento
doc.Close();
//visualiza o resultado
System.Diagnostics.Process.Start(outfile);
</code>
Os seguintes formatos de arquivo são suportados:

.aiff  ---    audio/aiff
.au      ---  audio/basic
.avi   ---    video/avi
.mid   ---    audio/midi
.mov   ---    video/quicktime
.mp4   ---    video/mp4
.mp4   ---    audio/mp4
.mpeg  ---    video/mpeg
.smil  ---    application/smil
.swf   ---    application/x-shockwave-flash

Fonte

como colocar um video dentro de um pdf


Eclipse: Remove Eclipse generated .class and .project files

Question: I have a Java project with SVN version control system. My IDE is eclipse. Iniitally when I open the project, I edited something. Since this is team project. Someone else commit his own .class and .project file into svn. When I pointed out, he removed .class and .project in some particular sub projects. Anyway, I have .class and .project in all sub projects. Now I want to a clean environment, I want to delete all .class and .project files. Are there some script available in this forum?
Comment: `find . -name .project | xargs rm`
Comment: Hi: del .project /s works fine. Thanks a lot! cheers!!
Comment: You should write it as an answer and accept it. That would make it easier for other users.
Comment: Do note that there is no harm in leaving those .project files around, and in fact it is Eclipse's idea to share them between developers. They do not contain local information, but key information needed by other developers to get up and running quickly.
Comment: What is windows? I don't see any trace of windows in the question. Maybe you should make that clear?
Comment: Anyway, I want to make a clean project. Thanks for the notes.
Comment: Sorry, that I did not mention I am using Windows 7, and Eclipse, SVN.
Comment: My memory is fading, but are you sure `del .project /s` doesn't work?
Comment: In your windows explorer, just do a search for .class and .project files and just simple delete.
Answer: You didn't mention what OS are you using... If it's linux you can do it in commandline like that:
<code>find /the/path/to/your/project -name ".class" -exec rm {} \;
</code>
Answer: If you have a unix like environment then 'find' from a command line could do it. First cd to the project directory then
    find .  ( -name *.class -or -name .project ) -delete
Answer: Are you using Maven as a build tool? What is your directory structure.
Any bin, out, target etc. directories should be on ignore list in SVN. You can use "add to ignore list" in Tortoise SVN or edit folder properties and set "svn:ignore" property. This you can do recursively. Mind that this will affect other developers too.
If you're not using Maven, deleting .project and .classpath might cause some trouble. There might be some project-specific settings set. Blindly deleting .project files is not a solution. If you use Maven, you can definetely delete .project, .classpath and .settings, add them to ignore list and re-import all proejects with m2e plugin.


Permutation of a String of ints

Question: I'm doing a Java assignment this week where we're expected to use a set to backtrack through a String recursively and find all permutations of said String, culminating in an int of maximum size from the numbers contained within the string. This part alone is fine. The issue is that we are expected to set the length of this integer, shown here in int z.
For example, the expected output of method maxDigit("12345",3) would be: 543.
Could you please point out where I need to be looking to improve my code?
Cheers.
<code>    /**
 * Returns the maximum possible integer given the string str containing digits, using
 * maximum of n digits. Each digit in str can only be used once.
 **/
static int maxDigit(String str, int z) {
    Set<Integer> result = new TreeSet<>();

    if(str.length() == 0 || z == 0)
        return -1;

    permute("",str,result,z);

    int answer = 0;
    for(int a : result) {
        if(a > answer)
            answer = a;
    }
    return answer;
}

/**
 * Creates a set of permutations in result based on string str with max n digits.
 **/
private static void permute(String acc, String str,Set<Integer> result,int z) {
    int n = str.length();
    if (n == 0)
        result.add(Integer.parseInt(acc));
    else {
        if(!(z < str.length())) {
            for (int i = 0; i < n; i++)
                permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z);
        } else {
            for (int i = 0; i < n - 1; i++)
                permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, z), result, z);
        }
    }
}
</code>
Comment: @RicoKahler It certainly would, but this in particular is designed to test knowledge of backtracking in Java, so sorting the String is impossible in this instance.
Comment: i know that this doesn't answer your question, but wouldn't sorting the numbers in the string descending and taking the first `z` numbers result in the largest possible number? This is O(nlogn)
Answer: This seems to work.  Your edge condition is the problem.
<code>private static void permute(String acc, String str,Set<Integer> result,int z) {
    int n = str.length();
    if (acc.length() == z)
        result.add(Integer.parseInt(acc));
    else {
        for (int i = 0; i < n; i++)
            permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z);

    }
}

System.out.println(maxDigit("1234", 2));
43
</code>
Comment: Thanks Nick. Unfortunately, this fails in another edge condition where z exceeds the size of the string.
Comment: Never mind, I'm just silly and forgot to implement a check for that in the former method. +1!

Permutation of a String of ints


Using WHERE clause twice on same column?

Question: I'm trying to select twice from the same column I read a few previously posted questions and some people where suggesting using T1. and T2. however I'm unsure on how to implement these into this example. So what I'm trying to do is select twice from the statement_type column. WHERE the value is either WTHD OR TIP
SELECT * FROM `usr_statements`
WHERE `username` = '$username' AND `statement_type` = 'WTHD' AND `statement_type` = 'TIP'
ORDER BY `statement_ref`";

The column I'm trying to sort from twice is the statement_type.
WHERE `username` = '$username' AND `statement_type` = 'WTHD' AND statement_type` = 'TIP'

Comment: Thankyou @FelixPamittan I previously tried OR but without defining the column again. but the suggestion you provided here worked. Thankyou very much.
Comment: you can use `OR` among `statement_type` here.
Comment: `WHERE \`username\` = '$username' AND (\`statement_type\` = 'WTHD' OR \`statement_type\` = 'TIP')`
Comment: Easiest to use the "in" statement. Like so... `statement_type` in ('WTHD','TIP')
Comment: @LewisDay, if this question is resolved, please accept one of the answers below.
Answer: If you are going to sort the same column by using different condition then use OR
SELECT * FROM `usr_statements`
WHERE `username` = '$username' AND (`statement_type` = 'WTHD' OR `statement_type` = 'TIP')
ORDER BY `statement_ref`";

If you have more then 3 statement then use IN for less the complexity,
SELECT * FROM `usr_statements`
WHERE `username` = '$username' AND `statement_type` IN('WTHD', 'TIP')
ORDER BY `statement_ref`";

Answer: You can either use OR:
WHERE `username` = '$username' AND (`statement_type` = 'WTHD' OR `statement_type` = 'TIP')

or use IN
WHERE `username` = '$username' AND `statement_type` IN('WTHD', 'TIP')

Comment: Thankyou! the `IN` is more readable and works perfectly, will be marking as answer shortly. :)


Akaike information criterion. AICs analysis ( sample size =5, No of parameters (not counting the error variance) = 3), in result AICc = infinite.

Question: Could you please recommend another formula for AIC correction for small sample size (n/k < 40)
Comment: You shouldn't do anything that has 5 observations and 3 variables.  You will surely be overfitting the data. The infinite AICc is a warning.  You shouldn't ignore it.
Comment: According to https://en.wikipedia.org/wiki/Akaike_information_criterion#AICc the "AIC with correction" is used for small sample sizes, is this what you are using?
Comment: Why is AIC infinite?
Answer: There are no other formulas for AIC.  There are other fit statistics, some of them variations on AIC, such as AICc, but that starts with AIC which will be infinite (as you state) and then adds to it:
$$AICc = AIC + \frac{2k^2 + 2k}{n - k - 1} $$
where n is sample size and k is the number of parameters.
There is also BIC:
$$BIC = ln(n)k - 2*ln{\hat{L}}$$
But there is a more basic problem: You are modeling 5 cases with 3 parameters.  You shouldn't do that. You will be overfitting your data. You need a lot more data or a simpler model.
Comment: Right, ok, calculate it and listen to it
Comment: Isn't the purpose of AIC etc to penalise overfitting? Seems odd to say it shouldn't be used in cases for which overfitting is suspected
Comment: Yes, that's the purpose. And, in fact, that's what it is doing. It is saying THERE IS OVERFITTING.  It is shouting that. So, I didn't say "don't use it" I said "listen to it".


Sqlite or sharedpreference is suitable for my application

Question: I have an android app with user login i need to store the login details in my app.
My app also has some user history of certain request made by him/her.
My app is a software service app so user details must be stored in app which is fetched from the database
Is  Sqlite or sharedpreference suitable for my application?
Comment: "which is fetched from the database"... Doesn't that answer your question?
Comment: A Google search on the subject will show you wonders.
Answer: Depends, If you only want to save sessions of user use SharedPrefrence or else if the data is more you can use sqlite
<code>   /**
     * method to set the login status for the application
     *
     * @param context
     * @param status
     */
    public static void setLoginStatus(Context context, int status) {
        sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();
        editor.putInt(KEY_LOGIN_STATUS, status);
        editor.apply();
    }
</code>

NOTE :
About that its totally on your choice what you use to save the current
  state of user , i will prefer using shared preferences. And for signup
  and sign in use SQLite database. Shared preferences are commonly used
  to perform light operations. You can search through data in SQLite as
  you may have many users.
So use SQLite to register and login and then use shared preferences to
  save tha current state of user.
Comment: I have just username and password to be saved at the same time a few user details which includes request type request details date etc
Comment: If the user data is more than use sqlite
Comment: I told you If you just want to manage `Sessions` use SharedPrefs OR use sqlite
Comment: You can use both. Session in SharedPreferences. Whatever else in database
Comment: @RautDarpan I can't understand whats ment by more than means what's the normal use of both databae
Comment: @arun There shouldn't be a reason to save a password in your app
Comment: If the data is more complex for `eg: username, place, date etc etc.` then use data base for this and save your `Session` details in `SharedPrefs` look at eg above
Comment: @arunmohan sessions in sense `isUserLoggedIn` or `LoggedOut` `AuthKey`
Comment: @arunmohan see I have updated my answer now you can get what i want to say
Answer: Sqlite is always a better option to store the data there you can manage in proper format and you can encrypt as well.
Answer: I would suggest, you should use sharedPreferences for saving the login details and i suppose whatever request you are storing, contains more data, so save your requests in SQLite.
Comment: the go for SQLite in case of storing requests
Comment: If am using does it need sharedpreference to store shared preference
Comment: https://developer.android.com/reference/android/content/SharedPreferences.html
https://www.tutorialspoint.com/android/android_shared_preferences.htm
Answer: Here is some good details about theme :
Pros and Cons of SQLite and Shared Preferences

SQLite
Large amounts of same structured data should be stored in a SQLite
  database as databases are designed for this kind of data. As the data
  is structured and managed by the database, it can be queried to get a
  sub set of the data which matches certain criteria using a query
  language like SQL. This makes it possible to search in the data. Of
  course managing and searching large sets of data influences the
  performance so reading data from a database can be slower than reading
  data from SharedPreferences.
SharedPreferences
SharedPreferences is a key/value store where you can save a data under
  certain key. To read the data from the store you have to know the key
  of the data. This makes reading the data very easy. But as easy as it
  is to store a small amount of data as difficult it is to store and
  read large structured data as you need to define key for every single
  data, furthermore you cannot really search within the data except you
  have a certain concept for naming the keys.

According to the Size or Format of your data you can choose one, for login information I suggest using SharedPreferences
Comment: @RautDarpan I have added the link and the text in the quotations


Can't there be an infinite number of prime triplets separated by 2?

Question: I came across a question on brilliant.org where it had been mentioned that $X, X + 2, X + 4$ are all prime numbers for $X = 3$. So is there any other $X$ for which $X, X + 2, X + 4$ are all primes and the answer was no.
So, can we say that there cannot be infinite number of prime triplets separated by $2$.
Please explain why?
Comment: One of those three numbers will be divisible by 3.
Comment: Isn't this a duplicate question?
Answer: At least one of them is divisible by $3$. (Indeed, I suppose exactly one of them is divisible by $3$.)
Answer: As mentioned by others, one of them will be divisible by 3.
To demonstrate this, we assume that $x$ is not divisible by 3, so it will either be of the form $x = 3q+1$ or $x = 3q+2$ for some $q \in \mathbb N$.
If $x = 3q+1$, then $x+2 = 3q+3$, so $x+2$ is divisible by 3. If, on the other hand, $x = 3q+2$, then $x+4 = 3q+6$, and thus divisible by 3.
Therefore exactly one of the three numbers $x$, $x+2$ or $x+4$ will be divisible by 3, so they can only all be prime if $x = 3$.


Can we prove AM-GM Inequality using these integrals?

Question: I came across these two results recently:
$$ \int_a^b \sqrt{\left(1-\dfrac{a}{x}\right)\left(\dfrac{b}{x}-1\right)} \: dx = \pi\left(\dfrac{a+b}{2} - \sqrt{ab}\right)$$
$$ \int_a^c \sqrt[3]{\left| \left(1-\dfrac{a}{x}\right)\left(1-\dfrac{b}{x}\right)\left(1-\dfrac{c}{x}\right)\right|} \: dx = \dfrac{2\pi}{\sqrt{3}}\left(\dfrac{a+b+c}{3} - \sqrt[3]{abc}\right)$$
for $0<a\leq b\leq c$.
I haven't tried to solve the first one yet, but I have an idea of how to approach it, namely using the substitution $x=a\cos^2\theta+b\sin^2\theta$. I have no idea how to approach the second one, however.
I think that the most interesting thing about the results above is that it seems like there is a proof for the AM-GM inequality hidden within. Clearly both integrands are positive and so the AM-GM falls out for the 2 and 3 variable case. All that is required is to prove the results.
My question is twofold:

How would the second integral be computed? Is there an approach using elementary techniques?
Can this be generalised to prove the AM-GM inequality for $n$-variables?
Comment: I checked numerically. The second integral is false for $a=1$, $b=2$, $c=3$. Please, check your sources.
Comment: @jjagmath. I used the same case !
Comment: The second integral seems to be correct with a cube root instead of a square root in the integrand.
Comment: Interestingly, the pattern fails for $n \ge 4$.  But I have no proof of any of these.
Comment: @ComplexYetTrivial. Good shot !
Comment: Can you tell use *where* you came across these identities?
Comment: For the first equation, see https://math.stackexchange.com/q/2799576/42969, https://math.stackexchange.com/q/3343625/42969, https://math.stackexchange.com/q/3549527/42969.
Comment: Apologies, yes it should be a cube root in the integrand. It has now been edited.

I found it on an instagram math page. I have contacted the owner asking for a source and/or proof but there was no reply.
Comment: Feng Qi and Dongkyu Lim, Integral representations of bivariate complex geometric mean and their applications, Journal of Computational and Applied Mathematics vol. 330 (2018), 41--58; available online at https://doi.org/10.1016/j.cam.2017.08.005.
Answer: $\DeclareMathOperator{\Res}{Res}$
$\DeclareMathOperator{\sgn}{sgn}$
$\newcommand{\d}{\mathrm{d}}$
$\newcommand{\e}{\mathrm{e}}$
$\newcommand{\E}{\mathrm{E}}$
$\newcommand{\P}{\mathrm{P}}$
$\newcommand{\i}{\mathrm{i}}$
$\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}$
Let $0 < a_0 \leq a_1 \ldots \leq a_{n-1}$ be a monotone sequence of $n$
positive real numbers. Then $$\boxed{
  \sum_{k=0}^{n-2}\frac{1}{\pi}\sin \tfrac{\pi (k+1)}{n}\int_{a_k}^{a_{k+1}}
\left(\prod_{i=0}^{n-1}\sqrt[n]{\abs{x-a_i}}\right)\frac{\d x}{x}
  =\frac{1}{n}\sum_{i=0}^{n-1}a_i - \sqrt[n]{\prod_{i=0}^{n-1}a_i}
}\text{.}$$
The left side is manifestly nonnegative, so OP's second question is answered in the affirmative, although the form of the left side for $n=2,3$ is deceptively simple and does not reflect the general case.
The underlying method of this answer does not differ from that of Svyatoslav's, save for doing the bookkeeping needed to provide for the $n$-variable case. The method can be adapted to show that, for a positive random variable $X$ that takes on a finite set of values,
$$
  \int_{\mathrm{ess}\,\inf X}^{\mathrm{ess}\,\sup X}
\frac{\sin (\pi \P(X >x))}{\pi x}\e^{\E \ln \abs{X-x}} \d x
  =\E\,X - \e^{\E\ln X}
\text{;}$$
it's tempting to think that this last equality holds for arbitrary positive random variables with finite arithmetic and geometric mean, but I have no proof of that.

Write $I$ for the closed interval $[a_0,a_{n-1}]$. Take
the cut of $\sqrt[n]{z}$ to be the negative real axis. Write $\mathbb{C}^*$ for the Riemann sphere. Consider the meromorphic
differential forms $\alpha_{U_0}$, $\alpha_{U_1}$, $\alpha_{U_2}$,
on $U_0 =
\mathbb{C}\backslash (-\infty,a_{n-1}]$, $U_1 = \mathbb{C}\backslash
[a_0,\infty)$, and $U_2=\mathbb{C}^*\backslash [0,a_{n-1}]$ given by
$$\begin{aligned}
  \alpha_{U_0} &=\left(\prod_{i=0}^{n-1}\sqrt[n]{z-a_i}\right)\frac{\d z}{z} \\
  \alpha_{U_1} &=-\left(\prod_{i=0}^{n-1}\sqrt[n]{a_i-z}\right)\frac{\d z}{z} \\
  \alpha_{U_2} &=-\left(\prod_{i=0}^{n-1}\sqrt[n]{1-a_iz^{-1}}\right)\frac{\d (z^{-1})}{(z^{-1})^2}\text{.}
\end{aligned}$$
These three forms agree pairwise on the intersections of their respective
domains. That's because—for the chosen cut convention—

if $a > 0$ and either $\Im z \neq 0$ or $\Re z > a$, then
$$\sqrt[n]{z-a} = \frac{\sqrt[n]{1-az^{-1}}}{\sqrt[n]{z^{-1}}}\text{;}$$

if $a > 0$ and $\Im z \neq 0$, then
$$\sqrt[n]{a-z} = \e^{-\i\pi \sgn \Im z /n}\sqrt[n]{z-a}\text{.}$$

Consequently, there is a unique meromorphic differential form $\alpha$ on
$\mathbb{C}^*\backslash I = \bigcup_{i=0}^2U_i$ such that $\left.
\alpha\right\rvert_{U_i} = \alpha_{U_i}$ for $i=0,1,2$. This $\alpha$ has a
simple pole at $0$ and a double pole at $\infty$.
So let $C$ be a cycle separating $I$ from $\{0,\infty\}$ and oriented in the
negative sense. What is
$$\frac{1}{2\pi\i}\oint_C\alpha\text{?}$$

If $C$ is taken to be a rectangle with sides parallel to and infinitesimally
close to $I$, then
$$\frac{1}{2\pi\i}\oint_C \alpha
    = \frac{1}{2\pi\i}\left(\int_{I+\i 0^+}\alpha -
    \int_{I-\i0^+}\alpha\right)\text{,}$$
the contribution from the remaining sides vanishing.

If $C$ is taken to encircle $\{0,\infty\}$ in a positive sense, then
$$\frac{1}{2\pi\i}\oint_C \alpha
    = \Res_0 \alpha + \Res_{\infty}\alpha\text{.}$$

For the former choice, note that, for real $x$,
$$\sqrt[n]{x\pm \i 0^+} = \sqrt[n]{\abs{x}}\e^{\pm\i\pi [x < 0]/n}$$
where $[(-)]$ is Iverson bracket notation.
Therefore
$$\int_{I\pm\i0^+}\alpha = \int_I\e^{\pm\i\pi
N(x)/n}\left(\prod_{i=0}^{n-1}\sqrt[n]{\abs{x-a_i}}\right)\frac{\d x}{x}$$
where $N(x)$ is the number of the $a_i$ greater than $x$. Then
$$\frac{1}{2\pi\i}\oint_C\alpha = \frac{1}{\pi}\int_I\sin \tfrac{\pi N(x)}{n}
\left(\prod_{i=0}^{n-1}\sqrt[n]{\abs{x-a_i}}\right)\frac{\d x}{x}$$
which, because $N(x)$ is constant away from the $a_i$, simplifies to
$$\frac{1}{2\pi\i}\oint_C\alpha =
  \sum_{k=0}^{n-2}\frac{1}{\pi}\sin \tfrac{\pi (k+1)}{n}\int_{a_k}^{a_{k+1}}
\left(\prod_{i=0}^{n-1}\sqrt[n]{\abs{x-a_i}}\right)\frac{\d x}{x}\text{.}$$
As for the latter choice: from the Laurent expansions of $\alpha$ at $0$, $\infty$
$$\alpha_z = \left(-\sqrt[n]{\prod_{i=0}^{n-1}a_i} + \mathcal{O}(z)\right)\frac{\d z}{z}$$
$$\alpha_z = \left(-\frac{1}{z^{-1}} + \frac{1}{n}\sum_{i=0}^{n-1}a_i + \mathcal{O}(z^{-1}) \right)\frac{\d (z^{-1})}{z^{-1}}$$
the required residues are found to be
$$\Res_0 \alpha = - \sqrt[n]{\prod_{i=0}^{n-1}a_i}$$
$$\Res_{\infty} \alpha = \frac{1}{n}\sum_{i=0}^{n-1}a_i$$
whence
$$\frac{1}{2\pi\i}\oint_C\alpha =
\frac{1}{n}\sum_{i=0}^{n-1}a_i - \sqrt[n]{\prod_{i=0}^{n-1}a_i}\text{.}$$
These two choices of $C$ must result in the same value for $\tfrac{1}{2\pi\i}\int_C\alpha$, whence
$$\boxed{
  \sum_{k=0}^{n-2}\frac{1}{\pi}\sin \tfrac{\pi (k+1)}{n}\int_{a_k}^{a_{k+1}}
\left(\prod_{i=0}^{n-1}\sqrt[n]{\abs{x-a_i}}\right)\frac{\d x}{x}
  =\frac{1}{n}\sum_{i=0}^{n-1}a_i - \sqrt[n]{\prod_{i=0}^{n-1}a_i}
}\text{.}$$
Comment: Nice general solution. Just, I'm afraid, the factor 2 is missing: for the case $n=3\,\, (a,b,c)$ the LHS of your equation gives $\frac{1}{\pi}(\sin\pi/3+\sin2\pi/3)=\frac{\sqrt3}{\pi}$ Or, maybe I'm missing something...
Comment: @Svyatoslav each $\sin$ factor is multiplied with an integral over a *different* interval, so for the case $n=3$ when the two $\sin$ factors are equal there is no spurious duplication and the expression matches that given in the OP
Comment: Thank you for the clarification
Comment: Nice proof! Could you please elaborate a bit on why $\alpha_z$ extends to meromorphic differential form? Additionally, and probably related to the previous question, how should one think of terms $\sqrt[n]{z-a_i}$ in the definition of $\alpha_z$ for $z\in (-\infty,a_0)$ (if one takes into account that the cut of the $n$-th root is negative axis)?
Comment: @SaliniMendisi I've added an explicit construction of $\alpha$ by choice of local sections.
Comment: Splendid, all clear now - thanks!
Comment: Stratospherical answer.
Answer: $$I(a,b,c)=\int_a^c\Big|(x-a)(x-b)(x-c)\Big|^{1/3}\frac{dx}{x}=I_{ab}+I_{bc}$$
where $I_{ab}=\int_a^b$, etc.
We go to the complex plane and consider $\oint$ with the turning points $z=a$ and $z=c$ (making the cut from $a$ to $c$). Let's denote this integral as $j$. It is easy to check that
$$j=\oint=I_{ab}+I_{bc}e^{-\pi i/3}+I_{cb}e^{-\pi i}+I_{ba}e^{-4\pi i/3}$$
where $I_{ba}=-I_{ab}$ (we go in the opposite direction - from $b$ to $a$ in the lower bank of the cut). We also added small half- and full circles around $z=a,b,c$ - to make the contour closed (the integrals along these circles have zero contribution).
Now, we add the integration path from $z=c$ to $R$ along axis $X$, and a big circle of the radius $R\to \infty$:
we integrate along the upper bank of the cut, then from $z=c$ to $R$, along a big circle, then from $z=R$ back to $z=c$ along axis $X$ in the opposite direction, and finally  along the lower bank of the cut to the starting point. Let's denote this integral as $J$.
As we have the only pole inside this big closed contour, and bearing in mind that integrals along axis $X$ cancel each other, we can write:
$$J=j+\oint_R=2\pi i \operatorname{Res}\Big((z-a)(z-b)(z-c)\Big)^{1/3}\frac{1}{z}$$
where $\oint_R=\oint_R\Big((z-a)(z-b)(z-c)\Big)^{1/3}\frac{dz}{z}$ - denotes the integration along a big circle (counter-clockwise).
All evaluations are straightforward (the only thing is that we have to appoint correctly the phases of the integrand when going around $z=a,b,c$ on the both banks of the cut).
$$\operatorname{Res}_{z=0}\Big((z-a)(z-b)(z-c)\Big)^{1/3}\frac{1}{z}=e^{\pi i/3}(abc)^{1/3}$$
$$\oint_R\to 2\pi ie^{-2\pi i/3}\Big(-\frac{1}{3}\Big)(a+b+c)\,\, \text{at} \,R\to\infty$$
Taking all together
$$(I_{ab}+I_{bc})(1+e^{-\pi i/3})=2\pi ie^{\pi i/3}\Big((abc)^{1/3}-\frac{a+b+c}{3}\Big)$$
$$I(a,b,c)=\frac{\pi}{\cos(\pi /6)}\Big(\frac{a+b+c}{3}-(abc)^{1/3}\Big)$$
The pattern for $0<a<b<c<d<e...$ is also clear.
Comment: While I have no objections to your main calculation, the last sentence seems highly optimistic. (Numerically, it's not clear to me that there's a generalization to $n>3$.)
Comment: You can write `\operatorname{Res}` to make it look a bit nicer – the content is already nice :)
Comment: @Martin R Thank you - improved :)
Comment: @Semiclassical I agree with you - I also cannot write the general form for the initial integral. The available generalisation is presented in the post by K B Dave
Comment: I will upvote once you edit the last sentence to clear this up a bit (the generalization by K B Dave doesn't seem clear to me ).
Answer: Let $n\in\mathbb{N}=\{1,2,\dotsc\}$ and $\boldsymbol{a}=(a_1,a_2,\dotsc,a_n)$ be a positive sequence, that is, $a_k>0$ for $1\le k\le n$. The arithmetic and geometric means $A_n(\boldsymbol{a})$ and $G_n(\boldsymbol{a})$ of the positive sequence $\boldsymbol{a}$ are defined respectively as
\begin{equation*}
A_n(\boldsymbol{a})=\frac1n\sum_{k=1}^na_k \quad \text{and}\quad
G_n(\boldsymbol{a})=\Biggl(\prod_{k=1}^na_k\Biggr)^{1/n}.
\end{equation*}
For $z\in\mathbb{C}\setminus(-\infty,-\min\{a_k,1\le k\le n\}]$ and $n\ge2$, let $\boldsymbol{e}=(\overbrace{1,1,\dotsc,1}^{n})$ and
\begin{equation*}
G_n(\boldsymbol{a}+z\boldsymbol{e})=\Biggl[\prod_{k=1}^n(a_k+z)\Biggr]^{1/n}.
\end{equation*}
In Theorem 1.1 of the paper [1] below, by virtue of the Cauchy integral formula in the theory of complex functions, the following integral representation was established.
Theorem 1.1. Let $\sigma$ be a permutation of the sequence $\{1,2,\dotsc,n\}$ such that the sequence $\sigma(\boldsymbol{a})=\bigl(a_{\sigma(1)},a_{\sigma(2)},\dotsc,a_{\sigma(n)}\bigr)$ is a rearrangement of $\boldsymbol{a}$ in an ascending order $a_{\sigma(1)}\le a_{\sigma(2)}\le \dotsm \le a_{\sigma(n)}$.
Then the principal branch of the geometric mean $G_n(\boldsymbol{a}+z\boldsymbol{e})$ has the integral representation
\begin{equation}\label{AG-New-eq1}\tag{1}
\boxed{G_n(\boldsymbol{a}+z\boldsymbol{e})=A_n(\boldsymbol{a})+z-\frac1\pi\sum_{\ell=1}^{n-1}\sin\frac{\ell\pi}n \int_{a_{\sigma(\ell)}}^{a_{\sigma(\ell+1)}} \Biggl|\prod_{k=1}^n(a_k-t)\Biggr|^{1/n} \frac{\textrm{d}\,t}{t+z}}
\end{equation}
for $z\in\mathbb{C}\setminus(-\infty,-\min\{a_k,1\le k\le n\}]$.
Taking $z=0$ in the integral representation \eqref{AG-New-eq1} yields
\begin{equation}\label{AG-ineq-int}\tag{2}
\boxed{G_n(\boldsymbol{a})=A_n(\boldsymbol{a})-\frac1\pi\sum_{\ell=1}^{n-1}\sin\frac{\ell\pi}n \int_{a_{\sigma(\ell)}}^{a_{\sigma(\ell+1)}} \Biggl[\prod_{k=1}^n|a_k-t|\Biggr]^{1/n} \frac{\textrm{d}\,t}{t}\le A_n(\boldsymbol{a})}.
\end{equation}
Taking $n=2,3$ in \eqref{AG-ineq-int} gives
\begin{equation}\tag{+}
\boxed{\frac{a_1+a_2}{2}-\sqrt{a_1a_2}\,=\frac1\pi\int_{a_1}^{a_2} \sqrt{\biggl(1-\frac{a_1}{t}\biggr) \biggl(\frac{a_2}{t}-1\biggr)}\, \textrm{d}\,t\ge0}
\end{equation}
and
\begin{equation}\tag{#}
\boxed{\frac{a_1+a_2+a_3}{3}-\sqrt[3]{a_1a_2a_3}\,
=\frac{\sqrt{3}\,}{2\pi} \int_{a_1}^{a_3} \sqrt[3]{\biggl|
\biggl(1-\frac{a_1}{t}\biggr)
\biggl(1-\frac{a_2}{t}\biggr)
\biggl(1-\frac{a_3}{t}\biggr)\biggr|}\,\textrm{d}\,t\ge0}
\end{equation}
for $0<a_1\le a_2\le a_3$.
Weighted version of the integral representation \eqref{AG-New-eq1} can be found in the paper [2] below. We recite the weighted version as follows.
For $n\ge2$, $\boldsymbol{a}=(a_1,a_2,\dotsc,a_n)$, and $\boldsymbol{w}=(w_1,w_2,\dotsc,w_n)$ with $a_k, w_k>0$ and $\sum_{k=1}^nw_k=1$,
the weighted arithmetic and geometric means $A_{w,n}(\boldsymbol{a})$ and $G_{w,n}(\boldsymbol{a})$ of $\boldsymbol{a}$ with the positive weight $\boldsymbol{w}$ are defined respectively as
\begin{equation}
A_{\boldsymbol{w},n}(\boldsymbol{a})=\sum_{k=1}^nw_ka_k
\end{equation}
and
\begin{equation}
G_{\boldsymbol{w},n}(\boldsymbol{a})=\prod_{k=1}^na_k^{w_k}.
\end{equation}
Let us denote $\alpha=\min\{a_k,1\le k\le n\}$.
For a complex variable $z\in\mathbb{C}\setminus(-\infty,-\alpha]$, we introduce the complex function
\begin{equation}\label{complex-geometric-mean}
G_{\boldsymbol{w},n}(\boldsymbol{a}+z)=\prod_{k=1}^n(a_k+z)^{w_k}.
\end{equation}
In Section 3 of the paper [2] below, with the aid of the Cauchy integral formula in the theory of complex functions, the following integral representation was established.
Theorem 3.1. Let $0<a_k\le a_{k+1}$ for $1\le k\le n-1$ and $z\in\mathbb{C}\setminus(-\infty,-a_1]$. Then the principal branch of the weighted geometric mean $G_{\boldsymbol{w},n}(\boldsymbol{a}+z)$ with a positive weight $\boldsymbol{w}=(w_1,w_2,\dotsc,w_n)$ has the integral representation
\begin{equation}\label{AG-New-eq1-weighted}\tag{3}
\boxed{G_{\boldsymbol{w},n}(\boldsymbol{a}+z)=A_{\boldsymbol{w},n}(\boldsymbol{a})+z-\frac1\pi\sum_{\ell=1}^{n-1}\sin\Biggl[\Biggl(\sum_{k=1}^{\ell}w_k\Biggr)\pi\Biggr] \int_{a_\ell}^{a_{\ell+1}} \prod_{k=1}^n|a_k-t|^{w_k} \frac{\textrm{d}\,t}{t+z}}.
\end{equation}
Letting $z=0$ in the integral representation \eqref{AG-New-eq1-weighted} gives
\begin{equation}\label{AG-New-eq1-weighted-z=0}\tag{4}
\boxed{G_{\boldsymbol{w},n}(\boldsymbol{a})=A_{\boldsymbol{w},n}(\boldsymbol{a})-\frac1\pi\sum_{\ell=1}^{n-1} \sin\Biggl[\Biggl(\sum_{k=1}^{\ell}w_k\Biggr)\pi\Biggr] \int_{a_\ell}^{a_{\ell+1}} \prod_{k=1}^n|a_k-t|^{w_k} \frac{\textrm{d}\,t}{t}\le A_{\boldsymbol{w},n}(\boldsymbol{a})}.
\end{equation}
Setting $n=2$ in \eqref{AG-New-eq1-weighted-z=0} leads to
\begin{equation}\label{AG-New-n=2-weighted-z=0}\tag{5}
\boxed{a_1^{w_1}a_2^{w_2}=w_1a_1+w_2a_2-\frac{\sin(w_1\pi)}\pi \int_{a_1}^{a_2} \biggl(1-\frac{a_1}{t}\biggr)^{w_1} \biggl(\frac{a_2}{t}-1\biggr)^{w_2} \textrm{d}\,t
\le w_1a_1+w_2a_2}
\end{equation}
for $w_1,w_2>0$ such that $w_1+w_2=1$.
There have existed more closely related conclusions published in the following references below.
References

Feng Qi, Xiao-Jing Zhang, and Wen-Hui Li, Levy--Khintchine representation of the geometric mean of many positive numbers and applications, Mathematical Inequalities & Applications 17 (2014), no. 2, 719--729; available online at https://doi.org/10.7153/mia-17-53.
Feng Qi, Xiao-Jing Zhang, and Wen-Hui Li, An integral representation for the weighted geometric mean and its applications, Acta Mathematica Sinica-English Series 30 (2014), no. 1, 61--68; available online at https://doi.org/10.1007/s10114-013-2547-8.
Feng Qi and Bai-Ni Guo, The reciprocal of the weighted geometric mean is a Stieltjes function, Boletin de la Sociedad Matematica Mexicana, Tercera Serie 24 (2018), no. 1, 181--202; available online at https://doi.org/10.1007/s40590-016-0151-5.
Feng Qi and Bai-Ni Guo, The reciprocal of the weighted geometric mean of many positive numbers is a Stieltjes function, Quaestiones Mathematicae 41 (2018), no. 5, 653--664; available online at https://doi.org/10.2989/16073606.2017.1396508.
Feng Qi and Dongkyu Lim, Integral representations of bivariate complex geometric mean and their applications, Journal of Computational and Applied Mathematics 330 (2018), 41--58; available online at https://doi.org/10.1016/j.cam.2017.08.005.
Feng Qi, Bounding the difference and ratio between the weighted arithmetic and geometric means, International Journal of Analysis and Applications 13 (2017), no. 2, 132--135.
Feng Qi and Bai-Ni Guo, The reciprocal of the geometric mean of many positive numbers is a Stieltjes transform, Journal of Computational and Applied Mathematics 311 (2017), 165--170; available online at https://doi.org/10.1016/j.cam.2016.07.006.
Feng Qi, Xiao-Jing Zhang, and Wen-Hui Li, The harmonic and geometric means are Bernstein functions, Boletin de la Sociedad Matematica Mexicana, Tercera Serie 23 (2017), no. 2, 713--736; available online at https://doi.org/10.1007/s40590-016-0085-y.
Feng Qi, Xiao-Jing Zhang, and Wen-Hui Li, An elementary proof of the weighted geometric mean being a Bernstein function, University Politehnica of Bucharest Scientific Bulletin Series A---Applied Mathematics and Physics 77 (2015), no. 1, 35--38.
Bai-Ni Guo and Feng Qi, On the degree of the weighted geometric mean as a complete Bernstein function, Afrika Matematika 26 (2015), no. 7, 1253--1262; available online at https://doi.org/10.1007/s13370-014-0279-2.
Feng Qi, Xiao-Jing Zhang, and Wen-Hui Li, Levy--Khintchine representations of the weighted geometric mean and the logarithmic mean, Mediterranean Journal of Mathematics 11 (2014), no. 2, 315--327; available online at https://doi.org/10.1007/s00009-013-0311-z.
Feng Qi and Bai-Ni Guo, Levy--Khintchine representation of Toader--Qi mean, Mathematical Inequalities & Applications 21 (2018), no. 2, 421--431; available online at https://doi.org/10.7153/mia-2018-21-29.
Feng Qi, Viera Cernanova, Xiao-Ting Shi, and Bai-Ni Guo, Some properties of central Delannoy numbers, Journal of Computational and Applied Mathematics 328 (2018), 101--115; available online at https://doi.org/10.1016/j.cam.2017.07.013.
Comment: I see, you really like this question
Comment: There is no need to post (what appears to be) *identical answers* to multiple questions: https://math.stackexchange.com/a/4256362/42969, https://math.stackexchange.com/a/4256364/42969, https://math.stackexchange.com/a/4256373/42969. – If you think that a question has been asked and answered before then you can flag it as a duplicate.
Comment: What I think would make this a better post (both as an answer and for you) is 1) removing all but the most relevant references (so we know what's important - academics can find your CV if they want it), 2) using preprint links instead of (or together with) DOIs so people without library access can quickly find them, and 3) briefly discussing the *motivation* and *implications* of having a Stieltjes transform pair for the shifted weighted GM (e.g., you can bound the difference from above, it's completely positive, it's operator monotone/convex, it can be used in information theory).
Comment: As a mathematician, I think that one should cite the formally published versions of all references, if any,  as possible as one can. The formally published versions imply final versions, most accurate versions, most complete versions, most ... versions.
Comment: If one wants to know more details about proofs of the general conclusions in my answer, I think it is better to read related references listed in my answer. In general, it is impossible for one to get all information about a complex or complicated problem from here. I think that reading journal articles is still necessary for a mathematician to study mathematics. It is often happened that the answers of academic problems in mathematics are not enough short to be recited here, but too long to be stated in details here. Because mathematics formulas can be expressed here by LaTeX, so I like here.
Comment: If estimating those integrals in the right hand sides of the equations with tags (2), (+), (#), (4), and (5) in my answer, then one can bound the difference between the (weighted) arithmetic mean and the (weighted) geometric mean of any finitely many variables.
Comment: The proposer of this question asked that "My question is twofold: How would the second integral be computed? Is there an approach using elementary techniques? Can this be generalised to prove the AM-GM inequality for -variables?" My answer reaches at these aims: as a consequence of one of the general conclusions in my answer, the second integral can be computed by virtue of the Cauchy integral formula in the theory of complex functions; the AM-GM inequality for -variables, including its weighted version, can be proved by the general conclusions in my answer.


Table - Live Search with jQuery

Question: I have been working on a solution for a Live Search on my table of data.
When I search Jim it works as expected :-)
However, when I search Carey, no results appear. Why is this? :-(
Demo: http://jsfiddle.net/L1d7naem/

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});
table, tr, td, th{
    border: 1px solid blue;
    padding: 2px;
}

table th{
    background-color: #999999;
}

Forename	Surname	Extension

Jim	Carey	1945

Michael	Johnson	1946

<input type="text" id="search" placeholder="  live search"></input>
Comment: there's a plugin to do this, it also handles pagination and sorting too: https://datatables.net/, but to answer your question, you are only comparing against the first td: `$row.find("td:first").text()`
Comment: @Pete Many thanks for this. I'm looking into that plugin. How do I resolve my current code to search the other td's? :)
Comment: I would do it like this: http://jsfiddle.net/L1d7naem/14/
Answer: Its because of the following line:
var id = $row.find("td:first").text();

You are working on the first column of table only and "Carey" is in second column of table
Answer: The behaviour you want can be achieved with the following corrections in the each loop (also note the < 0 in the condition...):
var id = $.map($row.find('td'), function(element) {
    return $(element).text()
}).join(' ');

if (id.indexOf(value) < 0) {
    $row.hide();
} else {
    $row.show();
}

Comment: Do you have a JSFiddle? Can you explain where this should go?
Comment: Sure: http://jsfiddle.net/d04yfx8d/. I append all string values of the tds and apply the filter on it.
Comment: Nice solution : )
Comment: Wow - this is a brilliant solution!!
Answer: Try this. You have to iterate through all columns and once you find any match just escape the loop using the return false; within each() function. Also, indexOf returns -1 if string is not found.

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            $row.find("td").each(function(){
              var id = $(this).text();
              if (id.indexOf(value) < 0) {
                $row.hide();
              }
              else {
                $row.show();
                return false;
              }
            });
        }
    });
});
table, tr, td, th{
    border: 1px solid blue;
    padding: 2px;
}

table th{
    background-color: #999999;
}

Forename	Surname	Extension

Jim	Carey	1945

Michael	Johnson	1946

<input type="text" id="search" placeholder="  live search"></input>
Answer:       $("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $.map($row.find('td'), function(element) {
    return $(element).text()
}).join(' ');

            if (id.indexOf(value) <0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});

http://jsfiddle.net/Lyxex4tp/
Comment: Because the following code do not consider third td into the searching, that's why on typing 19 nothing happens
Comment: With my solution: http://stackoverflow.com/a/39224667/2940802 you can filter for all columns, no matter how many they are...
Comment: kindly accept answer if you thinks its helpful to you :D
Comment: @JekinKalariya you are master :)
Comment: @MayankPandey have a look to my solution. It solves your last problem...
Comment: It's nearly perfect :-D Can you explain why when I type `19` nothing appears? I was expecting both rows to still display. Help? :)
Comment: This seems to resolve it http://jsfiddle.net/L1d7naem/12/ whoever the master is behind this :-D
Comment: You're the master :-D Thank you, Jekin!! :)
Comment: I will do - 20 seconds to go :-)
Comment: @JekinKalariya Out of interest. When I search `Jim Carey` it doesn't show anything : http://jsfiddle.net/Lbod9uj1. Why is this?
Comment: José Antonio Postigo is very right   http://jsfiddle.net/qxks62x9/   this is final one
Answer: Hope this works,
$("#search").on("keyup", function() {
var value = $(this).val();

$("table tr").each(function(index) {
    if (index !== 0) {
        var id = $(this).children().text()
        if (id.indexOf(value) < 0) {
           $(this).hide();
        }else {
            $(this).show();
        }
    }
 });
});

Here is the working fiddle https://jsfiddle.net/44Lux7ze/
Answer: Try this:
$("#search").on("keyup", function() {
var value = $(this).val();

$("table td").each(function() {
    if(value.match($(this).text)) {
        console.log($(this).text());
    }

    else {
        $("table").hide();
    }
});
});

Try matching with all the td elements.

Table - Live Search with jQuery


securing communication between 2 Linux servers on local network for ports only they need access to

Question: I have two Linux servers connected to each other via a cross-connect cable, forming a local network. One of the servers presents a DMZ for the other server (e.g. database server) that must be very secure.
I'm restricting this question to communication between the two servers for ports that only need to be available to these servers (and no one else). Thus, communication between the two servers can be established by:
(1) opening the required port(s) on both servers, and authenticating according to the applications' rules.
(2) disabling IP Tables associated with the NIC cards the cross-connect cable is attached to (on both servers).
Which method is more secure?
In the first case, the needed ports are open to the external world, but protected by user name and password.
In the second case, none of the needed ports are open to the outside world, but since the IP Tables are disabled for the NIC cards associated with the cross-connect cables, essentially all of the ports may be considered to be "open" between the two servers (and so if the server creating the DMZ is compromized, the hacker on the DMZ server could view all ports open using the cross-connect cable).
Any conventional wisdom how to make the communication secure between two servers for ports only these servers need access to?
Answer: Well I'm leaning towards one: Make sure that only connections from that can be made, originate from the server. So you need to add a source option to the iptables rules. Then you still have a defense in place with authentication. The problem is that if there's an application running on the server that can login to the database, there might be a chance that a malicious user finds it out IF he gets access to your server.
What I don't understand is why you would disable iptables on a NIC, it's not because you enable iptables on a NIC that all of a sudden it's accessible by the WAN. On the contrary, you can restrict access with it.
Comment: Thanks Lucas, I think you're mentioning a third method (correct me if I'm wrong): method (1) above that also restricts access to the local network servers only. Is that right? This was what I asked the hosting company to provide for me but they only knew how to do the 2 options above. Maybe I'll try to figure it out myself (let me know if there's any easy way to do this using CSF).
Comment: Well, then I'd go for the second option, you can always add iptables yourself if you have access to the machines. Another option would be installing openvpn and using a vpn between your two machines.
Comment: What do you think about using the method in this link, where instead of 12.345.67.89, I use the local IP address of the OTHER server (e.g. use 192.168.0.1 on server 192.168.0.2; and use 192.168.0.2 on server 192.168.0.1)? http://serverfault.com/questions/155094/csf-firewal-how-does-csf-allow-work
Answer: You should combine the methods and use iptables.
machineone has ip machineone
machinetwo has ip machinetwo
on machineone:
<code>-A INPUT -s machinetwo -d machineone --dport allowedport2 -j ACCEPT
-A INPUT -s machinetwo -d machineone --dport allowedport2 -j ACCEPT
-A INPUT -j DENY
</code>
on machinetwo:
<code>-A INPUT -s machineone -d machinetwo --dport allowedport1 -j ACCEPT
-A INPUT -s machineone -d machinetwo --dport allowedport2 -j ACCEPT
-A INPUT -j DENY
</code>


Google Sheet sparklines to track progress of projects within a fiscal year

Question: I want the cell the sparkline is in to visually represent the fiscal year 7/1/2020-6/30/2021 and to show a bar within it that demonstrates when during that year a project will begin and end.  So, say the project starts on 1/1/2021 and runs through 6/30/2021, the bar would fill in the right half of the cell.
(The bar will be colored to represent whether or not the project is on track, but I have that part figured out).
Where I'm running into trouble is when a project started prior to this fiscal year, or runs beyond it.  In those cases, I just want the bar to be solid across the full cell, to show that the project will be going on all year long.
Here's roughly what I'm looking at: '=SPARKLINE({INT(projectStart)-INT(fiscalYearStart), INT(projectFinish)-INT(fiscalYearFinish)},{"charttype","bar";"color1".....; "max",INT(fiscalYearFinish)-INT(fiscalYearStart)})
Say a project began back in January 2020, the bar isn't starting at the left of the cell - it's starting a bit farther to the right, which I don't like.  I'd like to pretend it started on 7/1/2020 for visualization purposes.
I am tracking a long list of projects across the fiscal year, so it will be apparent if some of them display incorrectly.
Comment: Do you also have some screenshots/a sanitized copy of the sheet?
Comment: It matters to me if the start date falls after 7/1/2020, in which case, I want the bar to start farther to the right in the cell (proportionate to where that start date falls within the fiscal year).
Comment: https://docs.google.com/spreadsheets/d/1qpro5WMBxOljwshoDFXsqC5_XFz-aF8dlfgMxdCINp4/edit#gid=0
Answer: I've taken the liberty of putting the FY start/end dates into cells L7, and M7 respectively.
Your problem can be solved with three colors/segments in the bar:
=SPARKLINE({MAX(G9-L$7,0),H9-G9,MAX(M$7-H9,0)},
{
  "charttype","bar";
  "color1","white";
  "color2",if(E9="Complete","darkgreen",if(today()>H9,"darkred",if(AND(today()>G9,today()<H9,E9="Behind Schedule"),"orange",if(AND(today()>G9,today()<H9),"lightgreen",if(E9="On Track","lightgreen","gray")))));
  "color3","white";
  "max",M$7-L$7
})


DNF of B∧(A∧B∧(A ∨ B ∨ (B∧C)))

Question: if you write
$B∧(A∧B∧(A ∨ B ∨ (B∧C)))$ like
$B ∧ A ∧ B ∧ (A ∨ B ∨ (B ∧ C))$ you can see better the idempotence of $∧ (B∧B = B)$ so:
$$A ∧ B ∧ (A ∨ B ∨ (B ∧ C))$$
My idea was to use distribution inside the parenthesis:
$((A ∨ B) ∨ (B ∧ C))$ equivalent to $(B ∨ A ∨ B) ∧ (C ∨ A ∨ B)$
where you can use idempotence of $∨$ to get:
$$A ∧ B ∧ ((A∨B) ∧ (C ∨ A ∨ B))$$
How do I get from here to
$$(A ∧ B) ∨ (B ∧ C ∧ A) $$
Which rules do I use?
I understand that, when I distribute over ∧ that the conjunction inside the parenthesis changes to a disjunction, but does it matter, which atomic sentence I distribute over which Literal first.
I also know, that after the distribution I can use the idempotence of junctions but I'm again confused about the "correct or most efficient" way to do so.
Thanks!
Comment: I think I understand: I distribute (A ∧ B) over ((A∨B) ∧ (C ∨ A ∨ B)) right?
Comment: That's right. Have you finished it then?
Comment: You should really use the Absorption law
Answer: You can do everything here with:
Absorption
$A \land (A \lor B) = A$
$A \lor (A \land B) = A$
Using Absorption twice you can do:
$A \land B \land (A\lor B \lor (B \land C))= A\land B \land (A\lor B) = A \land B$
In fact, you could have the term $(A\lor B \lor (B \land C)$ immediately be absorbed to do this in a single step:
$A \land B \land (A\lor B \lor (B \land C))= A \land B$
Note that $A \land B$ is already in DNF.
But if the goal is to get to $(A \land B) \lor (B \land C \land A)$, note that we can use Absorption to introduce terms as well:
$A\land B = (A \land B) \lor (A \land B \land C)$
and now it's a simple Commutation to get to your goal.

DNF of B∧(A∧B∧(A ∨ B ∨ (B∧C)))


proof T is a stopping time

Question: let $X(t) $ is a stochastic process and is cadlag and adapted, let $T = \inf\{t:|X(t)| \ge c\}$, proof T is a stopping time.
i.e.$\{T\le t\} \in F_t$
Answer: $\{T \leq t\}^c = \{T > t\} \subset \{|X(s)| < c , \forall s \leq t\}$
Since $X_t$ is right continuous, $|X_t| < c$ implies $\exists \epsilon >0$ such that $|X_{t+\delta}| < c , \forall \delta < \epsilon$. So in this case we have $T > t$. Therefore we see $\{|X(s)| < c , \forall s \leq t\} \subset \{T > t\}$.
So we see $\{T > t\} = \{|X(s)| < c , \forall s \leq t\} \in \mathcal{F}_t$, then its complement $\{T \leq t\} \in \mathcal{F}_t$

proof T is a stopping time


re-reflecting variable after transformation

Question: I have a question about the process of re-reflecting transformed data.  I see many questions and answers around this but I am not sure any answer my specific question.  Many of my variables were negatively skewed and so I reflected those variables before transforming them (either square root or log 10).  I am looking to re-reflect the variables for interpretation purposes and as I go into my primary analyses.  From what I have researched, my understanding is that I could subtract the maximum values for a given variable, plus 1, and it would "re-reflect" the variable to interpreting it in the original scales (e.g. high scores mean high scores).
However, my question is, when I go back and check to make sure the skewness has not changed, I found the M and SD have changed and I am wondering how to understand this, or if I am doing something wrong?
Answer: Despite a hint of numerous threads (although zero references; please give citations) this sounds like a bizarre procedure that may be popular only in certain sub-fields.
I can readily imagine that it's easier (e.g.) to work with $1 - x$ rather than $x$ if $x$ is a left-skewed fraction, but that doesn't seem to be the issue here.
If I understand this correctly, your transformations are of the form (assuming $x \ge 0$)
$\sqrt{x_{\text{max}} - x + 1}$
or
$\log_{10} ({x_{\text{max}} - x + 1}).$
It can be seen that those are reversible transformations, but they seem to me a bad idea. The words ad hoc apply everywhere.

If $x_{\text{max}}$ is empirical, you have no chance of comparability with other studies in the same branch of science. Either other people's $x_{\text{max}}$ is larger, in which case they can't use the same transformation, or it's smaller, in which case it doesn't have the same rationale, or they use their $x_{\text{max}}$, which is different, which leads to loss of comparability. It's poor science to use such arbitrary procedures, regardless of the statistical issues.
If $x_{\text{max}}$ is some definite upper limit, beyond which values are impossible, then there's a partial rationale you can make clear. An example would be that you can't go above all of a total. Odds are you have no such definite upper limit for most variables.
This all seems to be driven by the idea that skewness is a problem that must be solved. Where does that come from? For example, in a regression-like model, there is no requirement that predictor (regressor, explanatory, so-called "independent") variables have any particular marginal distribution or distributional properties. It might often be a good idea to transform because nonlinear relations are involved, but that's a different story.
Adding $1$ is manifestly a fudge so you can take logarithms. For that and other reasons the loss of simple functional form makes interpretation unnecessarily difficult. Back-transforming won't make the beast easier to think about.

If this is done to response (outcome, dependent) variables, please tell us why you think you are doing it. Odds are there's a better way.
P.S. Your concerns about mean (assuming that's what M indicates in your question) and SD are not clear, but in general for any nonlinear transformation, the mean and SD will not satisfy mean of transformed values $=$ transform of mean values, or equivalently for the SD. That's what nonlinearity implies, and the square root and logarithm of $x$, or the variants you have used, don't reduce to any $a + bx$.
UPDATE. Although it may be some distance from what you are doing, there is at least one very useful transformation that reverses sign, namely the reciprocal $1/x$. For example, the reciprocal of a time is often a rate or a kind of speed, and vice versa. So time to complete a task would be indeterminate if the task was not completed, but that maps to $0$ speed. Here if one scale is more useful than the other, then you should stick with that scale and not reverse the transformation unless it's essential substantively or practically.
Comment: I was following transformation steps suggested by Tabachnick & Fidell with regards to social sciences.  You do understand my transformations correctly and your ad hoc comments are very helpful.  I was using the transformations only on independent variables, not the dependent ones.  I will re-consider my methods.
Comment: Thanks for that, but please give a complete reference.
Answer: I agree with Nick Cox generally.
To answer the question, with reflection, mean usually changes (I think maybe not if median=mean, but not sure), but SD should not change when you reflect.
Imagine if you flipped a picture of a mountain 180 degrees, or shifted it a pixel to one side - the peak moves but the slopes are equivalent.
It's very easy to make errors in reflecting and centering syntax (such as leaving the "sqrt" term in the computation when you go to reflect).
Nick's points about transformations are valid and important. On the other hand, reflecting and linear transformations (such as addition and multiplication) are pretty benign unless you forget. Comment, label, and save syntax!
P.S., Tabachnick and Fidell have a bunch of stuff regarding preparatory data analysis. This is a good example: http://onlinelibrary.wiley.com/doi/10.1002/0471264385.wei0205/abstract . Someone scanned and uploaded here: http://people.cehd.tamu.edu/~okwok/epsy651R/Articles/Fidell.pdf .
Comment: I'd exercise a degree of caution with using some of Tabachnick and Fidell's books as statistical references. I don't know this particular book but having read some of their other stuff, they don't get everything right. ("read more than one book" is always a useful principle)


What are intrinsic types in Javascript?

Question: I have recently came across the term intrinsic (data) types in the StackOverflow question related to Javascript, but it was not clearly conveyed what is meant by this term.
So the question is. What are the intrinsic (data) types in Javascript?
Comment: More context would help, like a quote from the article…
Comment: https://google.com/search?q=intrinsic+javascript
Comment: @str This very question is the third result... oh, Ouroboros!
Answer: "Intrinsic" is the way some authors refer to what other authors call "built-in". So, those data types/objects/classes are always there regardless of what environment you're running in.
E.g.:

JavaScript provides intrinsic (or "built-in") objects. They are the Array, Boolean, Date, Error, Function, Global, JSON, Math, Number, Object, RegExp, and String objects.
https://learn.microsoft.com/en-us/scripting/javascript/intrinsic-objects-javascript
Comment: However, those intrinsics are not data types.
Comment: Perhaps the specific article OP read was referring to *built-in strings, numbers* etc. The word "intrinsic" should have the same meaning though.
Comment: Yes, perhaps. But until the OP provides a quote or link to the article, I'll vote to close.
Comment: @deceze And by "environment" you mean "programming language"?
Comment: @Eduard No, I mean *runtime environment*, e.g. browser vs. node.js vs. embedded in some system. As long as it's *Javascript*, these "intrinsic"/"built-in" objects/types/whatever should always be available.
Comment: @deceze Thank you!

What are intrinsic types in Javascript?


Existe alguma possibilidade de realizar uma ação javascript após o fim de um download?

Question: Possuo um link para um PDF no meu site. Gostaria que ao fim do seu download a página habilitasse outro botão.
Mas a questão é: isso é possível apenas com javascript/jquery?
Se sim, como funcionaria?
Comment: só vejo a opção de fazer o download por AJAX, sua ação pode ser executada após conclusão com sucesso da requisição, [essa resposta](http://pt.stackoverflow.com/a/69786/13561) mostra como fazer o download. Lado negativo: nem todas as versões de navegadores suportam essa solução
Comment: Veja essa [resposta](http://http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download "Title"), pode te ajudar...
Answer: Usa o plugin jquery chamado fileDownload, exemplo de uso:
<code>//
//With jquery.fileDownload.js
//custom use with promises
//
$(document).on("click", "a.fileDownloadPromise", function () {
    $.fileDownload($(this).prop('href'))
        .done(function () { alert('File download a success!'); })
        .fail(function () { alert('File download failed!'); });

    return false; //this is critical to stop the click event which will trigger a normal file download
});
</code>
Baixa aqui = https://github.com/johnculviner/jquery.fileDownload
Exemplo funcionando aqui = http://jqueryfiledownload.apphb.com/
Comment: que bacana o plugin lol não conhecia


MySQL 8.0 Reference says MOD() + 1 returns different result from 1 + MOD()

Question: I am trying to learn MySQL reading Official MySQL 8.0 reference/tutorial.
https://dev.mysql.com/doc/refman/8.0/en/date-calculations.html
In the paragraph that explains how you get the January using calculation, it says

A different way to accomplish the same task is to add 1 to get the
  next month after the current one after using the modulo function (MOD)
  to wrap the month value to 0 if it is currently 12:

mysql> SELECT name, birth FROM pet
WHERE MONTH(birth) = MOD(MONTH(CURDATE()), 12) + 1;

MONTH() returns a number between 1 and 12. And MOD(something,12)
  returns a number between 0 and 11. So the addition has to be after the
  MOD(), otherwise we would go from November (11) to January (1).

My question is why the addition should be after MOD()?
I get the same result even if the addition is before 'MOD(MONTH(CURDATE()), 12)' as below.
mysql> SELECT name, birth FROM pet
WHERE MONTH(birth) = 1 + MOD(MONTH(CURDATE()), 12);
am I missing something here?
Answer: The following two expressions are identical, because addition is, by definition, commutative:
MOD(MONTH(CURDATE()), 12) + 1
1 + MOD(MONTH(CURDATE()), 12)

The logic of why either of these works is that when the month of the current date, which is a number between 1 and 12, be 11 or less, the modulus by 12 simply returns that number, and we add one month to it.  In the case of a December month (12), the expression 12 % 12 returns 0, and then we add one to obtain January (1).
Comment: Nice explanation
Comment: Ah, Thank you. I understood now.


Programa que usa input().split(" ") e não roda no Python 3.5.1

Question: Tenho que fazer vários exercícios em Python que os valores de entrada devem ficar na mesma linha e me indicaram o input().split(" "), mas o programa não roda, dá erro. Ex.:
C, Q = input().split(" ")
C = int(C)
Q = int(Q)

if(C==1):
    T=4.00
elif(C==2):
    T=4.50
elif(C==3):
    T=5.00
elif(C==4):
    T=2.00
elif(C==5):
     T=1.50
print("Total: R$ %.2f"%(T*Q))
print

O erro q dá:

Traceback (most recent call last):
    File "C:/Users/ILDA/Desktop/lanche.py", line 1, in
      C, Q = input().split(" ")
  ValueError: not enough values to unpack (expected 2, got 1)
Answer: Isso está acontecendo porque você está tentando fazer um unpacking de uma lista (no código C, Q = input().split(' ')) porém, no seu unpacking vocês está esperando 2 valores ou mais ("C, Q"), mas acredito que você deva estar passando apenas uma palavra na command line (exemplo "foo"), por isso ira subir essa exceção. Veja como o unpacking funciona:
>>> x, y = [1, 2]

>>> x, y
(1, 2)

>>> x, y = [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
need more than 1 value to unpack

A relação com o numero de palavras é porque o código split(" ") ira retornar uma lista de strings a partir de uma determinada string, exemplo:
>>> "foo bar".split(" ")
['foo', 'bar']

>>> "foo".split(" ")
['foo']

Em resumo, o código funciona mas está inseguro da forma como foi feito.
Answer: Aqui são quatro formas que conheço para que você possa colocar um valor um ao lado do outro:
C, Q = input('Digite algo: ')
lista = [C, Q]

Q = int(Q)
C = int(C)
#Primeira forma - Utilizando a vírgula, bem simples.

print(C,Q,'- primeira forma\n')
#Segunda forma - Transformando as variáveis em str e usando o + para unir, simples também.

print(str(C)+str(Q),'- segunda forma\n')
#Terceira forma - Tirando a quebra de linha do print(), é algo bem legal também e as vezes útil.

print(C,end='')
print(Q,'- terceira forma\n')
#Quarta forma - Pegando os valores de uma lista e unindo(transformando em str, ou int no caso.)

print(''.join(lista),'- quarta forma\n')

if(C==1):
    T=4.00
elif(C==2):
    T=4.50
elif(C==3):
    T=5.00
elif(C==4):
    T=2.00
elif(C==5):
    T=1.50
print("Total: R$ %.2f"%(T*Q))

Espero ter ajudado.
E como já foi dito, o split serve para transformar uma string em lista, semelhante ao .join que utilizei acima.
Answer: O único erro que percebi é a saída, pois esse formato é trabalhado em C e não em Python
forma errada
print("Total: R$ %.2f"%(T*Q))
forma Correta
print(f"Total: R$ {(T * Q):.2f}")
Comment: Não é errada, essa sintaxe é perfeitamente válida no Python, embora já não seja mais encorajada o uso.