Alguma maneira de estilizar elemento "pai" com CSS

Question: Olá, existe alguma maneira de selecionar o elemento pai de outro elemento com CSS?
Para ser mais especifico, estou estudando em localhost usando a plataforma de fóruns phpBB3, quando uma mensagem é agradecida ela ganha a classe .bg1 (sendo que o padrão é .bg2).
Ambos .bg1 e bg2 são filhos diretos da classe .pannels, já essa não se altera estando a mensagem agradecida ou não.
Meu objetivo é estilizar a classe .pannels com um background-color:#eaf8e2 apenas se o elemento filho dela for o .bg1 caso seja o .bg2 gostaria de manter a cor #fff no background.

Comment: Estarei utilizando amigo.. Só gostaria de saber se havia alguma maneira de fazer isso em CSS antes de usar jQuery...
Comment: Por que você não faz isso utilizando jquery?
Answer: Não há atualmente nenhuma maneira de selecionar o pai de um elemento em CSS.
Nas especificações CSS, CSS2 e CSS3, não há nada nesse sentido, você vai ter que recorrer a JavaScript (ou jQuery, :has() selector) se você necessita selecionar um elemento pai.

Atualização na Especificação
Houve uma atualização nas especificações dos Seletores de Nível 4, onde a pseudo-class :has() parece ser a sintaxe escolhida para este proposito até o momento (Isto não é uma especificação final e pode sofrer mudanças, ou até mesmo ser removida por completo).
Isso não está disponível em nenhum browser até o momento (17/10/2017):

Can I Use;
MDN web docs;

Com está pseudo-class a solução ao problema proposto na pergunta seria está:
div.pannels:has(> div.bg1)
{
    /* styles serão aplicados ao "div.pannels" elemento que tenham um elemento filho "div.bg1"*/
}

Answer: A isso se dá o nome de parent-selector, sendo que não é possível fazer isso usando CSS3.
Isso já foi proposto, e algo parecido está para ser implementado pelos CSS4* seletores de nível 4, usando-se a marcação $ antes do seletor da hierarquia ao qual o estilo será aplicado.
* segundo a referência, CSS4 não existe, mas sim, seletores de nível 4.
EDIT: correção
Verificando pelo rascunho de especificação da W3C, é possível verificar que o símbolo atualmente proposto é o ! após o seletor a ser estilizado.


Q: Bounded of fourier coefficients of smooth function

Question: $f(x)$ is a smooth function till $k$ order, and piecewise continuous at $k+1$ order,then we have:
$$\left|{\alpha_v}\right|=
\left|\frac{1}{2\pi}\int_{-\pi}^{\pi}{f(x)e^{-ivx}dx}\right|=
\left|\frac{1}{2\pi iv}\int_{-\pi}^{\pi}f'(x)e^{-ivx}dx\right|=
\ldots=
\left|\frac{1}{2\pi}\left(\frac{-i}{v}\right)^{(k+1)}\int_{-\pi}^{\pi}f^{(k+1)}(x)e^{-ivx}dx\right|
$$
Suppose $\frac{B}{2}$ is a upper bounded of $\left|f^{(k+1)}(x)\right|$, how to get $$\left|a_v\right|,\left|b_v\right|\le \frac{B}{v^{k+1}}$$
Comment: Where are you stuck? Because the conclusion seems quite obvious.
Answer: Note that we have
$$\begin{align}
\left|\int_0^{2\pi}f^{(n+1)}(x)\,e^{-i\nu x}\,dx\right|&\le\int_0^{2\pi}\left|f^{(n+1)}(x)\,e^{-i\nu x}\right|\,dx \tag 1\\\\
&=\int_0^{2\pi }|f^{(n+1)}(x)|\,dx \tag2\\\\
&\le \max_{x\in [0,2\pi]}\left(|f^{(n+1)}(x)|\right)\,\int_0^{2\pi}\,(1)\,dx \tag 3\\\\
&=2\pi B
\end{align}$$
In arriving at $(1)$, we invoked the Triangle Inequality for Integrals.
In going from $(1)$ to $(2)$ we used the fact that $|e^{-i\nu x}|=1$.
In going from $(2)$ to $(3)$, we exploited the First Mean Value Theorem for Integrals.


How to start a server on a free port from within a client script?

Question: I have a (python) script that must start a server. The server should be using a free port obviously, and the python script must know this port in order to communicate with it.
Question is, how do I make sure this is the case?

You cannot determine the free port in the python script, and pass it to the server, because in the meanwhile another application could have taken the port.
You cannot let the server choose a port, because then the port is unknown to the script.

This looks like a pretty common problem, so I suppose it has been tackled before.
What is the neatest way to do this?
Answer: Use a list of preferred ports, and try them in the order of preference. This list will of course be known to both client and server.
I suspect you are picking a low port. Since most of the lower ports (close to 1024 or below) already have dedicated applications, you want to avoid these.
If you are using a higher port the likeliness of a collision is negligible, which I think is the common solution.
Comment: How and where should I try these ports?
Comment: Define a list of ports.
When you start the server, iterate through the list and try to listen to every port, until you find a free port.
When you connect to the server, iterate through the list (in the same order) and try to connect to each port. Then verify that you have connected to the correct application with some kind of hand-shake.


Looking for the age of my tuba

Question: I recently purchased an old tuba from an estate auction. No case, just the tarnished beast and mouth piece. By looking up the serial number on it, I am finding that it was built in 1891. I am doubting myself. Did I do this right?
Comment: Valves are not seized, neither are the slides..already taken apart and started cleaning it...I am so surprised of the condition considering the age.
Comment: It certainly looks old, why do you doubt that it's from 1891?
Comment: The middle valve looks like it has seized. Did you buy this to play or as a decoration? (I ask because a friend of mine has a very ancient weathered tuba hanging outside his front door with plants growing out of it.) If you're going to play it, it will need at least a wash out, and may well need the attention of a brass tech to free seized slides/valves/mouthpiece and replace valve felts and water-key corks/springs.
Comment: The dealer marking corroborates: "Brass instruments can be dated with the bell marking. "Emil Wulschner" = 1879-1892; "E. Wulschner & Son" = 1893-1902; "Wulschner-Stewart Music Co." = 1903-1914" ( https://www.brasshistory.net/Wulschner%20History.pdf )
Answer: I suppose you looked up some serial number table such as this one (page 19+):
https://docplayer.net/21438578-A-guide-to-dating-boosey-co-boosey-hawkes-instruments-based-on-serial-number.html
and chose the closes matching date. While this will most likely not give you the exact year of production you probably get a good idea, give or take a few years maybe.
I would not doubt that this tuba was from that time period, it does definitely look the part.
Comment: @PattiLaRockShirley In my town there's a tuba shop called "The Tuba Exchange." The founder, Vince Simonetti, amassed such an eclectic collection of historic instruments that it eventually split off the shop to become a museum. I had a tuba friend at Eastman who drove all the way to NC to explore it with me. Their website says they're "actively acquiring instruments for the collection" and gives Vince's email and phone number; you could get in touch. Whether you sell or not, he's probably one of the most qualified people on earth to figure out its backstory.
Comment: Thank You for your responses. I just had a hard time thinking this could be 130 years old and be in as good of shape as it is. Very minor dents, all slides and valves are great. It is cleaning up nicely from the tarnish also. I am debating on keeping or selling..where would I find a value if I were to sell it eventually? Sorry for all the questions..but I am a euphonium player by nature,but this spoke to me when I saw it.
Comment: @PattiLaRockShirley https://simonettitubacollection.com/

Looking for the age of my tuba


SMTP config environment variable pickupdirectorylocation

Question: I am trying to use an environment variable in SMTP config for the specified pickup directory location. E.g.
<code><smtp deliveryMethod="SpecifiedPickupDirectory" from="email@example.com">
  <specifiedPickupDirectory pickupDirectoryLocation="%TESTFOLDER%"/>
</smtp>

"%TESTFOLDER% = C:\Test
</code>
But getting back an error saying the path must be absolute.
Any ideas how I can get this to work?  Or even if it's possible!
Comment: Are you saying that your config file contains `"%TESTFOLDER%"` as the value?
Comment: why dont you write "c:\test" into the attribute value itself ??
Comment: @Furqan: I guess @BlueChippy wants machine-specific configuration (config include files are better suited for that IMHO).
Comment: @NeilKnight - Yes, I wanted to put the environment variable into the config file, so that when we moved from server to server, the mail pickup would always be correct.  This is because all of our servers have different numbers of HDD's, so the pickup folder is in a different location (mad, I know, but I have to work with it!)
Answer: You can't use it like that.
What you can do is set the name of the env. variable in your app.settings and then set the pickupDirectoryLocation in code using the System.Environment.GetEnvironmentVariable method.
Or loose the env. variable completely and use a config file include (preferred).
Comment: Used the config file include in the end.  Thx


RavenDB - How to Use in Production with Many Inserts?

Question: After hearing about NoSQL for a couple years I finally started playing with RavenDB today in an .Net MVC app (simple blog). Getting the embedded database up and running was pretty quick and painless.
However, I've found that after inserting objects into the document store, they are not always there when the subsequent page refreshes. When I refresh the page they do show up. I read somewhere that this is due to stale indexes.
My question is, how are you supposed to use this in production on a site with inserts happening all the time (example: e-commerce). Isn't this always going to result in stale indexes and unreliable query results?
Comment: Eventual consistency in RavenDB applies only to queries against indexes.  Loading and retrieving documents by ID is always ACID.
Comment: Eventual Consistency allows many applications to function better. Developers from a SQL background often assume it to be a bigger challenge than it really is from a business perspective.
Comment: Wow, maybe I'm missing something, but after using it some more I don't see how this can be used as a primary data store. Sometimes it takes several requests, spanning 15+ seconds, for the query to contain the correct results. This is in a super small document store with 1 doc type, no hierarchy, and 3 documents?!? That's fine if you are mostly read-only and don't need data consistency (e.g. displaying web pages), but I couldn't use this as a real replacement for an RDBMS for something like ecommerce/customer/order data. I tried `WaitForNonStaleResultsAsOfLastWrite` but then my app just hangs.
Comment: When a customer adds something to their account, they don't expect it to be there right away? My employer puts an emphasis on customer experience, not ease of development. In today's day and age most people want things now. That's one of the driving forces behind the whole JavaScript/Asynchronous web...you send smaller bits of data for a faster and more responsive user experience. Can you give me examples where unpredictable Eventual Consistency is acceptable for a business and/or where it is the norm?
Comment: I'm also curious how RavenDB claims to be ACID when it clearly lacks the `C`onsistency part? Isn't "Eventual Consistency" just another way of saying "Currently Inconsistent"?
Answer: Think of what actually happens with a traditional database like SQL Server.

When an item is created, updated, or deleted from a table, any indexes associated with table also have to be updated.
The more indexes you have on a table, the slower your write operations will be.
If you create a new index on an existing table, it isn't used at all until it is fully built.  If no other index can answer a query, then a slow table scan occurs.
If others attempt to query from an existing index while it is being modified, the reader will block until the modification is complete, because of the requirement for Consistency being higher priority than Availability.
This can often lead to slow reads, timeouts, and deadlocks.

The NoSQL concept of "Eventual Consistency" is designed to alleviate these concerns.  It is optimized reads by prioritizing Availability higher than Consistency.  RavenDB is not unique in this regard, but it is somewhat special in that it still has the ability to be consistent.  If you are retrieving single document, such as reviewing an order or an end user viewing their profile, these operations are ACID compliant, and are not affected by the "eventual consistency" design.
To understand "eventual consistency", think about a typical user looking at a list of products on your web site.  At the same time, the sales staff of your company is modifying the catalog, adding new products, changing prices, etc.  One could argue that it's probably not super important that the list be fully consistent with these changes.  After all, a user visiting the site a couple of seconds earlier would have received data without the changes anyway.  The most important thing is to deliver product results quickly.  Blocking the query because a write was in progress would mean a slower response time to the customer, and thus a poorer experience on your web site, and perhaps a lost sale.
So, in RavenDB:

Writes occur against the document store.
Single Load operations go directly to the document store.
Queries occur against the index store
As documents are being written, data is being copied from the document store to the index store, for those indexes that are already defined.
At any time you query an index, you will get whatever is already in that index, regardless of the state of the copying that's going on in the background.  This is why sometimes indexes are "stale".
If you query without specifying an index, and Raven needs a new index to answer your query, it will start building an index on the fly and return you some of those results right away.  It only blocks long enough to give you one page of results.  It then continues building the index in the background so next time you query you will have more data available.

So now lets give an example that shows the down side to this approach.

A sales person goes to a "products list" page that is sorted alphabetically.
On the first page, they see that "Apples" aren't currently being sold.
So they click "add product", and go to a new page where they enter "Apples".
They are then returned to the "products list" page and they still don't see any Apples because the index is stale.  WTF - right?

Addressing this problem requires the understanding that not all viewers of data should be considered equal.  That particular sales person might demand to see the newly added product, but a customer isn't going to know or care about it with the same level of urgency.
So on the "products list" page that the sales person is viewing, you might do something like:
var results = session.Query<Product>()
                     .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
                     .OrderBy(x=> x.Name)
                     .Skip((pageNumber-1) * pageSize).Take(pageSize);

While on the customer's view of the catalog, you would not want to add that customization line.
If you wanted to get super precise, you could use a slightly more optimized strategy:

When going back from the "add product" page to the "list products" page, pass along the ProductID that was just added.
Just before you query on that page, if the ProductID was passed in then change your query code to:
var product = session.Load(productId);
var etag = session.Advanced.GetEtagFor(product);

var results = session.Query<Product>()
                 .Customize(x => x.WaitForNonStaleResultsAsOf(etag))
                 .OrderBy(x=> x.Name)
                 .Skip((pageNumber-1) * pageSize).Take(pageSize);

This will ensure that you only wait as long as absolutely necessary to get just that one product's changes included in the results list along with the other results from the index.
You could optimize this slightly by passing the etag back instead of the ProductId, but that might be less reusable from other places in your application.

But do keep in mind that if the list is sorted alphabetically, and we added "Plums" instead of "Apples", then you might not have seen these results instantly anyway.  By the time the user had skipped to the page that includes that product, it would likely have been there already.
Comment: A shopping cart would exist in entirety in a single document.  You would just load it.  It seems you have a common mental block that comes from working with relational databases.  RavenDB works best with *structured* data.  A cart and its line items, or an order and its line items, are held together in a single document.  In DDD terms, the document represents the entire "Aggregate Entity", inclusive of all non-aggregate entities and value objects.
Comment: I haven't even been that far. I stopped when it was taking tens of seconds to refresh the index for the small document set I described. I do have a question though. Let's say on a shopping cart page, how do you load all the items. In RDBMS you hold on to the cart id and query off that. To use Load, don't I need to know the id for every line item to do what you are prescribing?
Comment: Matt, that makes a lot more sense.
Comment: Matt , One of the best explanation I read regarding consistency of the database.  What I understand, the query result depends on the  priority of the task(business function) and the application can be designed accordingly .
Comment: I had tried the `WaitForNonStaleResultsAsOfLastWrite` and my MVC page timed out. This was in a database containing 3 "documents" with 3 fields each (ID, Name, Description). Are there known performance issues with using the Embedded version with it's data store in the App_Data directory? It might be great for web, category, product type data, but I can't see doing anything like inventory, carts, orders, users, or roles in RavenDB.
Comment: No, there shouldn't be any performance issues with that.  There must be something else going on.  You may want to ask for help over on the [RavenDB Google Group](http://groups.google.com/group/ravendb) or raise a [support issue](http://ravendb.net/support).  Plenty of people use RavenDB for exactly what you are describing and it works perfectly.  Those type of operations (inventory, carts, etc.) would be done with Load, not Query.  If you are using Query to pull inventory items, then you need to rethink your design.
Answer: You are running into stale queries.
That is a by design part of RavenDB. You need to make distinction between queries (BASE) and loading by id (ACID).
Comment: So how is RavenDB commonly used for development? I cant reliably save a document to the repository and then immediately return it back as part of a list (common in CRUD scaffold for MVC; create then return to list view). So are we supposed to use RDBMS for the important stuff like users, carts, orders, then use Raven for searching site content, basically as a lucene replacement?
Comment: @Sam You can use RavenDB for all the above. For the "important" stuff you can use [WaitForNonStaleResuls](http://ravendb.net/docs/2.0/client-api/querying/stale-indexes#explicitly-waiting-for-non-stale-results) if you hit an index. However, for users and carts you could probably load by Id in most cases.


Question about permutation and series (are permutation always finite ? what are their impact on series ?)

Question: Let $\sigma :\mathbb N\longrightarrow \mathbb N$. We denote the support of $\sigma $ by $$supp(\sigma )=\{n\in\mathbb N\mid \sigma (n)\neq n\}.$$
Q1) Is the support always finite ? i.e. is for example $$\sigma (k)=\begin{cases}k+1&k\in2\mathbb N\\ k-1&k\in2\mathbb N+1\end{cases},$$
consider as a permutation ?
I heard that not, so I want to be sure.
Q2) I know that if a series $\sum_{n\in\mathbb N}u_n$ is not absolument convergent, then for all permutation $\sigma $ we have that $$\sum_{n\in\mathbb N}u_n\neq \sum_{n\in\mathbb N}u_{\sigma (n)}.$$
Is it really for all permutation ? For example, if I take $\sigma =(12345)$ (or even $\sigma =(12)$), will we really have $$\sum_{n\in\mathbb N^*}\frac{(-1)^n}{n}\neq \sum_{n\in\mathbb N^*}\frac{(-1)^{\sigma (n)}}{\sigma (n)}\ \ ?$$
I know that we can regroup terms to get that the series $\sum_{n\in\mathbb N^*}\frac{(-1)^n}{n}$ divergent, but if $\sum_{n\in\mathbb N^*}\frac{(-1)^{\sigma (n)}}{\sigma (n)}$ is convergent and $supp(\sigma )$ finite, will we really have $$\sum_{n\in\mathbb N^*}\frac{(-1)^{\sigma (n)}}{\sigma (n)}\neq \sum_{n\in\mathbb N^*}\frac{(-1)^n}{n}\ \ \ ?$$
Q3) Same question if $supp(\sigma )$ is infinite (if it's possible) and $\sum_{n\in\mathbb N^*}\frac{(-1)^{\sigma (n)}}{\sigma (n)}$ convergent.
I hope my question is clear enough.
Answer: If $supp(\sigma )$ is finite (and the series convergent but not absolutely convergent), you will always have $$\sum_{n=1}^\infty u_{n}=\sum_{n=1}^\infty u_{\sigma (n)}.$$
Indeed, let $M=\max supp(\sigma )$. Then,
$$\sum_{n=1}^M u_n=\sum_{n=1}^M u_{\sigma (n)}.$$
Since $u_n=u_{\sigma (n)}$ for all $n>M$, the claim follow.
Edit
If $|supp(\sigma )|=+\infty $, you can't say anything a priori. For example with $u_n=\frac{(-1)^n}{n}$ and the permutation $\sigma =(12)(34)(56)(78)...$ the sum will not change, whereas if you take the permutation that group even and odd $n$, the sum will not converge. After there is other combinaison that will change the sum.
Comment: Nice, it's what I wanted to know. And if $supp(\sigma )$ is infinite ? Will we have $\sum_{n=1}^\infty u_n\neq \sum_{n=1}^\infty u_{\sigma (n)}$ ? Or we can have equality ?
Comment: I edited my answer


Como atualizar uma função do helper com ajax

Question: Olá, preciso de ajuda que deu um nó na cabeça, eu estou trabalhando com codeigniter, criei três funções no meu helper consultando o banco de dados, e exibo um resultado em divs com as quantidades de registros, eu chamo essas três funções do helper em todos os controles, só que agora preciso utilizar ajax para atualizar essas funções em tempo real, ai que travei, porque não sei como chamar essas funções do helper para ser atualizadas em tempo real. Se puderem me ajudar me dando uma luz, agradeço. Meu código está assim:
meu helper chamado: funcao_helper:
 function np()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
            //carrega o banco de dados
            $CI->load->model('dashboard_model');

            $np = $CI->dashboard_model->contarNotasPendentes();

           return $np;//retorna a quantidade de registros
       }

       function vf()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
            //carrega o banco de dados
            $CI->load->model('dashboard_model');
            $vf =  $CI->dashboard_model->contarVendasFuncionarios();

           return $vf; //retorna a quantidade de registros
       }

       function pd()
       {
            // Obter uma referência ao objeto do controlador
            $CI = get_instance();
           //carrega o banco de dados
            $CI->load->model('dashboard_model');
            $pd =  $CI->dashboard_model->contarNovosPedidos();

           return $pd; //retorna a quantidade de registros
       }

Meu controller Principal:
class Principal extends CI_Controller {

    public function index()
    {
          //Notificações gerais do painel
          $data['np'] = np();//contar NF pendentes
          $data['pd'] = pd();//contar os pedidos novos
          $data['vf'] = vf();//contar vendas
          $total =  pd() + vf() + np();//somar todos
          $data['total'] =  $total;//exibir o valor total

          $this->load->view('admin/template/home', $data);
    }

}

Minha view:

          <?php if (isset($total))  { if($total != "0")  {   echo $total; } } ?>

          if($pd != "0")  { ?>

          <a href="<?php echo base_url() ?>" class="dropdown-item">
            <?php echo $pd ?> Novo Pedido

          <?php } ?>

          if($vf != "0")  { ?>

          <a href="<?php echo base_url('') ?>" class="dropdown-item">
            <?php  echo $vf; ?> Venda

          <?php  } ?>

          if($np != "0")  { ?>

            <?php echo $np ?> Nf Pendente

          <?php } ?>

Dai tentei um ajax assim pra atualizar a função pd:

Mas até agora nada, se puderem me ajudar agradeço.
Comment: No console apresenta algum erro?
Comment: Não, mas não exibe nada.
Comment: Acho interessante ativar os erros php `ini_set("display_errors", 1);` no começo do código, pode ser que esteja desabilitado no servidor
Comment: agora ele apareceu no console no javascript  404 Page Not FoundThe page you requested was not found., acho que não está achando meu helper
Answer: Bom depois de mto quebrar a cabeça conseguir resolver, vou deixar minha resposta caso alguém precise no futuro.
//Atualizar Notificações de Pedidos
        var atualizaNotificacaoPedido = function (tempoParaChecarNovamenteEmSegundos) {

              $.ajax({
                  type:"GET",
                  url:"http://[::1]/principal/pedido",
                  dataType: "json",
                  success: function (resposta){

                    if (resposta.erro == 0) {

                       $('.pd').html(resposta.listar_servico);
                       setTimeout(function() { atualizaNotificacaoPedido(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 40000);

                    } else{

                       alert('Erro ao trazer serviços');
                       setTimeout(function() { atualizaNotificacaoPedido(tempoParaChecarNovamenteEmSegundos); }, tempoParaChecarNovamenteEmSegundos * 40000);
                    }

                  },
                  error:function(){
                      console.log(resposta);
                      alert('Erro ao trazer serviços.');
                  }
             });
      }

      atualizaNotificacaoPedido(40000);

Dai no meu controller criei uma reposta em json para puxar meu select do banco ficando assim:
 public function pedido()
    {
        $listar_servico = $this->dashboard_model->contarNovosPedidos();

        if ($listar_servico) {

                $retorno['erro'] = 0;
                $retorno['msg']  = 'Pedido consultado com sucesso';
                $retorno['listar_servico']  = $listar_servico;

                header('Content-Type: application/json');
                echo json_encode($retorno);
                exit;

            } else {

                $retorno['erro'] = 60;
                $retorno['msg']  = 'Erro';

                header('Content-Type: application/json');
                echo json_encode($retorno);
                exit;
        }

    }

E minha view ficou assim:
 if($pd != "0")  { ?>

          <a href="<?php echo base_url() ?>" class="dropdown-item">
             Novo Pedido

      <?php } ?>

A única coisa que ficou ainda desregulada para mim é controlar o tempo no ajax que está mto rapido, já tentei colocar, 40000 e ainda assim fica mto rapido, mas se eu conseguir ajustar arrumo aqui tb. vlw


D8: Replacing Contact Form Title With Label

Question: I've searched around for this answer but to no avail.
All I want to do is with any contact form I create I want to replace its default title (usually "contact") with the form's label.
So instead of {{ title }} something like {{page.label}}.
I need more descriptive titles for my forms.
Answer: <code>{{ page['#title'] }}</code> seems to work consistently and accesses the form's label.


CLAMAV on Centos Mail Server: Can't connect to UNIX socket clamd.sock

Question: In my Centos 6.4 server, I am using Postfix and Dovecot with Amavis/ClamAV filter. Lately I have been trying to solve my spam problem(only occurs in Gmail and Hotmail) so I've been tailing logs.
Though I can send and receive e-mails, I have realized that Clamav causes error in /var/log/maillog so I think perhaps it can help my spam problem if I can solve this error.
That's the main error, I think the rest of the process goes allright.
(!)connect to /var/run/clamav/clamd.sock failed, attempt #1: Can't connect to UNIX socket /var/run/clamav/clamd.sock: No such file or directory

Test information:
XX.XX.XX.XX: Sender Client IP (This time Thunderbird)
YY.YY.YY.YY: My mail server IP
email@example.com: Sender address
firstname.lastname@example.com: Receiver address (This time Gmail)

When I send an e-mail from a mail account in my server, Here's how /var/log/maillog looks:
postfix[3422]: warning: XX.XX.XX.XX: hostname XX.XX.XX.XX.static.ttnet.com.tr verification failed: Name or service not known
postfix[3422]: connect from unknown[XX.XX.XX.XX]
postfix[3422]: setting up TLS connection from unknown[XX.XX.XX.XX]
postfix[3422]: Anonymous TLS connection established from unknown[XX.XX.XX.XX]: TLSv1 with cipher DHE-RSA-CAMELLIA256-SHA (256/256 bits)
postfix[3422]: D894AC1E61: client=unknown[XX.XX.XX.XX], sasl_method=PLAIN, firstname.lastname@example.com
postfix/cleanup[3429]: D894AC1E61: message-id=<firstname.lastname@example.com>
postfix/qmgr[1310]: D894AC1E61: from=<firstname.lastname@example.com>, size=862, nrcpt=1 (queue active)
amavis[3326]: (03326-01) ESMTP::10024 /var/amavis/tmp/amavis-20131030T102202-03326-IY7b8Pdi: <firstname.lastname@example.com> -> <firstname.lastname@example.com> SIZE=862 Received: from host.mydomain.com ([127.0.0.1]) by localhost (mydomain.com [127.0.0.1]) (amavisd-new, port 10024) with ESMTP for <email@example.com>; Wed, 30 Oct 2013 10:22:02 +0000 (UTC)
amavis[3326]: (03326-01) Checking: MemHkAhbAuqt [XX.XX.XX.XX] <firstname.lastname@example.com> -> <email@example.com>
amavis[3326]: (03326-01) Open relay? Nonlocal recips but not originating: email@example.com
amavis[3326]: (03326-01) (!)connect to /var/run/clamav/clamd.sock failed, attempt #1: Can't connect to UNIX socket /var/run/clamav/clamd.sock: 2
amavis[3326]: (03326-01) ClamAV-clamd: All attempts (1) failed connecting to /var/run/clamav/clamd.sock, retrying (1)
postfix[3422]: disconnect from unknown[XX.XX.XX.XX]
amavis[3326]: (03326-01) (!)connect to /var/run/clamav/clamd.sock failed, attempt #1: Can't connect to UNIX socket /var/run/clamav/clamd.sock: No such file or directory
amavis[3326]: (03326-01) (!)ClamAV-clamd: All attempts (1) failed connecting to /var/run/clamav/clamd.sock, retrying (2)
amavis[3326]: (03326-01) (!)connect to /var/run/clamav/clamd.sock failed, attempt #1: Can't connect to UNIX socket /var/run/clamav/clamd.sock: No such file or directory
amavis[3326]: (03326-01) (!)ClamAV-clamd av-scanner FAILED: run_av error: Too many retries to talk to /var/run/clamav/clamd.sock (All attempts (1) failed connecting to /var/run/clamav/clamd.sock) at (eval 113) line 600.\n
amavis[3326]: (03326-01) (!)WARN: all primary virus scanners failed, considering backups
postfix[3433]: connect from unknown[127.0.0.1]
postfix[3433]: E52C1C1E71: client=unknown[127.0.0.1]
postfix/cleanup[3429]: E52C1C1E71: message-id=<email@example.com>
postfix/qmgr[1310]: E52C1C1E71: from=<firstname.lastname@example.com>, size=1279, nrcpt=1 (queue active)
amavis[3326]: (03326-01) FWD from <firstname.lastname@example.com> -> <email@example.com>,BODY=7BIT 250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as E52C1C1E71
amavis[3326]: (03326-01) Passed CLEAN {RelayedOpenRelay}, [XX.XX.XX.XX]:33926 [XX.XX.XX.XX] <firstname.lastname@example.com> -> <firstname.lastname@example.com>, Message-ID: <firstname.lastname@example.com>, mail_id: MemHkAhbAuqt, Hits: 0.106, size: 862, queued_as: E52C1C1E71, 14736 ms
postfix/smtp[3430]: D894AC1E61: to=<email@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=15, delays=0.53/0.01/0.01/15, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as E52C1C1E71)
postfix/qmgr[1310]: D894AC1E61: removed
amavis[3326]: (03326-01) extra modules loaded: unicore/lib/gc_sc/Digit.pl, unicore/lib/gc_sc/SpacePer.pl
postfix/smtp[3436]: E52C1C1E71: to=<email@example.com>, relay=gmail-smtp-in.l.google.com[18.104.22.168]:25, delay=1.2, delays=0.01/0.02/0.68/0.5, dsn=2.0.0, status=sent (250 2.0.0 OK 1383128540 x12si3704513igx.15 - gsmtp)
postfix/qmgr[1310]: E52C1C1E71: removed
dovecot: imap-login: Login: user=<firstname.lastname@example.com>, method=PLAIN, rip=::1, lip=::1, mpid=3439, secured
dovecot: imap(email@example.com): Disconnected: Logged out bytes=90/777

And here's the source code of received mail in Gmail:
Delivered-To: firstname.lastname@example.com
Received: by 10.68.54.102 with SMTP id i6csp217498pbp;
        Wed, 30 Oct 2013 03:22:20 -0700 (PDT)
X-Received: by 10.50.6.99 with SMTP id z3mr1702938igz.27.1383128540254;
        Wed, 30 Oct 2013 03:22:20 -0700 (PDT)
Return-Path: <email@example.com>
Received: from host.mydomain.com (mydomain.com. [YY.YY.YY.YY])
        by mx.google.com with ESMTPS id x12si3704513igx.15.2013.10.30.03.22.19
        for <firstname.lastname@example.com>
        (version=TLSv1 cipher=RC4-SHA bits=128/128);
        Wed, 30 Oct 2013 03:22:20 -0700 (PDT)
Received-SPF: pass (google.com: domain of email@example.com designates YY.YY.YY.YY as permitted sender) client-ip=YY.YY.YY.YY;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of email@example.com designates YY.YY.YY.YY as permitted sender) email@example.com
Received: from localhost (unknown [127.0.0.1])
    by host.mydomain.com (Postfix) with ESMTP id E52C1C1E71
    for <firstname.lastname@example.com>; Wed, 30 Oct 2013 10:22:16 +0000 (UTC)
X-Virus-Scanned: amavisd-new at mydomain.com
Received: from host.mydomain.com ([127.0.0.1])
    by localhost (mydomain.com [127.0.0.1]) (amavisd-new, port 10024)
    with ESMTP id MemHkAhbAuqt for <firstname.lastname@example.com>;
    Wed, 30 Oct 2013 10:22:02 +0000 (UTC)
Received: from [192.168.2.15] (unknown [XX.XX.XX.XX])
    (using TLSv1 with cipher DHE-RSA-CAMELLIA256-SHA (256/256 bits))
    (No client certificate requested)
    by host.mydomain.com (Postfix) with ESMTPSA id D894AC1E61
    for <firstname.lastname@example.com>; Wed, 30 Oct 2013 10:22:01 +0000 (UTC)
Message-ID: <firstname.lastname@example.com>
Date: Wed, 30 Oct 2013 12:21:47 +0200
From: mydomain Development Base <firstname.lastname@example.com>
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.0
MIME-Version: 1.0
To: email@example.com
Subject: That's the mail
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit

    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

    What's up?

Though it all seems fine and have scanned by amavisd-new, it goes to spam. I don't necessarily ask why but if it's related to not being scanned correctly, I need to fix this issue.
And here's how I use CLAMAV in /etc/amavisd.conf file:
['ClamAV-clamd',
  \&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd.sock"],
  qr/\bOK$/m, qr/\bFOUND$/m,
  qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],

The file clamd.sock is not exist under /var/run/clamav/ dir, and this dir is chowned by clamav user and group (the service doesn't start when it's not). I don't know if it's a dynamic file that is being created and deleted on runtime but I don't think there's any issue with permissions, perhaps some process or service is missing to create the file.
Any ideas? Thanks in advance.
Comment: You need to configure amavisd or clamd to set up that sock (socket, and it is a run time creation) so that amavis can talk to it!
Comment: @NickW Hi, please send it as an answer so that I can accept. I had it configured in /etc/amavisd.conf but it was set to /var/run/clamav/clamd (not clamd.sock) in /etc/clamd.conf. After setting both the same value, the problem is now fixed. Thanks!
Answer: You need to make sure that you have clamd configured to provide the socket in the same way in both amavisd (in /etc/amavisd.conf) and clamd (/etc/clamd.conf), otherwise they will not be able to communicate.
Answer: This error can appear when the machine does not have enough RAM, seemingly 1GB is not enough on Debian 11.


Hazard function and survival analysis

Question: I have a function $\lambda(t)$ which returns the instant probability of dying at a time $t$. I'd like to compute the function $F(t)$ which returns the probability of being dead at a certain time $t$.
Using some reliability theory, I have obtained the following relation:
$$
F(t) = 1-e^{- \int_{0}^{t} \lambda(u) \,du }
$$
But when I do a numerical application I obtain strange results:
Here is the shape of the function $\lambda(t)$:

It can be seen that just after 60 seconds, the probability of dying is above $0.2$. But then when I try to compute the probability of beeing dead at $t=100s$, I obtain:
$$
F(t) = 1-e^{- \int_{0}^{100} \lambda(u) \,du }=0.051
$$
What am I doing wrong?
Comment: You mistakenly interpret the values of $\lambda$ as probabilities.  They are not: when multiplied by times, they will be the negative logarithms of probabilities.  Notice that the area under this curve is approximately that of a triangle of width $60.5-60$ and height $0.22,$ roughly equal to $1/2\times 0.5\times 0.22=0.055.$ This is small, so its exponential is $e^{-0.055}\approx 1 - 0.055,$ very close to $1-0.051.$  As far as doing anything wrong, consider how strange this functional shape for $\lambda$ is! Death can occur essentially only between 60 and 60.5 seconds, never before or after.
Comment: (Continued) Consequently, I would like to suggest that the most productive way to pursue this problem would be to discuss how you obtained $\lambda,$ because it looks like your calculation is correct.
Comment: The plotted curve is the probability of death at any given time (as you said in this case, death can only occur around t=60sec and is very small everywhere else). What I probably did wrong is to call this probability function $\lambda$ which is the symbol used for the hazard function. How can I convert this probability function into a hazard one? Or simply, how can I obtain the probability of being dead at $t=100s$ for example?
Comment: The probability that death occurs *at* an exact instant will be zero (consider a very small interval around that instant with small enough that the truncated distribution over that interval is close to uniform. Divide it into say 5 sub-intervals, and then focus on the one containing your specific point; divide in similar fashion again and again until the probability of being in the 'right' interval is below any chosen $\epsilon>0$). We can speak of the death-rate at an instant, but the probability is 0.
Comment: Your results might be consistent with a cure model, in which only a fraction of those at risk for an event ever experience it. See [this page](https://stats.stackexchange.com/q/300733/28500) among others on this site. If that doesn't describe your situation, then there is some problem in how you obtained $\lambda (t)$.
Comment: What are the units of $\lambda$? Are they the rate of death per second? Or are they possibly using some other units?
Answer: Answer
Given that your $\lambda(t)$ actually represents the instantaneous probability to die at time $t$ (the hazard), your function $F(t)$ computes the probability to die before a certain time $t$. In other words, $F(t)$ is the cumulative distribution function (CDF) of the time of death.
Following the discussion in the comments, your function represents the probability density function (pdf) $f(t)$ of time of death. From there you can compute the CDF as
$$
F(t) = \int_0^T f(u) du
$$
with $T$ either infinity or the largest possible time.
Some Background on Survival Models / Distributions
The following derivations are largely based on this material
Survival models can be based on the hazard rate $\lambda(t)$ (the instantaneous probability to die at time $t$) or on the distribution of times of death $f(t)$ (which is the pdf of the random variable time of death).
\begin{align}
 \text{Hazard function}   && \lambda(t) &= \underset{\mathrm{d}t \rightarrow 0}{\lim} \frac{P(t \leq T \leq t + \mathrm{d}t | T\geq t)}{\mathrm{d}t} = \frac{f(t)}{S(t)} = - \frac{\mathrm{d}}{\mathrm{d}t}\ln \big[S(t)\big] \nonumber \\
 \text{Cumulative Hazard} && M(t) &= \int_0^t \lambda(x) \mathrm{d}x \label{eq:cum_hazard} \\
 \text{pdf}               && f(t) &= \lambda(t) S(t) \nonumber \\
 \text{cdf}               && F(t) &= P(T < t) = \int_{0}^t f(x)  \mathrm{d}x \nonumber \\
 \text{Survival function} && S(t) &= 1- F(t) = \int_t^{\omega}f(x) \mathrm{d}x = e^{-M(t)} \label{eq:surv}\\
 \text{Life Expectancy}   && e(t) &= \frac{1}{S(t)} \int_t^\omega S(x) \mathrm{d}x \quad \text{with } e(0) = \int_0^\omega S(x) \mathrm{d}x \quad \text{since} \quad S(0) = 1 \label{eq:lexp}
\end{align}
where $\omega$ denotes the highest age.
Answer: If your plot is intended to be the probability density function for an event over time, $f(t)$ in the terminology of the answer from @Martin Georg Haas, then you technically have an improper distribution as it does not integrate to 1 over its support. Your numerical evaluation of the integral, consistent with $F(\infty) = 0.051$, agrees well with the area of a roughly corresponding isosceles triangle having height 0.2 and base 0.5.
If that's what you intend, you have a cure model in which about 95% of the cases never experience the event: $$S(\infty)= 1 - 0.051=0.949.$$ If that matches your data, you haven't done anything "wrong."
If that's not what you intend and all individuals eventually experience the event, then you have done something wrong and you need to scale your $f(t)$ by a factor of about 20 so that it integrates to $F(\infty)=1$.

Hazard function and survival analysis


Modulation in the violin solo Bach's Laudamus Te

Question: I'm trying to decide the key changes in the Laudamus Te of the Mass in B minor (J.-S. Bach).

I think the key in the 8th measure is B minor (the Laudamus Te is in A Major), but I'm not sure what happens in the 9th measure.
It seems to be similar one tone lower, but is not in A minor.
F, C and G are sharp, so it looks like A major, but what to say about the sharp G on the last beat?
Are there modulations that I'm not seeing?
Answer: First of all the last G is natural not sharp because any accidental in the measure stays unless otherwise noted.
It seems like the harmonic rhythm is every two beats (i.e. the chords change every two beats). From the two measures you've shown  we can see the chords created are:

F#  Bm7  | E  A7

The first part can be interpreted as V to i7 in B minor and the second part can be interpreted as V to I7  in A major. Without seeing more of the piece I cannot confirm if the piece actually modulates or if something else is going on. If the next measure uses chords more accustom to A minor in the next measure I would say it has modulated if it doesn't then probably not.   For example I can see an interesting sequence coming out of this progression as all the chord are a 4th up/5th down from another.
Comment: Yeah sorry meant sharp not flat. How can you be sure about F# without a E# in the first two beats?
Comment: @PierreArlaud An F# chord is made up of the notes F#, A#, and  C#. If there was an E# then it could be interpreted as a minor 7th of an F# chord making it an F#7, but it is not necessary.
Comment: @PierreArlaud There are no flats in the two measures you posted and B is natural in both.
Comment: Sorry I'm at a point of high confusion tonight apparently. I meant that D is sharp in F# and here it's natural.
Comment: @PierreArlaud when I say the chord created is F# I mean the harmony seems to infer F#. It does not mean that every note in that section is in the chord or from the key of F#.
Comment: @Dom when you say Am7, don't you mean A7? The C is sharp, so it's a major chord. Of course, the following chord is almost certainly a D major, so if there's any modulation taking place here, it's probably to D major. (Though without the additional context, it's hard to tell where it might go next).
Answer: I'd call it more F♯7 - Bm | E7 - A7, treated as V7 of ii - ii - V7 - V7 of IV. (Notice that G♮/G♯ never shows up in m.8.)
Bach is actually articulating every quaver, but using these as elaborations of the main harmonic rhythm, which is, as Dom says, every minim.
The pattern of the sequence at the quaver is | (m. 8 in "B minor") vii° - i - V7-6 - V - i - vii°6 - i6 - i |
(m.9 in A Major) V7 - (iii) - V6-5 - V7 - I - vii°6 - I6 - I7 |.
The 7th over the tonic in the 2nd half of the m.8 is thus a conventionally prepared and resolved suspension holding over the seventh, not a chord tone of the tonic. The F♯m (iii) chord I've marked in parentheses in m.9 almost acts more as a passing chord under the held E than independently, but it cancels F♯'s significance as V of ii.
What Bach has done in m.9 is intensify the sequential pattern by changing the accompaniment in the first half of the bar to

recast the preceding bar as V of ii - ii (rather than V-I in B minor), and
add a touch of ambiguity on the 4th quaver - in m.8, the D in analogous spot in the melody is a too-early resolution of the suspended 7th (given that it plays against C♯); in m.9, the C♯ that follows the suspended D could very well be a deceptive resolution (vi6), as the B that follows it is the only B in the harmony and acts more like a lower auxiliary -

and, in the 2nd half, by foregoing the suspension, instead dropping the turn motif a whole tone to undercut A as tonic and cast it as V of IV. You know that the chain of falling fifths is going to continue.
That's the beauty of Bach's music. This passage really exists on 3 levels:

as 2 bars articulating a standard cadential pattern in A Major (V7 of ii - ii - V7 - I?), where the pattern is broken enough at the end to reinterpret the tonic as a dominant;
as a falling fifth sequence on the minims; and
by means of very subtle voice leading, as an active movement by quavers that melds the bars together through anticipation and restatement of harmonies (2nd and 6th quavers of m.8, 6th quaver of m.9); by changing the function of a root (2nd quaver and last quaver of m.9); and by intensifying the movement through ambiguous voice leading (4th and 7th quavers of m.9).


Linear and continuous applications (normed space)

Question: Hello can you help me with this exercise i don't ununderstand how I must do
We provide the vectorial space $\mathbb{R}^2$ with the norm
$$
\|(x,y)\|= \sqrt{\frac{x^2}{16}+\frac{y^2}{9}}
$$
prove that $u(x,y)=\sqrt{2}x+y$ is linear and continuous on $\mathbb{R}^2$
the linearity is clear but how to do for the continuity?
I must prove that
$$
\|u\|\leq c
$$
where $$\|u\|= \sup_{\|(x,y)\|\leq 1} \|u(x,y)\|$$ how to do?
Thank you for your help
Comment: I don't believe that function is linear. Could it be $u(x,y) = \sqrt{2} \; x + y$ instead?
Comment: you are write i don't see it clearly from 1h I will correct it
Comment: You should give more information about where you are stuck and what you have tried. Do you know how to write down the definition of linearity and continuity?
Comment: For linearity check $u(x_1,y_1)+u(x_2,y_2)=u(x_1+x_2, y_1+y_2)$. For continuity, since this is a linear functional, check if there exists a $c>0$ such that $\|u(x,y)\| \leq c \|(x,y)\|$.
Comment: I don't know how I can find $||(x,y)||$ from $||u||
Answer: Hint:
$\|u(x,y)\|=\|\sqrt{2}x+y\|=|\sqrt{2}x+y|$ (the standard norm on $\mathbb{R}$).
So try to maximize the function $f(x,y)=|\sqrt{2}x+y|$ over the elliptical region $\frac{x^2}{16}+\frac{y^2}{4} \leq 1$.
Comment: nothing new I write this in my question I just don't understand how I must do?
Comment: @PolineSandra you have just written symbols for the norm so it was not clear if you could interpret them to the statement I have mentioned in my response. To help you further: in order to maximize this, think for which values of $c$  will the line   $\sqrt{2}x+y=c$ be tangent to the ellipse. The tangency will help you determine the max, min values.
Comment: I don't understand why the tangent?
Comment: i found $ c= \pm \sqrt{41}$ how to contibue please
Answer: For the continuity let $(x_n,y_n)$ be a sequence in $\mathbf R^2$ such that $(x_n,y_n) \to (x,y)$. All you have to do is to show that $$|u(x_n,y_n) - u(x,y)| = | \sqrt{2} (x_n-x) +y_n - y|\to 0, \qquad \text{for} \quad n \to +\infty.$$
Hint: What can you say about the convergence of the component sequences $(x_n)$ and $(y_n)$ in $\mathbf R$ if you know that $(x_n,y_n)$ converges in $\mathbf R^2$? Use the triangle inequality.
Comment: we work I think with the norms


The rotating wheels problem?

Question:
As shown in figure a smaller wheel of radius $r_1$ and bigger wheel of radius $r_2$ are joined by a string.
When both of them are rotating such that the string does not slip over them then it is obvious that smaller wheel will rotate faster than bigger wheel.
If the bigger wheel is rotating with an angular velocity $\omega$ then what will be the angular velocity of smaller wheel in ideal situation?
Also, can we construct an infinite wheel system as shown below,

It is obvious that angular velocity of each wheel is greater than the previous then it will become very fast as we continue to make it large then what prevents us from creating such a system of wheels.
Comment: Where's the figure?
Comment: @TrầnThúcMinhTrí sorry now it is here
Comment: I don't understand what is the question.
Comment: The ratio of angular velocities is in directly inverse proportions to the ratio of circumferences of the two wheels connected by any given belt.
Comment: @Aretino what will be angular velocity of smaller wheel? and is the infinite system possible?
Comment: Nothing "infinite" is possible, sorry. Unless you have an infinite amount of space and time at your disposal, which I certainly haven't.
Answer: $\omega=\frac vr$
$\implies w\propto\frac1r$
So as the radius decreases by a factor of $a$, the angular velocity increases by $a$
so
$\omega_2 = a\cdot\omega_1$
Comment: Even in ideal situation latter wheels will have more energy which violates conservation principle
Comment: There is no violation: all the wheels are to be set into rotation at the same time, the force doing that must then provide the necessary work.
Comment: @imaginaryabhishek: there is no conservation of energy involved. All wheels will get an amount of kinetic energy, growing in a geometric progression.
Comment: faster wheel means more energy
Comment: not exactly , in this case faster wheel is not more energy, in a rotating system $E= \frac12Iw^2$, in this case as $\omega$ increases , the moment of inertia $I$ decreases,
Comment: @TheIntegrator: nonsense, $I$ is the same for all wheels.
Comment: @TheIntegrator: "all the wheels will rotate at the same angular velocity" is also wrong.
Comment: @YvesDaoust  the radius if the smaller wheels decreases so wont $I$ decrease ?  also yeah i wasnt sure about that. thanks i will remove it.
Comment: @TheIntegrator: all wheels are identical.
Answer: The linear speed of the belt is constant, so that
$$\omega_1r_1=\omega_2r_2.$$
This gives you the angular speed ratio for a pair of wheels.
If you concatenate many wheels, the ratio will indeed become huge, and so will the torque required to set the system in motion, to fight inertia, or simply friction. If you manage to produce enough torque, the first belts will slip or break.
Answer: For each set of two wheels, assuming massless wheels,
$$
\omega_1r_1 = \omega_2r_2
$$
Supposing identical sets and concatenating them
$$
\omega_1 r_1 = \omega_2 r_2\\
\omega_2 r_1 = \omega_3 r_2\\
\omega_3 r_1 = \omega_4 r_2\\
\cdots
$$
then
$$
\omega_n = \left(\frac{r_1}{r_2}\right)^{n-1}\omega_1
$$
Assuming no friction or losses of any kind, we have that the setup is a transformer in the sense that the input energy is equal to the output energy
$$
\tau_n\omega_n = \tau_1\omega_1
$$
with $\tau_1,\tau_n$ the input and output torques respectively. We are considering a finite $n$ In the case of $n\to \infty$ the input should be locked without movement due to the impossibility of infinite energy generation from a finite effort.

The rotating wheels problem?


Does a note/key/string struck on one piano cause the same note on another piano to resonate?

Question: I need assistance please. Not possessing one (never mind two!) pianos myself, I wonder if someone could test this experiment for me? (Or has someone already noticed this phenomenon?)
I am presently conducting a research project on quantum mechanics and the results of this experiment would prove very significant for me. Any assistance would be much appreciated so thank you in advance.
Comment: Any musical instrument can cause any other nearby musical instrument to resonate, as long as the other musical instrument has something that can resonate that is free to vibrate and is tuned to frequencies sympathetic with the source notes or chords being played by the first instrument. The degree of resonance will vary with the loudness of the source instrument. A soft sound may not cause enough resonance to be heard, but a louder sound will work. Basic physics.
Comment: Out of curiosity, in what way are you applying this to your quantum mechanics research?  I know sympathetic responses are easily explained by classical physics (as @NReilingh stated in his answer).
Comment: @Basstickler  Hi, I'm both a musician and a physicist. Here's one example from quantum mech: lasers.  The basic principle behind the Einstein equations is that a photon will stimulate "resonant" emission or absorption of photons of exactly the same wavelength as electrons change orbital levels (whose energy differences are equal to the photon energy).  So, oddly enough, There is a sort-of similarity to resonant pianos. It's more conceptual than physical, since you'd have a hard time "storing energy" in a piano string (ooh! String Theory!) for release when stimulated.
Comment: @CarlWitthoft Totally wrote a piece called "String Theory" about causing sympathetic resonance within a piano when I was in college. :-D
Comment: @CarlWitthoft Very interesting!  I imagine you could describe the tension of the string as stored energy, which I think is classically called potential energy?  For some reason your talk of lasers reminded me of this http://www.ted.com/talks/woody_norris_invents_amazing_things.html maybe because the lasers emit unidirectional light.
Comment: @Basstickler There is potential energy in the tension, but that's not relieved (aka converted to kinetic energy) by the sound waves. If it were, either the string would lose tension or some other mechanism would have to "pump" it back up.The resonance is purely due to absorbed energy from the sound waves.
Comment: @CarlWitthoft Yeah, that makes sense.  Now I'm thinking about how the amount of potential energy stored in the string effects pitch... I like science
Comment: The effect isn't quantum but are you merely wanting to use this as an illustration perhaps?
Answer: Yes, but this phenomenon is easily explained by classical physics.
If you hold down the sustain pedal on a piano (thus releasing the strings to vibrate freely), any instrument nearby playing a tone that is matched by one of the piano strings will cause that string to vibrate in sympathy.
The tone provided by the voice, trombone, second piano, violin, etc. is causing sound waves (periodic waves of air compression) to emanate from the instrument towards the piano string. Force from these waves of air compression is imparted to the piano string. Because the resonant frequency of the piano string is the same as the frequency of the air compression waves, the piano string responds by absorbing this kinetic energy and amplifying its own vibration.
Other strings on the piano that occur at perfect intervals (or harmonics) of the sound will also vibrate in sympathy, but with less intensity.
See also:

http://en.wikipedia.org/wiki/Sound
http://en.wikipedia.org/wiki/Sympathetic_vibration
http://en.wikipedia.org/wiki/Acoustic_resonance
http://en.wikipedia.org/wiki/String_resonance_(music)
http://en.wikipedia.org/wiki/Overtone
http://en.wikipedia.org/wiki/Harmonics
Comment: I'd also like to add that this is also true for other instruments as well - anything that *can* vibrate in a given room *will* vibrate in that room at the appropriate frequency - snare drums, light fixtures, chairs, etc.  Some instruments, such as the Sitar *depend* on sympathetic vibrations for the instrument to function.  I should also add that the pianos would have to be fairly close together and you would have to strike one of them loudly.  Also, the results would be more pronounced if two grand pianos were used.
Comment: Drums respond to a larger range of frequencies for two reasons: they all have a membrane which vibrates in two dimensions as opposed to one, and the 2-dimensional surface area absorbs MUCH more energy from sounds in the air than a string, so the pitch doesn't have to match exactly.
Comment: Lorries passing by can and do have the same effect on ,for example, fittings in the house - like badly fitting windows. Low frequency seems to be more successful in this phenomenon.The 'opera singer breaking the wineglass' syndrome is also relevant, and while I've never experienced it, believe it can happen. Yes, snare drums seem to have a greater propensity to vibrate sympathetically - wonder why?
Comment: I believe the snare drum just seems like it has a higher propensity because it is louder when this happens.  I think this is due to the snares touching the bottom head while it (and to some extent the snares) is vibrating.  You will notice that if the snares are turned off the drum will not have the same volume in its sympathetic resonance (drummers typically turn their snares off when not playing for an extended part of a song).  Different drums will be tuned differently which will also effect the resonance.
Comment: Also, rooms have a resonant frequency.  That frequency will propagate and be louder than others.  This means that the room's resonant frequency would be the easiest to frequency to stimulate as a sympathetic response.  In an amplified setting that frequency would be most likely to create feedback as well.
Comment: To be the persnickety physicist again, the strings absorb energy from all acoustic wavelengths. It's just that the wavelengths which don't match the string damp out rather than building up.
Comment: @CarlWitthoft Indeed! My wording wasn't the best there -- I've made some judicious punctuation changes that should make it more correct.
Comment: If I sneeze in my home office, which also has 3 acoustic guitars hung on the walls, the whole room 'rings' for a few seconds afterwards
Answer: A nice little demo of this is one I use with pupils: rest a piece of folded paper, about a quarter of a postage stamp size, on, say, the top string of a guitar. The middle of the string on an acoustic is good. Play notes on another guitar (or other instrument) and see what happens when that same top E is played.
It also works, but not so  markedly, with other notes which have that top E as a harmonic.
Comment: I have a guitar with very light strings, and if one plays the fifth string ("A") it will cause the first string (upper "E") string to sound; that string will continue to sound even if the "A" is damped.
Answer: If the sympathetic vibration of piano strings is significant for quantum mechanics theories, you are doing something wrong.  This is a wholly classical physics phenomenon.
Sympathetic vibration is actually a rather standard phenomenon.  I has happened to me repeatedly when practising singing that I was annoyed by some buzz that turned out to be, for example, some pencil in a metal container on a writing desk.  Finding the culprit of such sympathetic responses may be tricky.
Now a buzz is noteworthy because it is a non-linear response containing overtones not present in the exciting vibration.  The whole room usually responds in a linear manner that one does not realize until one has actually sang in a sound-deaf room without reflections.  Reed and brass instruments work principally by using a sympathetically vibrating air column in resonance with the actual sound production (reeds or lips).
It is pretty easy to get sympathetic reaction from a piano by putting down the sustain pedal (thus removing the dampeners from all strings) and singing into it, or knocking on it.
Without using the sustain pedal or holding down the keys for the resonating notes, you'll notice much less of an effect.


Existence of extremal value

Question: Determine the minimum and maximum values of the function $\frac{x^4}{(x-1)(x-3)^3}$.
By equating the first derivative to $0$,its fairly simple to deduce that the extreme points are $x=0,\frac{6}{5}$. However,to determine minimum or maxumum,we need to analyse the 2nd derivative as well which seems to be awfully long. Is there any way to do it simply?
Comment: You could try analysing the first derivative and think: if I add an number infinitely small, what will happen will the value of the first derivative go up or down
Answer: Call your function $f$. Notice that the numerator is always non-negative. Now, in some neighbourhood of $0$ we have $x-1<0$ and $x-3<0$, so the denominator is always non-negative in that neighbourhood. As $f(0)=0$, it must be a minimum.
As the only roots of $f'$ are $0$ and $\dfrac{6}{5}$ and it is a continuous function, it must have a constant sign on $\left(1,\dfrac{6}{5}\right)$ and a constant sign on $\left(\dfrac{6}{5},3\right)$. Evaluating, one gets that $f'\left(\dfrac{11}{10}\right)>0$ and $f'(2)<0$ , so $f$ increases on $\left(1,\dfrac{6}{5}\right)$ and decreases on $\left(\dfrac{6}{5},3\right)$, from where $f$ attains a maximum at $\dfrac{6}{5}$.
Comment: The 2nd derivative turns out to be $2\times \frac{(x-1)^2(x-3)^4(18x^2-20x^3)-2(6x^3-5x^4)(x-1)(x-3)^3(3x-5)}{(x-1)^4(x-3)^8}$. Here 0 satisfies that the 2nd derivative is 0,so 0 should neither be maximum or minimum.
Comment: @a_i_r The fact that $f''(0)=0$ does not mean $0$ isn't a maximum or a minimum; $f(x)=x^4$ serves as a counterexample.
Comment: Isn't the condition for maxima $f''(x)<0$ and for minima $f''(x)>0$? This is the theory I learnt about local extrema all this time.
Comment: That is a sufficient condition, **not** a necessary one
Comment: Desmos shows that in the neighbourhood of $0$,there are a lot of other points which also give the value $0$,could you please check where is the mistake?Since only 2 extreme points have been found.
Comment: There is no mistake. I don't know what other $0$'s you are talking about.
Comment: I meant plugging $x=0$ in the original function,we get $f(x)=0$ but according to desmos,there are such $x$ not equal to $0$ for which $f(x)=0$. In that case,why weren't those non zero values be derived using first derivative test?
Comment: The only point such that $f(x)=0$ is $x=0$, because a fraction is $0$ iff the numerator is $0$. The fact that a graphing calculator shows values close to zero doesn't mean those are actually roots.
Answer: The function tends to $1$ at $-\infty$ and to $\infty$ when $x\to 1^-.$ As $0$ is the only stationary point in $(-\infty,1),$ it must be a minimum. On the other hand $6/5$ belongs to the interval, where the function tends to $-\infty$ at $1^+$ and at $3^-.$ Therefore the function attains a maximum at $6/5
$
Comment: Please check my comment to the other answer kindly.
Comment: I don't get your point. No second derivative is used in my answer
Comment: I meant as in your solution,$0$ should be a minimum but 2nd derivative(which I calculated) shows $f"(0)=0$,which implies $0$ is neither minimum nor maxima since for maxima we need $f"(x)<0$ and for minima $f"(x)>0$.
Comment: The second derivative test may be inconclusive. For example $f(x)=x^4$ at $0.$ The better test is to study the signs of the first derivative on both sides of the stationary point.

Existence of extremal value


File-Transfer Cordova como usar php

Question: Olá tenho o seguinte código
 onDeviceReady: function () {
    navigator.camera.getPicture(
                app.uploadPhoto,
                function (message) { alert('get picture failed'); },
                {
                    quality: 50,
                    destinationType: navigator.camera.DestinationType.FILE_URI,
                    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
                }
            );
},
uploadPhoto: function(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";

var params = {};
params.value1 = "test";
params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.0.101/upload/index.php"), app.win, app.fail, options);
},

win: function(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
},

fail: function(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
},

Ele está funcionando, porem quando eu envio para o meu php eu não sei como salvar, o meu php esta assim:
    <?php
move_uploaded_file($_FILES["file"]["tmp_name"], 'C:\xampp\htdocs\upload\images');
    ?>

Gostaria de salvar dentro de C:\xampp\htdocs\upload\images, como deve ficar o meu php?
Answer: Consegui fazer funcionar da seguinte forma, o js ficou assim.
ft.upload(fileURI, encodeURI("http://192.168.0.102/upload/index.php"), app.win, app.fail, options);

O index.php recebe e envia-lo para a pasta 'images' dentro de 'upload'.
 <?php
    $new_image_name = strtolower($_FILES['file']['name']);
    move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$new_image_name);

Comment: Se a sua resposta está correta, então marque ela como aceita.

File-Transfer Cordova como usar php


Como carregar imagem padrão caso o src="" não encontre?

Question: Existe alguma forma de carregar uma imagem padrão, usando apenas HTML, caso o primeiro src="" não encontre o arquivo?
 // Existe algum atributo para isso?

Answer: Outros fallbacks mais simples que pode experimentar, com javascript:

Um exemplo no jsfiddle do @Randrade: https://jsfiddle.net/wts9e4xb/1/

Sem error

Com error

Com CSS (requer tamanho fixo):

Comment: Bom, mesmo usando JS acredito que ainda sim seja a melhor solução.
Answer: Encontrei essa solução...

<object data="https://img.com.br/no_existe.jpg" type="image/png">

</object>

Nessa pergunta


Clickable link inside message discord.py

Question: I would like my bot to send message into chat like this:
await ctx.send("This country is not supported, you can ask me to add it here")

But to make "here" into clickable link, In HTML I would do it like this, right?
 This country is not supported, you can ask me to add it here

How can I do it in python?
Answer: As the other answer explained, you can't add hyperlinks in normal messages, but you can in Embeds. I don't see why you wouldn't want to use an Embed for an error message, especially considering it adds more functionality, so you should consider using that.
embed = discord.Embed()
embed.description = "This country is not supported, you can ask me to add it [here](your_link_goes_here)."
await ctx.send(embed=embed)

Feel free to mess around with the Embed & add some fields, a title, a colour, and whatever else you might want to do to make it look better. More info in the relevant API docs.
Comment: Is there a way to do this in the title? I tried this but it didn't work in the title
Comment: @F.M Yes, but not using the same ``[notation](with brackets)``. When you create the Embed, you can pass in a hyperlink through the `URL` parameter. `embed = discord.Embed(url="YOUR_LINK_HERE")`, and it will put the link on the title.
Comment: But that makes the whole title the same link, I was wondering if I could make different words different links.
Comment: @F.M No, you can't do that.
Answer: As far as i know, Discord don't allow using HTML in messages, when you see any form of formating on some messages it's either :

Done with markdown
Embed usage.

The problem is that both those methods won't help you to solve your problem, because :

in markdown we use [Here](link) to achieve what you want, but after i tried it on Discord, it doesn't seem to render, so my guess is that not all markdown is usable in Discord
Embeds are really different from what you want to achieve.
Answer: Another way of solving this; you can add url=(pop_in_link), but this one works when you do, import discord. You can use either method
Answer: This might help people trying to embed links in their code for their bot.
embed = discord.Embed(
    title="[title]",
    url="[URL]",
    description="[description (optional)]",
    color=[color hex code or tag (optional)]
)


Are you allowed to score a goal off the ground with your head to showboat?

Question: An attacker beats the defensive line and then goes around the keeper on the edge of the penalty area, leaving them well behind. The attacker continues dribbling the ball towards their opponents' goal. They then stop the ball on the goal line with their foot. They then get down to their knees, wait for the goalkeeper and/or other defenders to approach (in order to make a last ditch save) and then score with their head.
Would this goal stand, and if not, what would be the outcome and why?
Comment: interesting question, I asked a generalised version of this question with respect to what sort of punishment is possible for unsporting behaviour with intent of teasing/taunting/insulting the opponents or the fans
Answer: This scenario occurred in a 2014 match in the french Ligue 1. Paul-Georges Ntep scored a goal  for Rennes against Reims with a header after dribbling up to the empty goal. On this occasion at least, the referee let the goal stand.
Herman Koré repeated the feat in the French cup , according to google translate:

During the 8th round of the Coupe de France between Chateaubriant and
  US Concarneau Saturday Herman Kore had fun pushing the ball head on
  the opponents goal

and again the goal stood, even though the opposition were upset.
So in practice it seems likely that the goal will stand, but the referee could possibly decide that the act of heading the ball in from the ground was "unsporting behaviour". This is indeed recommended in this post, which claims to have been "approved by the U.S. Soccer Federation's National Referee Program". In this case the referee would stop the game, issue a yellow card to the attacker, and restart with an indirect free kick to the defending team.
Comment: That post you linked is actually official policy for referees in the US. Furthermore, the answer has come directly from IFAB, so I'd argue that the referee was wrong in this case.
Comment: This weekend Würzburger Kickers scored this goal: [link]https://www.youtube.com/watch?feature=player_embedded&v=mPixvuy5z-8 . This is a correct goal but as @Fillet said: a goal as discribed in the question should not be given because of unsporting behaviour and the player gets a yellow card. Yellow cards for unsporting behaviour are also for taking of the shirt eg
Comment: @Phab: the 1-0 for Würzburger Kickers is definitely improvisation, not showboating. The striker seems to fall, possibly due to a challenge from the defender behind him, and then heads the ball in while on the floor. You, I and Referee all agree: correct goal
Answer:  It's a goal, but why bother do that? (Beside to showboat, obviously)
In the Rules of The Law, it was told that (page 34):

A goal is scored when the whole of the ball passes over the goal line,
  between the goalposts and under the crossbar, provided that no
  infringement of the Laws of the Game has been committed previously by
  the team scoring the goal"

Making a goal with your head is not an infringement. So goal it is.
Comment: I would say it's taunting indeed! The player says "Look, how bad you are! I have even time to do some "tricks" before scoring the goal."
Comment: So, you're saying that in no way, the action can be considered to be unsporting behaviour?
Comment: Well this is objective or depends to the referee, but I will call it as not unsporting behavior. Well, taunting can be remarked as unsporting behavior, but this is not taunting, this is just 'looking for problem'
Comment: Taunting might result in a yellow card, but there isn't anything in the rules where it would be an infraction that would negate a goal, is there?  I'm not seeing any basis for why it would be disallowed.


Attach hidden (biometric) data to a digital signature on a pdf

Question: I'm wondering if it is possible, using iText (that I used for signing) or other tools in Java, to add biometric data on a pdf.
I'll explain better: while signing on a sign tablet, I collect signature information like pen pressure, signing speed and so on. I'd like to store those informations (variables in java) togheter with the signature on the pdf. Obviously hidden and encrypted such as the signatures info.
Is there some kind of hidden data field on a pdf or something that can contain this kind of information? I think it is inappropriate to store it in the metadata fields such as author etc.
Answer: There are different ways to add info to a PDF document.
You could add the data in a document-level attachment. That way, people can inspect the data by opening the attachment panel.
Storing it as metadata is fine too, but you're right about it being inappropriate to store that info in something like the author key.
As you may know, the <code>/Info</code> dictionary will be deprecated in PDF 2.0 in favor of using an XMP metadata stream. In this metadata stream, you can add custom XML data (see section 2.2.1 of the XMP specification - Part 3).
If you don't want to mix your biometric data with the document metadata, you can even define an XMP stream for any dictionary you want, probably including the signature dictionary. See section 14.3.2 of ISO-32000-1.
PS 1: I don't know who downvoted your question. I upvoted it, so you're back at 0.
PS 2: If you want to create future proof signatures, read http://itextpdf.com/book/digitalsignatures
PS 3: Signatures created with the 4-year-old version of iText usually aren't future-proof.
Comment: Thank you Bruno, this was usefull to me (thanks even for the upvote). I am using a recent iText release so it should be fine for the future proofness


Heavy but silent acoustic drumming

Question: I am gonna play a gig with an acoustic band (flute, saxophone, cello and digital piano) without any mics or speakers. I will be drumming along with them. The idea is that we play smooth jazz and instrumental covers of pop songs. The latter will involve quite a lot of drums and I am wondering for ways to make my drums more silent but I want to be able still to put lots of energy in my playing, to get the right feel. I am especially worried about the loudness of my hihat. Any ideas? Would a digital drumkit solve this problem? Or should the speaker be too loud for overpowering the sound of hitting the digital drums?
Thx a lot!
Comment: "to make my drums more silent but I want to be able still to put lots of energy in my playing, to get the right feel" - how exactly do you envision that?! Patrick has a good answer below in regards to energy. That is what you project. If, on the other hand, you want to play strong/powerful but have low volume, that just makes no sense. You can still have a decent dynamic range even if playing pp to mf.
Answer: Using Hot Rods would help a lot:

They feel a lot more like using drum sticks, than using brushes, but are much quieter. (I'm a big fan of getting "enthusiastic" young drummers I work with to use them, especially in small rehearsal spaces!)
Comment: Put a couple of large pillows in it.
Comment: But that leaves the kick drum as another problem
Answer: I'm just going to add on to some of the already decent answers here. In your head you need to separate the idea that playing with energy means playing loud. Intensity and energy can happen even at very soft dynamics. But most importantly, I'm not sure you're asking the right question, it sounds like you want to find sticks or techniques that allow you to play your default heights and bring the volume down mechanically through implements. I think what you need to do is adjust your mentality and decide that you can continue to use whatever implements you have and just play softer with the lighter accompaniment. Just keep in mind that while you're playing the gig, if you can't hear them you're not balanced. You should be able to easily take musical cues from them while they listen back to you for tempo.
All your drums and cymbals are able to to be played at softer dynamics through deliberate choice, not only through different drumming techniques, tunings, or stick choices. So play softer with any amount of energy you choose and you'll be fine.
Answer: With smooth jazz drumming the key is to play silent but technical. If you are worried about overpowering the band, try using sticks that are lighter, it makes the cymbals have less sustain.
I would suggest some 8A sticks, regal tip or nylon tip. As you can see the 8A series are practically made for jazz. They are a significantly lighter stick and are practically made for drummers in the same situation as you.

In reference to the kick drum issue, try to play heel down technique. Alot of drummers are taught to play heel up due to making a better and more sustainable sound to get more tone. When you play heel down it gives less power to the pedal thus giving the illusion that you are playing quieter but yet you are putting the same amount of pressure on just with less power and drive into the pedal.

With the high hat problem, keep it closed and refrain from opening it up as much as you usually would. It will get rid of the sustaining of the sizzling issue and it will not be as loud.
Answer: There are some good answers for managing volume if you must use an acoustic kit.  However in your question you also asked about an electronic kit (I'm not sure why they don't call them digital). I know you mentioned the absence of mic or speakers, but also mentioned a digital piano which means you will have speakers for the piano.
I have a band that plays classic rock, pop, and country music in small venues.  I have used four different drummers and all of them used an electronic kit.  For whatever it's worth, all the kits were made by Roland, but I understand Simmons makes some really good electronic kits as well.  The venues we play (resturants and bars seating less than 100 people) require relatively low volumes.  Whenever I watch other bands in these same venues that have an acoustic drum kit, folks complain that the volume is too loud because the rest of the musicians have to turn up their volume to be heard above the drummer.
The technology in electronic kits is continuing to evolve and drummers tell me the makers of these kits are getting better at replicating the feel of an acoustic kit.  The main advantage for a drummer using an electronic kit is that you don't have to hold back and can put your full energy and velocity into your drumming - while controlling the volume with a volume control knob.  I can tell that when a drummer tries to play softly on an acoustic kit, it seems to interrupt their rhythm or impede there technique and they are not as smooth on the fills and transitions and faster runs.
For amplification you can use a specialized electronic drum monitor.  These are tuned and designed specifically to accurately reproduce the full range of sounds found in a full drum kit.  Many have separately amplified woofers for the kick drum plus high range tweeters for the cymbals as well as mid range for the toms.  You can position one of these so that the audience can hear it as well as you do. Most also have headphone jacks.
Depending on how your digital piano is amplified, you may be able to input your drum kit into that system.  My drummers plug into my PA system and we EQ their channel for optimal sound of their kit and adjust the volume so that it can be heard in the overall mix without overpowering.  One of my drummers brings his own drum monitor as well - and in other bands he plays in sometimes uses it as a standalone amp for his drums and does not go into the PA at all.
It might take getting used to the feel of an electronic kit (or V kit as they are sometimes called), but it is certainly an option for managing and fine tuning the volume without having to hold back your energy.  Plus you can plug in the headphones and practice at home while others are sleeping or watching TV.
They work great for recording too - you don't have to worry about getting multiple mics positioned just right.  You have individual volume control over every drum in the kit.  One more nice feature - you can literally have 100 different sounding kits in one.  Need congas or timpanis - no problem - just select them on the console.
I have included a picture of a monitor specifically made for V drums below.

Comment: The reason that we don't call electronic drum kits "digital drum kits" is that the first electronic drumkits were not digital — they were analog synths.
Comment: @SimonWhite Ahhhh - that's the reason.  Thanks for enlightening me.  I have noticed that many of these electronic kits are now being called V-Drums I guess short for Virtual Drums.
Answer: A common way to solve this is to have a drum shield (often made of plexi glass) in front of the set to stop some of the sound from reaching out.
Comment: I have thought about this too, but I fear that due to sound reflection on one hand and sound blocking on the other hand, I will not hear other band members and hear myself really loud :/
Comment: Sound reflection could be reduced by putting up some woolly blankets or something at the lower part in front of the set. As for you hearing the others, maybe you could sit on the side of the others, so that the shield only stops sound out to the audience.
Comment: So you're saying the plexi around the kit, blanckets inside the plexi and open to the side. Seems legit, but the flutist or the cellist will complain about not hearing themselves probably...
Comment: I think you just have to try out, and see what works best for you. The ideal would be to mic up the others and have a monitor for you, but I guess that is not an option since you said "without mics and speakers"?
Comment: I am afraid already of the price for plexiglas haha we are amateurs and we do the concert by ourselves. Sadly but nope thats not an option
Answer: The items in the previous post I call bundle sticks, which is a good option, but I think they are still pretty loud. How about regular jazz brushes? These are VERY quiet. I have also put masking tape on the cymbals and the hi-hat cymbals as well. Using a pillow for the bass drum is a good idea.

Heavy but silent acoustic drumming


Nginx rules conversion

Question: I have these htaccess rules:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

and I used an online converter and this is what it gave me, however, it doesn't work, so I'm not really sure what's wrong with it.
location / {
rewrite ^/(.*)/$ /$1 redirect;
if (!-e $request_filename){
rewrite ^(.*)$ /index.php break;
}
}

thanks in advance
Comment: What do you mean by "doesn't work" - what actually happens?
Answer: In nginx you don't use rewrite for front controllers, instead use try_files. Your configuration should look something like this:
server {
    ...
    try_files $uri $uri/ /index.php;

    location ~ (.+)/$ {
        return 301 $scheme://$host$1;
    }
}

Nginx rules conversion


Which property of trace of matrix that $\mathrm{tr}(hh^H B B^H) = h^HB^HBh$?

Question: By numerical tries, I see that
$$\mathrm{tr}(hh^H B^H B) = h^HB^HBh$$
where $\mathrm{tr}(A)$ and and $A^H$ are the trace and the conjugate transpose of matrix $A$, respectively.
$h$ is column vector.
Could anyone tell me which property of $\mathrm{tr}()$ can be used to prove this ?
Comment: @JeanMarie thanks, my mistake
Answer: It is due to the property $tr(AB)=tr(BA)$ which is always true for square matrices.
Here, as $h^HB^HBh$ is a scalar:
$$h^HB^HBh = \mathrm{tr}(h^HB^HBh) = \mathrm{tr}((h^HB^HB)h)=\mathrm{tr}(h(h^HB^HB))$$
Remark: more generally, we have a "rotating property" of operator "trace" (see the interesting answers in (Prove that $\operatorname{trace}(ABC) = \operatorname{trace}(BCA) = \operatorname{trace}(CAB)$)) that can be extended to any number of factors and any (rectangular or square) type of matrices as long as their dimensions are compatible for multiplication(s).
Comment: thanks, but the right hand side of my equation does not contain $\mathrm{tr}()$
Comment: See the last sentence I have added to my "proof".
Comment: I dont understand your last sentence. I followed your hint

$$h^HB^HBh = \mathrm{tr}(h^HB^HBh) = \mathrm{tr}(hh^HB^HB)$$

where the first equality comes from $h^HB^HBh$ is scalar and the second equality comes from the identity $ \mathrm{tr}(AB)= \mathrm{tr}(BA)$.

Do you think it is ok ? If yes I will mark accepting your answer. Thanks
Comment: it is my another mistake. Thanks, I have fixed my question
Comment: Fine.  I erase my different remarks or answers "for future generations" reading this question and its answers.


Chef conditional execute in recipe

Question: I'd like to create an execute block which is only run when some specific condition is met (in this case if an interface wlan0 is present). Alternatively, I'd like to prevent the notifies clause of a template on the same condition.
How can I describe that in a recipe? I could of course put the whole condition in the execute's command, but I hope there's a better way to achieve this...
Comment: The 'guards' 'not_if' and 'only_if' will only execute a resource if a script returns true. https://docs.chef.io/resource_execute.html
Answer: Go to:
https://docs.chef.io/resources.html#guards
Look at the section titled "Conditional Execution"
Comment: That no longer exists.
Comment: seems to be back now.

Chef conditional execute in recipe


HTML displayed as text

Question: I have a .php file which contains html code. The issue I am having is that it's being displayed as text, not as html elements. I have found several other questions regarding the same problem:
Why is this HTML showing up as plain text in browser?
Browser shows plain text instead of HTML in mac
Page shows code not rendering
However, I believe that everything the people suggested there applies to my code.
My code:
<?php
// required headers
header("Access-Control-Allow-Origin: null");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// files needed to connect to database
include_once '../config/database.php';

// get database connection
$database = new Database();
$conn = $database->getConnection();

$error = "";
if (isset($_GET["key"]) && isset($_GET["email"]) && isset($_GET["action"]) && ($_GET["action"]=="reset") && !isset($_POST["action"])) {
    $key = $_GET["key"];
    $email = $_GET["email"];
    $curDate = date("Y-m-d H:i:s");

    $query = "SELECT * FROM password_reset_temp WHERE email=:email AND `key`=:key";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(":key", $key);
    $stmt->bindParam(":email", $email);
    try {
        $stmt->execute();
    } catch (PDOException $e) {
        echo json_encode(array("message" => $e->getMessage()));
    }
    if ($stmt->rowCount() == 0) {
        $error .= '
Invalid Link

The link is invalid/expired. Either you did not copy the correct link
        from the email, or you have already used the key in which case it is
        deactivated.

        Click here to reset password.
';
    } else {
        $row = $stmt->fetch();
        $expDate = $row['expDate'];
        if ($expDate >= $curDate){
// the part that is not showing begins here
?>

            <form method="post" action="" name="update">
            <input type="hidden" name="action" value="update" />

            Enter New Password:

            <input type="password" name="pass1" maxlength="15" required />

            Re-Enter New Password:

            <input type="password" name="pass2" maxlength="15" required/>

            <input type="hidden" name="email" value="<?php echo $email;?>"/>
            <input type="submit" value="Reset Password" />
            </form>
            <?php
        } else {
            $error .= "
Link Expired

The link is expired. You are trying to use the expired link which
            as valid only 24 hours (1 days after request).

";
        }
    }
    if($error!=""){
        echo "
".$error."

";
    }
} // isset email key validate end

if(isset($_POST["email"]) && isset($_POST["action"]) &&
 ($_POST["action"]=="update")){
$error="";
$pass1 = mysqli_real_escape_string($con,$_POST["pass1"]);
$pass2 = mysqli_real_escape_string($con,$_POST["pass2"]);
$email = $_POST["email"];
$curDate = date("Y-m-d H:i:s");
if ($pass1!=$pass2){
$error.= "
Password do not match, both password should be same.

";
  }
  if($error!=""){
echo "
".$error."

";
}else{
$pass1 = md5($pass1);
mysqli_query($con,
"UPDATE `users` SET `password`='".$pass1."', `trn_date`='".$curDate."'
WHERE `email`='".$email."';"
);

mysqli_query($con,"DELETE FROM `password_reset_temp` WHERE `email`='".$email."';");

echo '

Congratulations! Your password has been updated successfully.

Click here to Login.

';
   }
}
?>

My .htaccess looks like this
# Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (Case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]

The output:

            <form method="post" action="" name="update">
            <input type="hidden" name="action" value="update" />

            Enter New Password:

            <input type="password" name="pass1" maxlength="15" required />

            Re-Enter New Password:

            <input type="password" name="pass2" maxlength="15" required/>

            <input type="hidden" name="email" value="..."/>
            <input type="submit" value="Reset Password" />
            </form>

All the other .php files in that directory work perfectly. If you need any other information, let me know.
Comment: **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from.
Comment: **Danger**: You are using [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords.
Comment: Is this embedded inside another file? If not, you're missing the `` and `` tags, at a minimum.
Comment: You should [learn how to use the label element properly](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/). Without a for attribute or a form control inside it, a label is useless. (And if you are going to put a `` inside very label, you should probably use `font-weight` on them instead)
Comment: Multiple `` elements are not a good substitute for CSS margins.
Comment: @Quentin Im using prepared statements, is that not enough?
Comment: @php_n00b — You aren't at the bottom.
Comment: @Quentin the second part will be rewritten, since its from a tutorial. Im usually using Bcrypt. The question was about the first part, where I was stuck. I included the bottom unchanged code in case it was relevant. Thanks for reminding me!
Answer:
header("Content-Type: application/json; charset=UTF-8");

You said it was JSON and not HTML.
The browser is trying to treat it as JSON, failing, and showing it as text instead.
Comment: "html" is not a valid content-type. It should be `text/html`, but that's the default for PHP so remove it entirely.
Comment: That was indeed causing the error, changing it from "application/json" to "html" worked for me! Thanks

HTML displayed as text


Authentication with specific subdomains

Question: Basically I'm trying to enable the authentication module when accessing to a specific part of a subdomain, which are dev.domain.com and pma.domain.com, they both must have the authentication module loaded. I can't seem to figure why my nginx configuration file isn't working.
In the second server block you can see the pma and dev with the authentication module, when I access to pma.domain.com or dev.domain.com, I don't see the authentication module showing from my browser, nor any error logs stored.
Anyway, I just need a fix to enable the authentication on them two subdomains, not an entire rewrite of my nginx configuration file.
server {

    server_name domain.com;

    root            /var/www/domain.com/www;
    index           index.php index.htm index.html;
    error_page      404 /404.html;
    error_page      500 502 503 504  /50x.html;

    access_log      /var/www/domain.com/logs/access.log;
    error_log       /var/www/domain.com/logs/errors.log;

    error_page 404  /index.php;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/domain.com/www$fastcgi_script_name;
        include fastcgi_params;
    }
}

server {

    server_name ~^(.+)\.domain\.com$;

    set $file_path $1;

    root            /var/www/domain.com/www/$file_path;
    index           index.html index.php;

    access_log      /var/www/domain.com/logs/access.log;
    error_log       /var/www/domain.com/logs/errors.log;

    location /
    {
        try_files $uri /$uri /index.php?$args;
    }

    location ~ pma
    {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/domain.com/www/dev/authfile;
    }

    location ~ dev
    {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/domain.com/www/dev/authfile;
    }

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/domain.com/www$fastcgi_script_name;
        include fastcgi_params;
    }
}

Anyone?
Answer: However, you need to split this two domains in separate server blocks and leave wildcard substitution for others, or try to use workaround below.
1.
"location" directive works with URI only, not with host header
2.
And if you try to do something like
if ($host ~ "(dev|pma).example.com" ) {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/domain.com/www/dev/authfile;
}

then you will get a

error nginx: [emerg] "auth_basic" directive is not allowed here
  in.....

because auth_basic directive is unconditional
workaround (not well tested):
    if ($host ~ "(dev|pma).example.com" ) {
        return 555;
    }

    error_page 555 = @auth;

    location @auth {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/domain.com/www/dev/authfile;
        try_files $uri /$uri /index.php?$args;
    }

Comment: I get this error when restarting nginx `Restarting nginx: nginx: [emerg] unknown directive "if($host"`
Comment: add a space symbol between "if" and "($host"
Comment: Here's a weird thing, when I access the subdomains, the page constantly loads for a long time then shows a blank page after that. Any reason why?
Comment: Well... anything...?
Comment: At least give me a response.
Comment: Hey! At least help when you can!
Comment: You'll lose the bounty if you don't answer.
Comment: You should use recursive_error_pages on; For ghloogh solution.
Answer: A way simpler solution is either use map
map $http_host $auth_type {
    default "off";
    example.domain.tld "Restricted";
}

server {
    auth_basic $auth_type;
}

Or
As of nginx 1.5.4+ the auth module:
http://nginx.org/en/docs/http/ngx_http_auth_request_module.html
Comment: Nice. I had to add hostnames; at the top of the map to be able to use wildcard matching
Comment: Depends on who is taking over your dns.

Authentication with specific subdomains