Como eu poderia destacar o radio button que está selecionado?

Question: Possuo este radio group no qual serve para especificar o nível de gravidade de uma determinada ocorrência, usando as cores para classificar o nível.
Veja:

   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

   Nível de gravidade

         <input type="radio" value="B" checked autocomplete="off"> Branco

         <input type="radio" value="A" autocomplete="off"> Amarelo

         <input type="radio" value="L" autocomplete="off"> Laranja

         <input type="radio" value="V" autocomplete="off"> Vermelho

Repare que quando eu seleciono uma das opções de cores e em seguida removo o foco do radio button, o radio button que está selecionado fica quase imperceptível, parecendo que ele não esta selecionado. Isso pode confundir o usuário, levando ele a crer que não selecionou direito a opção desejada.
Perguntas

Como eu poderia fazer com que o radio button selecionado se
destacasse entre os demais?
Poderia haver um efeito visual na opção selecionada?

Acredito que desta forma o usuário não iria se confundir em questão disto.
PS: O radio button que estiver selecionado não pode ter sua cor alterada, porque ela tem uma finalidade.
Answer: Use um elemento ::after por exemplo, veja

            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>

                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                  Nível de gravidade

                          <input type="radio" value="B" checked autocomplete="off"> Branco

                          <input type="radio" value="A" autocomplete="off"> Amarelo

                          <input type="radio" value="L" autocomplete="off"> Laranja

                          <input type="radio" value="V" autocomplete="off"> Vermelho

Comment: O branco não está aparecendo no branco xD
Comment: @Randrade já arrumei, agora está certinho ;)
Answer: O que acha dessa ideia?
Quando a classe .active é adicionada, um ícone do Glyphicons (padrão do Bootstrap) é inserido ao botão através do seletor ::after do CSS.

.btn-default.amarelo
{
  background: yellow;
}

.btn-default.amarelo:hover
{
  background: rgb(240, 240, 0);
}

.btn-default.amarelo.active,
.btn-default.amarelo:active
{
  background: rgb(230, 230, 0) !important;
}

.btn-default.laranja
{
  background: orange;
}

.btn-default.laranja:hover
{
  background: rgb(255, 140, 0);
}

.btn-default.laranja.active,
.btn-default.laranja:active
{
  background: rgb(255, 125, 0) !important;
}

.btn-default.vermelho
{
  background: red;
}

.btn-default.vermelho:hover
{
  background: rgb(240, 0, 0);
}

.btn-default.vermelho.active,
.btn-default.vermelho:active
{
  background: rgb(230, 0, 0) !important;
}

.btn-default.active::after
{
  font-family: 'Glyphicons Halflings';
  font-size: 12px;
  content: '\e013';
}
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Nível de gravidade

        <input type="radio" value="B" checked autocomplete="off"> Branco

        <input type="radio" value="A" autocomplete="off"> Amarelo

        <input type="radio" value="L" autocomplete="off"> Laranja

        <input type="radio" value="V" autocomplete="off"> Vermelho

Answer: Segue uma sugestão para destacar a opção selecionada.
Adicionei um fundo ao texto e fiz com que ele alterna-se de acordo com a gravidade selecionada:
CSS adicionado:
h1 {
  background-color: rgb(212, 212, 212);
  width:305px;
  border-radius: 10px;
}

.btn-default.active {
  font-weight:bold;
}

JS adicionado:
$(".btn-default").on("click", function(){
  $("h1").css("background-color", $(this).css("background-color"));
});

Exemplo:

$(".btn-default").on("click", function(){
  $("h1").css("background-color", $(this).css("background-color"));
});
h1 {
  background-color: rgb(212, 212, 212);
  width:305px;
  border-radius: 10px;
}

.btn-default.active {
  font-weight:bold;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          Nível de gravidade

                  <input type="radio" value="B" checked autocomplete="off"> Branco

                  <input type="radio" value="A" autocomplete="off"> Amarelo

                  <input type="radio" value="L" autocomplete="off"> Laranja

                  <input type="radio" value="V" autocomplete="off"> Vermelho

Comment: Sugestão criativa +1
Answer: Cada vez que é clicado num button é adicionado nele uma classe .active, então pode ser criado um estilo específico para essa classe. Seguindo o padrão do focus do button pode ser adicionado por exemplo um box-shadow nele quando ele for selecionado

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          Nível de gravidade

                  <input type="radio" value="B" checked autocomplete="off"> Branco

                  <input type="radio" value="A" autocomplete="off"> Amarelo

                  <input type="radio" value="L" autocomplete="off"> Laranja

                  <input type="radio" value="V" autocomplete="off"> Vermelho

Answer: Talvez só "subir" um pouco o botão selecionado?
.btn.btn-default.active {
    bottom: 3px;
  }

Veja o exemplo completo.

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    Nível de gravidade

                  <input type="radio" value="B" checked autocomplete="off"> Branco

                  <input type="radio" value="A" autocomplete="off"> Amarelo

                  <input type="radio" value="L" autocomplete="off"> Laranja

                  <input type="radio" value="V" autocomplete="off"> Vermelho

Comment: Ideia legal mano +1
Answer: Uma sombra pulsando é uma boa forma de chamar a atenção:

.btn-default.amarelo{
    background: yellow;
}
.btn-default.amarelo:hover{
    background: rgb(240, 240, 0);
}
.btn-default.amarelo.active{
    background: rgb(230, 230, 0) !important;
}
.btn-default.laranja{
    background: orange;
}
.btn-default.laranja:hover{
    background: rgb(255, 140, 0);
}
.btn-default.laranja.active{
    background: rgb(255, 125, 0) !important;
}
.btn-default.vermelho{
    background: red;
}
.btn-default.vermelho:hover{
    background: rgb(240, 0, 0);
}
.btn-default.vermelho.active{
    background: rgb(230, 0, 0) !important;
}
.btn-default.active{
   animation:efeito .5s infinite linear;
   background: #eee !important;
}

@keyframes efeito {
    0% { box-shadow: 0 0 25px green; }
    50% { box-shadow: none; }
    100% { box-shadow: 0 0 25px green; }
}

@-webkit-keyframes efeito {
    0% { box-shadow: 0 0 25px green; }
    50% { box-shadow: 0 0 0; }
    100% { box-shadow: 0 0 25px green; }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

 Nível de gravidade

         <input type="radio" value="B" checked autocomplete="off"> Branco

         <input type="radio" value="A" autocomplete="off"> Amarelo

         <input type="radio" value="L" autocomplete="off"> Laranja

         <input type="radio" value="V" autocomplete="off"> Vermelho

Ou quem sabe, pulando:

.btn-default.amarelo{
    background: yellow;
}
.btn-default.amarelo:hover{
    background: rgb(240, 240, 0);
}
.btn-default.amarelo.active{
    background: rgb(230, 230, 0) !important;
}
.btn-default.laranja{
    background: orange;
}
.btn-default.laranja:hover{
    background: rgb(255, 140, 0);
}
.btn-default.laranja.active{
    background: rgb(255, 125, 0) !important;
}
.btn-default.vermelho{
    background: red;
}
.btn-default.vermelho:hover{
    background: rgb(240, 0, 0);
}
.btn-default.vermelho.active{
    background: rgb(230, 0, 0) !important;
}
.btn.active{
   animation:efeito .5s infinite linear;
   background: #eee !important;
}

@keyframes efeito {
    0% { top: -5px; }
    50% { top: 0; }
    100% { top: -5px; }
}

@-webkit-keyframes efeito {
    0% { top: -5px; }
    50% { top: 0; }
    100% { top: -5px; }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

 Nível de gravidade

         <input type="radio" value="B" checked autocomplete="off"> Branco

         <input type="radio" value="A" autocomplete="off"> Amarelo

         <input type="radio" value="L" autocomplete="off"> Laranja

         <input type="radio" value="V" autocomplete="off"> Vermelho

Comment: A ideia é interessante, mas animações contínuas pra indicar estado podem se tornar cansativas.


How to access localhost virtual server from another PC in network

Question: we have more PCs in a network. There is an intranet application running on one of the se PCs under virtual server:
<VirtualHost 127.0.0.1>
   DocumentRoot "D:\data\o\application\root"
   ServerName application
</VirtualHost>

It is a Zend Framework application. That's why it requires virtual server. We are running Apache as a webserver on all PCs.
How can I access this application from another PC in the intranet if the PC has name, let's say "johndoe-pc"?
EDIT:
This is a complete virtual host configuration from httpd.conf:
NameVirtualHost 127.0.0.1

#D:\data\o is document roo of the Apache web server

<VirtualHost 127.0.0.1>
   DocumentRoot "D:\data\o"
   ServerName johndoe-pc
</VirtualHost>

<VirtualHost 127.0.0.1>
   DocumentRoot DocumentRoot "D:\data\o\application\root"
   ServerName application
</VirtualHost>

On the PC where the application is I can access it by typing:
http://application

Answer: Replace 127.0.0.1 by *
<VirtualHost *>
   DocumentRoot "D:\data\o\application\root"
   ServerName application
</VirtualHost>

But depending of other part of your apache configuration it might not work, give it a try. Don't forget to restart Apache
Comment: also, "application" must be known, to the PCs in the network, if you don't want to use the IP of that computer.
You do this by either adding it to the hosts file, or you have a DNS server on your network, just like @esc1729 suggested.
Comment: What should I type in the URL address of the other PC's web browser to access the application? Also check my updated httpd.conf virtual server configuration.
Answer: If you have no DNS server running you may access this virtual host directly via the IP of the server. I presume that the name you mentioned in your post is the NetBios name. You will need a DNS name. If you do not want to run a DNS server, just put name and IP of the webserver into all hosts files of your workstations. On Windows you'll find them in C:\WINDOWS\system32\drivers\etc\hosts.
Answer: If you don't want to change your Apache configuration, install an SSHd on that computer and use port forwarding with ssh -L80:serverip:80, where serverip is the IP of the computer running Apache.
You will then be able to access that application with http://localhost/.
I suggest however, that you change your Apache configuration, since with this solution, every user needs to open an SSH session to that computer.


Puppet fails on icinga2 using puppet-icinga2 module

Question: I am trying to bring up a box for icinga2 using vagrant and
I am using puppet-icinga2 from https://github.com/Icinga/puppet-icinga2/tree/v0.6.2
so I have a role as shown below
<code>class role::icinga2_server {

class { 'postgresql::server':
      ip_mask_deny_postgres_user => '0.0.0.0/32',
      ip_mask_allow_all_users    => '0.0.0.0/0',
      listen_addresses           => 'localhost',
      postgres_password          => 'password',}

postgresql::server::db {
        'icinga2_data':
        user => 'icinga2',
        password => 'password'
}

class { 'icinga2::server':
      server_db_type => 'pgsql',
      db_host => 'localhost',
      db_port => '5432',
      db_name => 'icinga2_data',
      db_user => 'icinga2',
      db_password => 'password',
 }
}
</code>
So when I provision box I get postgres intall fine via puppet (using puppet-postgres module) then puppet throws errors on
<code>==> centos7: Notice: /Stage[main]/Vagrant/Group[vagrant]/gid: gid changed '1000' to '500'
==> centos7: Debug: /Stage[main]/Vagrant/Group[vagrant]: The container Class[Vagrant] will propagate my refresh event
==> centos7: Debug: Exec[postgres_schema_load](provider=posix): Executing 'su - postgres -c 'export PGPASSWORD='\''password'\'' && psql -U icinga2 -h localhost -d icinga2_data < /usr/share/icinga2-ido-pgsql/schema/pgsql.sql' && export PGPASSWORD='' && touch /etc/icinga2/postgres_schema_loaded.txt'
==> centos7: Debug: Executing 'su - postgres -c 'export PGPASSWORD='\''password'\'' && psql -U icinga2 -h localhost -d icinga2_data < /usr/share/icinga2-ido-pgsql/schema/pgsql.sql' && export PGPASSWORD='' && touch /etc/icinga2/postgres_schema_loaded.txt'
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns: psql: could not connect to server: Connection refused
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns:   Is the server running on host "localhost" (::1) and accepting
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns:   TCP/IP connections on port 5432?
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns: could not connect to server: Connection refused
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns:   Is the server running on host "localhost" (192.168.10.131) and accepting
==> centos7: Notice: /Stage[main]/Icinga2::Server::Install::Execs/Exec[postgres_schema_load]/returns:   TCP/IP connections on port 5432?
==> centos7: Error: su - postgres -c 'export PGPASSWORD='\''password'\'' && psql -U icinga2 -h localhost -d icinga2_data < /usr/share/icinga2-ido-pgsql/schema/pgsql.sql' && export PGPASSWORD='' && touch /etc/icinga2/postgres_schema_loaded.txt returned 2 instead of one of [0]
</code>
I see errors stating psql cannot connect but when I bring my vagrant box up, ssh in I see postgres installed running and listening fine. I can also connect using psql but puppet fails at creating schema on postgres as seen on debug output.
I also did login and executed same command for postgres schema load and it did work fine.
Why puppet is failing to load schema?
Comment: Have you tried manually running the command that's erroring and looking for a more detailed message?
Comment: I have tried that, logged in and executed `su - postgres -c 'export PGPASSWORD='\''password'\'' && psql -U icinga2 -h localhost -d icinga2_data < /usr/share/icinga2-ido-pgsql/schema/pgsql.sql' && export PGPASSWORD='' && touch /etc/icinga2/postgres_schema_loaded.txt` and it did work as expected
Answer: The release versions of that module are really really old, and not very good either.
You should start by trying out our current development state, currently still in a branch called "develop".
There are still some things todo until we reach a releasable state (in terms of cleanup and breaking changes).
You should have a look on the roadmap.


I intend to run a periodic routine. Which way could guarantee more precise delay? `nanosleep` or `signal through timer_create, timer_settime`?

Question: I intend to run a periodic routine.
Which way could guarantee more precise delay? nanosleep or  timer_create, timer_settime?
The type of their input argument is same(struct itimerspec).
It would be better if there could be a description about the internal implenmetation in your answer.
Could anybody help to make it clear for me?
I would be thankful for any hint on this question.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/214462/discussion-on-question-by-sunshilong369-i-intend-to-run-a-periodic-routine-whic).
Answer: The kernel uses the same clock source for both of them under linux.
And unless you're using a real-time OS, there are no guarantees of precise timing anyway.
So neither of them could provide you a precise delay.


New build Win7 workstation fails to see the DC (Server 2k8 ) but can see the DHCP/network just fine

Question: We have a new-build windows7 64 bit workstation that can't see the Windows Server 2k8r2 Domain Controller and therefore can't join the domain.  It is connecting to the network just fine, all drivers load correctly and DHCP (a linux DHCP box) assigns an IP address correctly.  However since the machine can't see the domain controller it can't join the domain and can't access its DNS services (the DC also acts as the DNS)
Other machines on the same unmanaged switch have no issues.
We are stuck.  Any suggestions?
Answer:
since the machine can't see the domain controller it can't join the domain and can't access its DNS services

This is nonsensical. You must use the DC's DNS service on the workstation in order for it to be able to "see" the DC.
It sounds to me as if your workstation isn't doing this. You say you are using DHCP, what DNS server/s are configured on your DHCP scope? You must only use your DC as the DNS server for internal clients, no other DNS servers must be used.
Comment: I agree.  I guess my limited knowedge is showing.  The DHCP passes out a perfectly valid IP address and the workstation can see the network.  However the WS cannot see the domain controller nor register with the domain.  Neither can ping nor communicate with the other as far as we can tell.  However the WS CAN see other machines on the network and ping/navigate to them.  I hope this clarifies my earlier post.
Comment: I guess I wasn't clear enough. Is your workstation using the DC's IP address for DNS?
Answer: Having never tried to get a Windows client to join a domain following accepting a lease from a non-Windows DHCP server, the following is a bit of a guess...
Firstly, using an "unauthorised" DHCP server - could this be affecting the way that the Network Location Awareness (NLA) service determines what sort of network you're plugged in to.  This, could possible be causing the Windows Firewall to be in "public" network mode.
Also, agree with ThatGraemeGuy - are you dishing out your DNS server address(es), such that the AD service location (SRV) records can be found?


What is the relationship between correlation coefficients and regression coefficients in multiple regression?

Question: Consider the model $ y = \beta_0 + \beta_1 x_1 + \beta_2  x_2 + \epsilon$.

What is the relationship between the correlation coefficients $r_{y,x_1}$, $r_{y,x_2}$ and the regression coefficients $\beta_1$ and $\beta_2$?
In particular, how to interpret a situation where a particular correlation coefficient is statistically significant but the corresponding regression coefficient is not statistically significant?
I recall reading a concept called "partial correlation coefficients". Is that in some way relevant in the above context?
Answer: Let's assume that the variable $x_1$ and $x_2$ are centered, it will make things easier (nothing prevents you to do that before doing your regression). Then, it is straightforward to see that:
$r_{y, x_1}\sigma_y=\beta_1\sigma_{x_1} + \beta_2r_{x_1, x_2} \sigma_{x_2}$
and
$r_{y, x_2}\sigma_y=\beta_2\sigma_{x_2} + \beta_1r_{x_1, x_2} \sigma_{x_1}$
Hence, the relation also involves standard deviations terms and the correlation between $x_1$ and $x_2$.
This should answer your second question. For example, if $r_{x_1, x_2}=1$ and $x_1 = x_2$, any solution $\beta_1\sigma_{x_1} + \beta_2r_{x_1, x_2} \sigma_{x_2} = \sigma_y$ leads to the same linear model for $y$. As a consequence, $\beta_1$ (or $\beta_2$) can take arbitrary values (which are going to depend on the numerical implementation of the linear regression you are using).
Looking at the value of $r_{x_1, x_2}$ is then critical before making any relation between $r_{y, x_i}$ and $\beta_1, \beta_2$.


Exporting plot panel as the same size no matter how wide the legend is

Question: I'm having trouble exporting plots in ggplot. I want to display my data using different variables in different plots and have the plot panel size export to the same size every time. My issue is that sometimes my legends are wider or shorter and R ends up smushing my plot to accommodate for the size of the legend.
I want the plot panel to print in the same dimensions every time, and for R to stretch the width of the image it exports to accommodate the varying sizes of legends.
p1
p2
library(ggplot2)
my_data <- data.frame(
  Name = c("Alice Smith", "Eduardo Fernandez", "Steven Brown"),
  Age = c(25, 30, 22),
  Gender = c("Female", "Male", "Male"),
  Height = c(165, 180, 175))

p1 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender))+
  geom_point(size = 2, stroke = 1)
p1

ggsave(filename = "p1.png",
       plot = p1,
       device = "png",
       height = 7,
       width = 10,
       units = "in",
       dpi = 500,
       bg="black")
dev.off()

p2 <- ggplot(data = my_data, aes(x = Age, y = Height, color = Gender,shape=Name))+
  geom_point(size = 2, stroke = 1)
p2

ggsave(filename = "p2.png",
       plot = p2,
       device = "png",
       height = 7,
       width = 10,
       units = "in",
       dpi = 500,
       bg="black")
dev.off()

I know that technically you can do this by making your export width wider or smaller and checking every single time to make sure that the panel is the same size but it's so time consuming. I have been painstakingly exporting the plots .2 inches wider at a time and checking to see if the panels are exactly the same until I get it right. There must be a better way.
Comment: relevant question: https://stackoverflow.com/questions/53285493/explicitly-set-panel-size-not-just-plot-size-in-ggplot2
Answer: As described further in the help, patchwork has the get_dim and get_max_dim functions so you can apply the plot dimensions of another plot.
library(patchwork)
set_dim(p1, get_max_dim(p1, p2))

and set_dim(p2, get_max_dim(p1, p2))

test using ggsave:
set_dim(p1, get_max_dim(p1, p2))
ggsave("p1.png", height = 3)

set_dim(p2, get_max_dim(p1, p2))
ggsave("p2.png", height = 3)

Comment: Thank you! This worked in my R plot viewer but when I exported them using ggsave the dimensions were still off. Is the problem with ggsave? is there something else I can use that's better?
Comment: Can you share a reproducible example of it not working using ggsave? I've edited my answer to show an example that worked as expected.


Why do composers use seemingly/unecessarily complex time signatures?

Question: I see this all the time: In the piece I'm currently analysing (Sei Quartetti Brevi by Sciarrino), the composer uses 7/16 + 4/8 in the first measure, followed by 5/8 + 3/8 in the second, followed by 5/8 + 4/8, etc. etc.
The only reason I can see doing this sort of thing is to create a feeling of timelessness. Can anyone help me understand why contemporary (and not-so-contemporary) composers use such complex time signatures?
Why not instead of using 7/16 + 4/8, you just use 7/8 + 4/4? It would be significantly easier to read for the performers, and easier to notate imo.  So why bother?
Comment: The rock group Rush is known for complex time changes, and most certainly there is not a sense of "timelessness" in their music. To the contrary, their songs drive forward with a strong and definite rhythm.
Comment: Unless it is a copying error on the publicists part, I don't believe I'm mistaken.  I'd be happy to send you the score if you want to see for yourself.  It's available for free @ http://en.scorser.com/S/Sheet+music/sciarrino/-1/1.html
Answer: If we use 'em, it's because they seem necessary to us. It might be that we need an irregular effect for expressive purposes; it might be that if we don't group the notes just so, the lines won't line up properly together rhythmically; it might be that we need them to avoid arriving at a definite downbeat until exactly the right time, and that irregular "sprung" rhythms are the right way to do this.
Without the score, I can only speculate about Sciarrino's reasons, but I'm listening to the Arditti Quartet playing the Sei Quartetti as I type this, and I don't think timelessness is what he was aiming for: this isn't Messiaen-like stasis, nor is it pointillistic "moment form". (It's actually pretty continuous for '70s New Music, as compared to what I recall from the concerts I took in back then.) In Sciarrino's case, I think the 2nd reason I gave above predominates, although the other two certainly have a place as well.
I suspect that the 7/16 measure you are talking about was probably in there to add a long beat to what would otherwise be 3/8. That's speculation on my part, but it would fit what he seems to be doing. Messiaen used to do that all the time in his livelier pieces.
Changing metres of this sort aren't limited to use by the avant-garde. I did something very similar near the end of my own chorale prelude on Aus tiefer Not schrei' ich zu dir:
(BW refers to "Brustwerk", i.e., a change of manual.)
The full score is at the Orgelbüchlein Project, and a demo on SoundCloud here - the passage starts at about 3:05. I think that, by most people's standards, this would be considered a somewhat conservative work (the kind of material is certainly very different from Sciarrino), but the reasons for the changing metres are very similar.
Comment: Just wanted to add that I also use time signatures for the above reasons, as well as to elongate or truncate specific beats à la Messiaen. We also use them to rhythmically modulate the beat center (to create various rhythmic and agogic effects). Lastly, it would be remiss not to mention that *some* composers do it because they think it makes them look cool / smart. Other composers think it makes their music look fancy. Other composers do it because they like to make people feel uncomfortable. Still others reject the idea of the 4/4 box where everything is filled in like ravioli.
Comment: Yeah, I was a little remiss - one can _advance_ the structural downbeat (as well as delay it). It even comes about for other reasons as well. That repeated note line in the tenor, which imposed the metric modulation and irregular metres, is actually the antiphon "De profundis clamavi ad te" from the Office of the Dead in the Liber usualis (it's a very ecumenical chorale prelude), so sometimes it even comes about through the accommodation of existing materials. As for the rest, well, I try to ignore the pseuds...
Comment: yes, don't we all? I believe the tendency is for them to get lost in the noise of contemporary pablum.
Answer: There are a couple things I consider when choosing time signatures.  I don't write music quite like this but I can see a few reasons why something like this might take place.
Generally speaking, it is easier to maintain a tempo than to switch.  So when a composer is going from one time signature to another, it is easiest to maintain the tempo and use different subdivisions to spell out your new time signature, rather than changing the tempo to keep the time signature easier to read within.  This tends to make more sense when the piece frequently changes time signatures and less sense when the piece changes from one time signature to another that will last for an extended time.
This next part is not exactly a standard convention within the tradition but seems to be generally followed in many settings and makes intuitive sense to most I speak with about it.  I like to make the distinction between different denominators within a meter.  A simple example: 4/4 and 8/8; 4/4 is best used to describe a standard rhythm with 4 beats, while 8/8 is the same amount of eight or quarter notes, it is best used to describe groupings within that time that amount to uneven beats.
4/4: 1 + 2 + 3 + 4 +
8/8: 1 + a 2 + a 3 +
Let's translate this concept to another meter: 5/4 vs 5/8.  I think of 5/4 as having 5 equal beats (1/4 notes), while 5/8 would have 2 uneven beats with 3 and 2 eighth notes.
5/4: 1 + 2 + 3 + 4 + 5 +
5/8: 1 + a 2 +
So when starting from scratch and trying to choose a meter, I would base my choice on the beats.  Once a piece is established, your choices become a little different but the same concept can apply.  It may be best to write something in one meter to maintain tempo, or it may be best to change your tempo to accommodate the new feel of your change in meter.  For instance, going from 4/4 to a sort of double time, it may be best to write 4/8.  This allows the measure to maintain 4 beats without needing to specify the double time and by not maintaining the length of a bar (4 1/4 notes) we do not introduce the confusion of an 8/8 time signature, which would imply the uneven beats as described above.  This would also apply to double time in 3/4, where switching to 6/8 (maintaining the length of the measure) would imply a change in the length of the beat (6/8 is nearly always 2 beats of 3 eighth notes, which would subvert the intention of double time).  Again, this will largely depend on how long this new meter will be utilized.  It will ultimately be easier to read something in 4/4 than 4/8, especially if there are a lot of subdivisions, so changing the tempo to write 4/4 would be preferred if the double time would appear for an extended time.
As others have suggested, it sometimes seems that composers have taken this approach to be more complicated or just because they can.  However, when listening to some composers, it just makes sense.  Think of Stravinsky.  In The Rite of Spring the meters change all the time but when I listen to the piece it just sounds right.  I also tend to think that a lot of people don't fully understand a piece of music when they make some sort of judgement about whether or not the use of certain time signatures is justified.  There is always some sort of intent.  I have conceptualized writing a piece that would include what would normally be considered poor choices for meters with the intention of making it harder for the players to read, which could add the effect of chaos or confusion, allowing it to convey an intended feeling when performed without directing the players as such.  I have seen a performance of a piece that has a similar approach with a little more depth of concept, Failing.  The idea being that the piece is intended to be difficult for the sake of being difficult, with the additional depth being that the intention of the composer is to have the performer fail and by successfully performing the piece, you are also failing.
In the piece that you are analyzing, it seems that nearly all of the measures with less than conventional meters start with a rest (not all though).  So it appears that the Sciarrino wanted a specific space to appear between phrases that would not be properly accommodated by a rest at the end of the previous measure.  This also allows the piece to maintain a feeling of being off of the beat, though nothing at the beginning seems to provide a pulse to be off of, the off beat feel will be translated by the performers.  I would argue that the use of the time signatures in this case would be somewhat to space out the phrases.  Similar circumstances could be an instance where another composer may employ a fermata but by adjusting the time signature and adding a rest would specify the length, though in this case nothing is being sustained.
There are lots of reasons one might choose to have complex and changing time signatures but it is generally safe to say that it is not arbitrary.  Specifically to the point of x/4 vs x/8, there can be larger implications than readability, including beat allocation within a measure/subdivisions of beats as well as preserving tempo, which can ultimately be more readable.  As a final note, I wrote a lot of music that was essentially free of meter, as in it would constantly change meter if analyzed by phrases.  My composition teacher, the late Dr. Packales, advised me once that leaving the pieces in 4/4 as I did may ultimately be easier and more readable for the performers.  I liked the idea at the time because it made me feel unique or something but in the end, a lack of time signature changes would more likely leave the performer needing to analyze the piece to determine not only phrasing but beats, making it harder to get a proper feeling for whether something takes place on a downbeat or an upbeat etc.
Comment: Yeah, I got the impression he was using irregular measures to coordinate things, although I didn't catch the use of rests at the beginning of the bars (hard to do without a score). I noticed a few voices making staggered entries that appeared to come in at somewhat irregular intervals, although they fit together quite well.
Comment: Cripes, I missed the link for the score. I see what you mean about the rests. I suspect that's because he's trying to give an impression that the notes are starting from _niente_ and ending there.
Comment: Yeah, for this piece it offers some insight but there are/have been plenty of composers that use complex time signatures, so that bit of analysis wouldn't necessarily translate to other pieces, hence my extended babbling.  I'm rather long winded.
Answer: Note that much of the real problem is that our notation is simultaneously too rigid and not expressive enough. It often does not reflect real performance accurately both because it can't convey that level of detail and because getting even close to real accuracy would make impossible to read and practice from. There are things in traditional musics which are almost impossible to express in our notation, yet easy to demonstrate and learn by ear... even a stretched measure (fairly common in folk dances) is awkward. That forces some workarounds. This is one.
(And our time signatures are trivial compared to, eg, Indian classical music. They approach rhythm very differently. But that's another topic.)
Comment: Indeed, I think one problem is that time signatures are generally expected to go at the start of a measure where the time changes.  In "The twelve days of Christmas", the time should change from three to four right at the pickup "and a | par-tri-idge in a pear | tree", but notation can't accommodate that; thus "two-oo tur-tle doves, and a" is notated as a 4/4 measure rather than a measure that starts out in 3/4 measure and changes to 4/4.
Answer: (7/16 + 4/8) is exactly the half of (7/8 + 4/4), then it's completely different.
Why do contemporary composers love complex time signatures? I think that often their use is not justified as it could be in the music from the first half of 20th century. For me a good contemporary composer always writes music taking into account performers needs, and never makes music difficult only for the fun of it.
Answer: Many contemporary composers prefer to divide time unevenly, and some don't divide time into anything at all (the timelessness feeling that is mentioned in the question). This is contrary to the approach in most music genres that divide time into equal grids. But consider that there is a big cultural reservoir of styles and notation built around this equal grid idea.
Contemporary composers make use of this cultural reservoir to translate the music in their mind with unorthodox time use to the performers accustomed with the wide spread music culture. So it is still practical to use a wide known standard notation that every musician and composer is accustomed to read and play.
There are also stylistic preferences. Defining measures like that may be the only way to translate what's in composer's mind. If there are frequent changes in measure, it is possibly because the composer wants to tell something with that notation. It can be a non-repeating rhythm structure, accenting...etc that a composer aims that the players would intuitively give that output when that notation is used.
Also that kind of measure notation is actually easier for players to understand what's going on in the music, count the bars, play the accents and dynamics correctly...etc. And again, it is generally used if the composer has some intention to make use of something related with that use (like accenting). If you rewrite the same music for example in 8/8, the interpretation of that would usually be a different music and that would be harder for musicians to understand what is going on in the piece.
There are also some contemporary composers write in 4/4 for ease but the music is totally independent from anything related with the measure. Here the intention of the composer is totally different than the above. This is more close to the timelessness feeling mentioned in the question.
So in short, it is all about communication. Notations are only translations of what's going on in our mind.
I suppose the question is about the notation, not composer's preferences. I think why don't contemporary composers divide time into equal grids is another question to be discussed.
Answer: I think in modern music, especially when you start reaching into the grounds of progressive metal, they simply do it because they can, whether it's to show technical prowess or just because they "happened" to come up with a cool riff that's in 13/16 time.
It also entirely depends on the situation. If it's anything like what I described above, the answer is most likely because they can, simple as. In other contexts, it could very well be used to show timelessness, helplessness, etc.
Comment: Maybe partially a response, but still looks like an answer to me.


Reading value from Firebase Android and update it

Question:
I want to get productQuantity value and update it:
private void updateValue() {

        try {
            newQuantity = Integer.parseInt(editTextQuantity.getText().toString());
        } catch (NumberFormatException e) {
            editTextQuantity.setError("Enter Charger Quantity");
            return;
        }

        DatabaseReference mReference = FirebaseDatabase.getInstance().getReference();
        mReference.child("goods").child("charger").orderByChild("productQuantity").equalTo(quantity)
                .addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        dataSnapshot.getRef().setValue(newQuantity);
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

    }

I used addChildEventListener but it did not work on quantity the old value and newQuantity the new value.
Comment: Try: equalTo(quantity + "") to convert quantity to string since you keep quantity as a string in the database.
Comment: quantity stored in database as int
Comment: In the screenshot you shared the quantity is stored as a string, as shown by the quotes around the value.
Comment: It's an old screenshot before I make some changes to the code anyway I've replaced it
Answer: Let's take an example. Let's say we want to get the product which has the productQuantity property set to 362 and we want to increase it by 10. To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("goods").child("charger").orderByChild("productQuantity").equalTo(362);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int productQuantity = ds.child("productQuantity").getValue(Integer.class);
            int newQuantity = productQuantity + 10;
            ds.child("productQuantity").getRef().setValue(newQuantity);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);


Why does the Php exec function, returns Array( )?

Question: I am working on a php script that tries to get the username of the person on a given computer on a server.
Here's the code im using
exec('wmic COMPUTERSYSTEM Get UserName', $user);
    print_r($user);
And when ever this runs i always get back  Array( )
Any help would be greatly appreciated.
Answer: You cannot use exec to return any output from your command.
See this answer.But you can use shell_exec() to return the output of your command.
You can have an array of computer:
$computer = array('comp1', 'comp2');
$comp1 =  array();

foreach($computer as $username)
{
    $comp1 = shell_exec("wmic /node: ". $username ." computersystem Get UserName");
    print_r($comp1);
}

But if there is only one:
$user = shell_exec('wmic /node: <yourcomputername> COMPUTERSYSTEM Get UserName');
print_r($user);

But i suggest to get logged users, there is a tool from sysinternals that i used to do certain task like executing process remotely, list info about the system through command prompt.
Checkout and install PSTools. Then you can use the PsLoggedon.exe
Comment: So how should i be printing this? should i just echo the shell_exec? or is there a certain way i should do it?
Comment: do you have an array of $user that you want to automate?
Comment: can you elaborate what you mean by automate?
Comment: are you going to run the command with one user only or you have a list of user stored in an array and want to get their usernames?
Comment: I have a list of different computers, and im checking to see if there is ANYONE logged onto it. and i believe only one person can be logged on at a time.
Comment: Sorry i just saw the edit, I am aware of PsLoggedon, however I do not have the capability to install PsLoggedon to the machines on my server(Its a school server, and i have admin privileges). I wanted to use `wmic` because then all i would need to do is put in the admin username and pass to get access to all the computers in the school.
Answer: exec always return a array, if the output argument is present
See: http://www.php.net/manual/en/function.exec.php
If your code return only one user, try this:
$user = shell_exec('wmic COMPUTERSYSTEM Get UserName');
echo $user;

shell_exec manual:
http://www.php.net/manual/en/function.shell-exec.php
It may be disabled if PHP is in safe mode.
Look:
https://www.php.net/manual/en/features.safe-mode.functions.php
You can check your server's PHP settings with the phpinfo() function.
Comment: hmm when i tried it, i didnt get any output, ill keep trying :)
Comment: Should i put the full path for this command in the ()'s? if so what would that look like?
Comment: just checked and it says safe_mode is off.
Answer: You have to specify the array this way: print_r($user[1]);
exec('wmic COMPUTERSYSTEM Get UserName', $user);
print_r($user[1]);


Scaling in SVM (why and how to , plus references)

Question: Hi I know why feature scaling is preferred in SVM, I have two questions:
1-does anyone know of legit articles of books explaining it. I am writing my thesis and I need references. It doesnt have to be for SVM specific, even if it is for Neural Networks or other supervised learning algorithms it will be appreciated.
2-Other than the referencing part does anyone have another source for more explanations on the scaling or rescaling of inputs.
Thanks
Answer: You can find this in "Elements of Statistical Learning" (http://web.stanford.edu/~hastie/local.ftp/Springer/OLD/ESLII_print4.pdf)
on page 398. This is for neural nets.
Also, this is a very nice article that you can look at for more info on implementation (http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-16.html)


Determine an interval of values for the parameter λ ensuring that the following equation is valid: $−2200=−(45+λ)x_1−(80+λ)x_2 $

Question:
Determine an interval of values for the parameter λ ensuring that the following equation is valid: $−2200=−(45+λ)x_1−(80+λ)x_2$

My attempt :
Note that for different values of $\lambda$, the equation represents an equation of a straight line.
Putting $x_1=0\ $ and $x_2=0\ $ we see that for any value of $\lambda\ $ the L.H.S doesn't match with the R.H.S.
Hence for any value of $\lambda\ $ these equations represent straight lines not passing through origin.
So we can write $$−2200=−(45+λ)x_1−(80+λ)x_2 \\ \implies \frac{x_1}{\frac{2200}{(45+\lambda)}}+\frac{x_2}{\frac{2200}{(80+\lambda)}} =1$$
So from this we can see that $\frac{2200}{(45+\lambda)}$ and $\frac{2200}{(80+\lambda)}$ must not be undefined i.e.$\ (45+\lambda)$ and $(80+\lambda)$ must be non-zero.
Hence $\lambda \ne -45,-85$. Thus the admissible values are all real numbers except $-45$ and $-85$.
Is my solution correct?
Comment: Hi! How do you define "an equation is valid"?
Comment: It was given to me like this. I think "valid" means that the equation is consistent.
Comment: If you draw a $x_1Ox_2$ plane then this equation is parametric line, where $\lambda$ is parameter. So you have infinitely many solutions for any $\lambda$.

ANY equation is valid, no matter how many solutions it has. It is strange to ask if an equation is valid.
Answer: You have divided by $45+\lambda$ and $80+\lambda$.  If you plug $\lambda = -45$ into the original equation you get $-2200=-35x_2$, which is a fine equation with the solution $x_2=\frac {2200}{35}$ and $x_1$ can be anything.  If by a valid equation you mean one that does not have any division by $0$ or one that can be satisfied, any $\lambda$ yields a valid equation.
Comment: You are right. I didn't think about this case.


What fonts or typefaces were commonly used in old (pre-1950) mathematics literature?

Question: I recall reading some books in my university library which were published in the 1920s and 1930s, and am wondering about their fonts. They looked very nice, and I would like to find some. It seems Monotype Modern was one such font, but it somehow costs hundreds of dollars despite the fact that its creator has been dead for a century.
Are there open source versions of such classic mathematical fonts?
Comment: The [History of Science and Mathematics StackExchange](http://hsm.stackexchange.com) might be a better place for this question. *Possibly*, people on the [TeX StackExchange](https://tex.stackexchange.com) might have insights.
Answer:
Hint:  Some related information is given in Mathematical Typography by D.E. Knuth from 1979. He discusses  aspects of the development of typography used in AMS Transactions from 1900 up to the late 1970s  in order to introduce $\TeX$ and $\mathrm{METAFONT}$.


Como declarar uma função dentro de outra função em C#?

Question: Em Delphi é possível declarar função dentro do bloco de uma determinada função, veja este exemplo feito em Delphi:
procedure TForm1.btnRunClick(Sender: TObject);
begin
  mostrarNome('Carvalho');
end;

function TForm1.mostrarNome(nome: String): String;
  function transformaMaiuscula(str: String): String;
  begin
    Result := UpperCase(str);
  end;
begin
  ShowMessage(transformaMaiuscula(nome));
end;

A saída será:

CARVALHO //Em letras maiúsculas

Sendo assim, eu gostaria de saber se é possível fazer o mesmo em C#, declarar uma função dentro de outra função. Veja este código em C#:
class Program
{
    static void Main(string[] args)
    {
        mostraNome("Carvalho");

        Console.ReadKey();
    }

    static void mostraNome(string nome)
    {
        static string transformaMaiuscula(string str)
        {
            return str.ToUpper();
        }

        Console.WriteLine(transformaMaiuscula());
    }
}

O código em C# acima não funciona, o compilador diz que a sintaxe é inválida, porem, ele serve apenas como ilustração.
Existe um meio de fazer isto em C#?
Answer: Gambiarra
Até o C# 6 a única forma era o uso de lambda que nada mais é que um ponteiro para função (eventualmente pode armazenar variáveis capturadas também), assim é possível escrever o corpo de uma função e armazenar em uma variável ou passar como argumento, ou ainda retornar na função que foi declarada.
Func<string string> transformaMaiuscula = (string str) => str.ToUpper();
transformaMaiuscula("Teste"); //obviamente pode fazer o que quiser

Esse recurso é um açúcar sintático em cima de delegates.
Ele existe desde o C# 3. No C# 2 existia a sintaxe do delegate que é parecido com a sintaxe da lambda, porém menos conveniente. Em C# 1 existia o delegate, mas a sintaxe era tão inconveniente que tinha que declarar o delegado e depois declarar e definir um método separado, ou seja, nem podia declarar dentro de outro método.
Func<string string> transformaMaiuscula = delegate(string str) {
    return str.ToUpper();
};
Console.WriteLine(transformaMaiuscula(nome));

Esse Func<string string> é um delegado já declarado pelo .NET, para sua conveniência. Em outras circunstâncias também poderia usar um Action e muito eventualmente um Predicate. Só o Predicate existia no C# 2, o que era bem limitante, e que obrigava na prática declarar o delegado fora do método.
Não vou nem usar o exemplo do C# porque sequer parece com o que está sendo pedido, mas a declaração do delegado seria delegate string transformaMaiuscula(string str), depois é declarar o método com a mesma assinatura. A declaração vai dentro de um tipo, mas não dentro de um método.
Note que usar um delegado com sintaxe de lambda é bem diferente de usar um método normal. Até pode simular essa ideia, mas elas possuem características diferentes. E é uma tremenda gambiarra fazer isso. Inclusive tem consumo de memória, gasto de processamento e possível perda da confiabilidade em casos mais complexos se o programador não tomar certos cuidados.
Se você precisa de um delegado aí tudo bem, pague o preço de usá-lo. Não é o caso da pergunta.
Sintaxe lambda fora do método
C# 6 permitiu inclusive que a sintaxe de lambdas fosse usada em qualquer método, assim quando o método é muito simples dá para declarar seu corpo de forma mais simples. Ele passou ter a sintaxe da lamba, mas não sua semântica. Só foi possível usar em métodos normais dos tipos.
string transformaMaiuscula(string str) => str.ToUpper();

Não que isto ajude a pergunta, coloquei como curiosidade porque as pessoas demoram para se acostumar com recursos novos.
Solução correta
Ai pode-se pensar: vai se fazer o que se não tem outra coisa? Pois bem, eu não usaria uma lambda quando só se deseja um função local (aninhada), como mostra a pergunta. Minha solução, e esta é a recomendação oficial, é simplesmente desaninhar a função. Apenas crie um método separado, provavelmente privado e estático e chame-o onde precisa.
Ele só tem um inconveniente, outros métodos da classe poderão chamá-lo. Mas é algo administrável e não gera nenhum outro custo.
private static string transformaMaiuscula(string str) => str.ToUpper();

Aí dentro do seu método simplesmente chama o método transformaMaiuscula() como outro qualquer.
C# 7
No C# 7 já é possível usar a sintaxe de função local, assim não paga preço algum e não corre risco, nem mesmo de permitir a chamada desta função por outros membros da classe.
A sintaxe é quase a usada pelo AP:
static void mostraNome(string nome) {
    static string transformaMaiuscula(string str) {
        return str.ToUpper();
    }
    Console.WriteLine(transformaMaiuscula(nome));
}

O static foi permitido na sintaxe, ele dá mais segurança para evitar capturas indevidas de variáveis no contexto maior.
Note que você pode declarar o método local depois de usá-lo. Não é possível fazer isto com lambda, a declaração deve vir antes sempre.
De forma simplificada poderia usar assim:
static void mostraNome(string nome) {
    static string transformaMaiuscula(string str) => str.ToUpper();
    Console.WriteLine(transformaMaiuscula(nome));
}

Coloquei no GitHub para referência futura.
Answer: Diretamente, não. Mas você pode declarar uma Action ou delegate, ou ainda Func<>, que é quase a mesma coisa.
using System;

public class Program
{
    delegate void Teste2();

    public static void Main()
    {
        Action Teste = () =>
        {
            Console.WriteLine("Teste!");
        };

        Teste2 teste2 = delegate() {
            Console.WriteLine("Teste 2!");
        };

        Func<string, string> teste3 = delegate(string argumento) {
            return argumento + " " + argumento;
        };

        Teste();
        teste2();
        Console.WriteLine(teste3("Buemba!"));
        Console.WriteLine("Hello World");
    }
}

Fiz um Fiddle.
Resultado:
Teste!
Teste 2!
Buemba! Buemba!
Hello World

A diferença entre eles é que delegate precisa ser fortemente tipado. Action é um pouco mais dinâmico, mas não retorna valor algum. Para retornar valores, use Func<TArgumentos, TRetorno>, onde TRetorno é o que será retornado e TArgumentos são os tipos dos argumentos.
Comment: Só para conhecimento, já tem uma proposta aprovada para o C# 7 que trabalha justamente com a ideia que a pergunta tinha, ela se chama "Nested local function". https://github.com/dotnet/roslyn/issues/259
Comment: Sim, vou editar com mais um exemplo.
Comment: É possível eu especificar um parâmetro e um retorna para a Action?
Comment: Acho que agora tem tudo.
Comment: Sim, mas vou fazer outra pergunta a respeito do `Func<>`.
Comment: Ok, fique à vontade :)


Drupal 7 Views Table Blocks Common Fields Sorting not working in single page

Question: My site having dashboard page where I am displaying multiple Views blocks (2-3) with Table format. Each block have few common fields to display with different filters. These blocks have exposed form as well.
The issue I am facing with SORTING on common fields. The fields which are not common, sorting on those are working as expected. Filter and Paging are also working fine on each block as I have set different page id for those.
Do you have any idea how to make those sorting possible ?
Note: Ajax is ON in each block and machine id is also set different.
Answer: You need to change the Filter identifier under the More fieldset at the bottom of the exposed filters in the View
Comment: Thanks for the answer. This is working for node and entity BUT og group have some limitation. Sorting is not working for OG case. Do you have any idea on those ? Please do needful.


Estimate monotone function from noisy obsersations

Question: Assume that $y=f(x)$ is an unknown monotonically increasing function of variable $x$. We have access to $N$ observations of this function given as tuples $(x_i,y_i)$, such that $y_i=f(x_i)$. The problem is to estimate $f(.)$ from this observations. In the noise-less case, they obey the monotone condition that $f(x_i) < f(x_j)~,~\forall x_i < x_j$. In the noisy case, some of the observed samples may no longer obey the monotone condition though the majority might be. I am unfamiliar with this kind of problems. Is this specific problem studied in literature? If not, can you point me to the techniques which are used in similar kind of problems?
I did a bit of my own research and Isotonic regression seems like a candidate to me. Is that right?
Comment: this question may be of use https://stats.stackexchange.com/questions/272881/regression-with-constraints
Answer: Yes Isotonic regression is a classical solution when the output is continuous. This however creates a rather non smooth function: https://en.wikipedia.org/wiki/Isotonic_regression.
When the output is discrete, then you can use ordinal regression. If you discretize $Y$ first (define interval slices), you can still use it. And then interpolate.
Finally you can use a parametric method. Define a set of functions with parameters $a,b,c...$ that are increasing for any parameter. Then fit with least squares (or maybe better: with canonical GLM to have no bias).
This is an example of fitting with such functions:

red: raw noisy data
yellow: $f(x)=a^2x^{b^2}$
green : $f(x)=(a^2x+b^2)\left(1-\frac{1}{1+c^2x}\right)$.

(using squares everywhere is a trick to force positive values)

I would naturally use the parametric method is most situations I've known because this creates a very smooth interpretable curve and it is very easy to implement.
Comment: original function I have might actually be non-smooth. For eg, it can have stair-case type of behavior. In those scenarios, does a smooth approximation make sense?
Comment: You can also look into monotone splines


Find the root in the form $a+bi$

Question: $(2-i)z^2-(1+i)z+1$, with $z=i$ as a root. There's supposed to be another root in the form of $a+bi$.
When I factorised it, it became $(z-i)[(2-i)z+i]$, which looks nothing like the $a+bi$ form.
Did I factorise it incorrectly?
Comment: if you find one root, you can always use sum/product of roots of a quadratic to find the 2nd root
Answer: Guide:
Let $(2-i)z+i = 0$
Solve for $z$.
Multiplying the conjugate of the denominator of a fraction to both the numerator and denominator helps.
Comment: Right; thank you! I didn't see that earlier.

Find the root in the form $a+bi$


Proving extended AM-GM inequality using a monotonic function

Question: The AM-GM inequality is a known one, it states that for any list of n numbers, the following is true:
$$ \frac{x_1 + x_2 + \text{...} + x_n}{n} \ge \sqrt[n]{x_1 \cdot x_2 \cdot \text{...} \cdot x_n }$$
But there are other important statistic means in math, such as the harmonic mean:
$$ H =\left(\frac{\sum_{k=1}^n x_k^{-1}}{n}\right)^{-1}$$
Or the root mean square:
$$ X_\text{rms} = \sqrt{\frac{1}{n} (x_1^2 + x_2 ^ 2 + ... + x_n^2)} $$
The AM-GM can be extended with these means. More specifically, given any list of numbers:
let A be the arithmetic mean, GM be the geometric mean
let H be the harmonic mean and $X_\text{rms}$ bet the root mean square
The following is true:
$$ X_\text{rms} \ge A \ge GM \ge H $$
All of these inequalities can be proven using mathematical induction, and it is a well-known proof.
But I want to consider a different approach:
$ \text{For any list of n numbers, let's define the function }$
$$ S(p) = \left( \frac{x_1^p + x_2^p + \text{...} + x_n^p}{n} \right) ^ \frac{1}{p} $$
$ \text{Then} $ $ H = S(-1) $, $ A = S(1) $, $ X_\text{rms} = S(2)$
$ \text{Notice that}$ $GM = \lim_{p \to 0} S(p) $
So we can say for sure that $S(2) \ge S(1) \ge S(p \to 0) \ge S(-1) $.
We then make the hypothesis that $ S(x)  \text{is monotonically increasing on the set of real numbers }$
My question is how to prove this hypothesis? Ideally, your answer would also contain a proof of $\lim_{p \to 0} S(p) = GM$ as I figured this one out on pure intuition.
P.S I am in the last grade of school right now, so no high-level math (Higher than basics of calculus or complex numbers theory) would be prefered. Still, though, any help would be very much appreciated!
Comment: You should at least learn asymptotic expansion (see links from my profile), so that you can immediately confirm systematically yet rigorously your guess that the power mean tends to the geometric mean as the power tends to zero.
Answer: This is shown in many places.
There is a proof
using Jensen's inequality
 in
https://en.wikipedia.org/wiki/Generalized_mean
One book I like is in
chapter 8 of
THE CAUCHY–SCHWARZ
MASTER CLASS
An Introduction to the Art of
Mathematical Inequalities
by
J. MICHAEL STEELE
It's available in both
soft-cover and digital.
https://www.amazon.com/Cauchy-Schwarz-Master-Class-Introduction-Mathematical-ebook-dp-B00KILLJLA/dp/B00KILLJLA/ref=mt_kindle?_encoding=UTF8&me=&qid=1569430702
Other good references are
INEQUALITIES
BY
EDWIN F. BECKENBACH
AND
RICHARD BELLMAN
and
the classic
Inequalities
by G. H. Hardy, J. E. Littlewood, G. Pólya
Comment: Are there any free online resources where I can see this proof? I think it would be strange to buy a mathematics book for only one proof...
Comment: I did a search for "generalized mean" and found the reference I added to my answer.


Como tratar calendário no banco de dados

Question: Olá,
Estou fazendo um projeto pessoal, para praticar programação e me deparei com uma situação que estou com dificuldades para resolver. Um usuário tem uma rotina que se repete semanalmente, onde cada dia da semana ele tem tempo livre diferente, por exemplo:
Segunda-feira ele tem de 17 às 20h livre, já terça-feira tem das 8 às 14h, e assim vai até domingo, mas na próxima segunda ele tem o mesmo horário livre, das 17 às 20h livre.
Qual é o melhor método de guardar esses horários de tempo livre em um banco de dados MySQL. De forma a ser eficiente e ocupar o menor espaço possível?
Answer: Tabela: HorariosLivre
id*   |usuario_id  |  dow   |   hora_inicial   |   hora_final
 1         1           2             17                20
 2         1           3             08                14

onde, usuario_id é fk para tabela de usuarios, e dow é o 'day of week' ou seja, dia da semana, sendo domingo = 1, e sábado = 7.
veja mais sobre a função do mysql, DayOfWeek():http://www.w3resource.com/mysql/date-and-time-functions/mysql-dayofweek-function.php


std::allocator: Is constructing on unallocated memory in C++ allowed?

Question: So I am relatively new to C++, and I recently encountered the std::allocator class. I understand that this is a powerful tool used in creation of vectors, lists, deques, etc. and I am trying to learn more about it.
One thing that confuses me is the following:
For example, if we define some allocator<int> denoted as alloc, and we use it to allocate n locations in memory via auto const b = a.allocate(n), where b is the pointer to the first int element in the allocated memory, then, one is also obliged to construct the allocated memory in order to actually access it, right?
If we introduce some iterating pointer auto e=b, then the construction can be performed via alloc.construct(e++,int_obj), where int_obj is some user-initialized object of the type int. This is all nice and tame as long as the total amount of calls to construct is less than n. However, I am not quite sure what happens when the number of user calls to construct exceeds n. I initially expected some warning or error message to rear its ugly head, however nothing happened. As a simple example, here is the snipped of the code I tried to run:
int n{ 0 };                            // Size of the array is initialized to 0.
cin >> n;                              // User reads in the size.
allocator<int> alloc;                  // 'alloc' is an object that can allocate ints.
auto const b = alloc.allocate(n);      // Pointer to the beginning of the array.
auto e = b;                            // Moving iterator that will point to the end of the array

for (int i = 0;i != 10;++i)
    alloc.construct(e++, i);           // We start constructing 10 elements in the array, regardless of the size n, which can in principle be less than 10.
for (auto i = b;i != e;++i)
    cout << *i << "\t";

Initially I run this code for n=1, and all works nice; it prints out digits from 0 to 9, even though I allocated space only for one digit. That is a red flag already, right? Then I change n to 2, and program breaks after printing the digit number four, which is more what I expected.
What I conclude from this behavior is that trying to construct memory yet unallocated via std::allocator is undefined and unpredictable, and as such should be avoided (which is obvious to begin with). But, this seems as as extremely dangerous pitfall, and I wanted to know if there is some build-in workaround in C++ that will always prevent user when trying to construct unallocated memory.
Comment: C++ is not a memory-safe language. There are plenty of ways that you can produce _undefined behaviour_ - which may crash, or may do something unexpected, or may "work" as intended - this is one of them. The fact that it seems to "work" for n=1 is coincidence. In general, it's best to avoid manual allocation if possible. Especially, you should rarely need to use `allocator` directly; In this case `new int[n]` would do the job just fine. But then, many would say you should avoid "raw" arrays as well...
Comment: In that case it allocates another (larger) array, copies/moves the elements from the original array into the new one, and deallocates the old one. It is never correct to allocate a certain amount of storage and then use more than what was allocated (even if it doesn't always cause a segmentation fault, it cannot be expected to behave in any reliable way).
Comment: @davmac :  I am aware that one can dynamically allocate an array, but, as an exercise I try to emulate how simple vector class works. Vector class has a nice limitation, that will initially allocate some memory for followup elements, and whenever new element is added to the vector, new object in vector will be created in order to hold the element. However, there are cases when we want to add new element, but the space allocated previously is already full, so vector needs to know to allocate more memory. It does that without user's knowledge. This principle I want to understand.
Comment: have a look at this two links: http://www.gotw.ca/gotw/008.htm  http://www.stroustrup.com/except.pdf
Comment: Yes, constructing an object on non-existent memory is a dangerous pitfall. It is the programmer's responsibility to ensure that doesn't happen, by using clean technique. Acommon guideline is to avoid any direct assignment/initialisation of a pointer using a `new` expression  (e.g. don't do `some_X = new X`), since it is easy to misuse such pointers (and therefore access unallocated memory).  Instead, use the standard library - specifically, standard containers (`vector`, `list`, `string`, etc) if you need a collection of objects, or `shared_ptr` to hold results of any `new` expression.
Answer:
But, this seems as as extremely dangerous pitfall,

It certainly is, and it's your responsibility to avoid this pitfall. That's why it's always recommended to use existing containers first, because they've been carefully written, reviewed and tested to avoid such bugs.
If you do need to handle raw memory directly, it's generally better to write your own container which you can test to a similar standard, rather than interleaving manual memory management with the rest of your program logic.

and I wanted to know if there is some build-in workaround in C++ that will always prevent user when trying to construct unallocated memory

No, because that necessarily incurs a runtime cost for something that was incorrect when it was written. I don't want my program to run slower because someone else is bad at their job.
However, there are plenty of tools to help you test and diagnose these bugs, for example:

the clang and gcc compilers have address sanitizers which compile these checks into your program (it's an optional compiler facility rather than part of the language)
valgrind is an external program whose default tool (memcheck) runs your real program looking for these bugs. It's slow, but it's used for testing or debugging and not for live programs


Non-existence of surjections from $L^p$ to $L^q$

Question: Let $1 \leq p, q \leq \infty$ and suppose there exists a continuous linear surjection
$$ T : L^p[0,1] \longrightarrow L^q[0,1]. $$
Does it necessarily follow that $q \leq p?$

In the case of sequence spaces $\ell_p$ the result holds if we swap $p,q$ by Pitt's theorem, which asserts that for $q<p$ any bounded linear operator $T:\ell_p \to \ell_q$ is compact. In the $L^p$ context I suspect the notions of type/cotype may relevant, but as a non-specialist it isn't obvious to me how these can be applied. This question is mainly out of curiosity, and any references would be appreciated.
Comment: From open mapping theorem, if $T$ is surjective then $||T^*(x)|| >= c||x||$. In words, $L^p$ would contains isomorphic copy of $L^q$. Then one can use some local properties like type or cotype to show that $q<=p$.
Comment: If you have a continuous linear surjection, it means that $L^q$ is a quotient of $L^p$. Maybe this observation is helpful.
Comment: @Salcio That's very useful to know, though it doesn't cover all cases as Nick's answer shows - instead it implies that if $T$ exists, then $1<p<2$ implies $p \leq q$ and $1<p<\infty$ implies $q \geq p.$
Answer: It is true that for $1<p<\infty$, $L^p[0,1]$ contains a complemented subspace isomorphic to $L^2[0,1]$. The subspace is the closed linear span of the Rademacher functions. This result is due to Khintchine inequality.
For $p = 1, q > p$, it is true that there is no linear surjection from $L^p[0,1]$ onto $L^q[0,1]$. This is because $L^1[0,1]$ cannot contain infinite dimensional reflexive subspaces (a consequence of $L^1[0,1]$ having the Dunford Pettis Property)


Why does my Washburn sound bad even after installing EMGs?

Question: I have a Early 90s Washburn. I installed new EMGS into it. It sounded great and then all of a sudden it has a crunchy clean tone. I changed the battery, plugged a cheap guitar into same cable and amp no problem there. I sent the pickups back to EMG and they reported no problems found. I put in proven passives pickups and they have the same problem.
Comment: Clearly the pickups have nothing to do with the problem. Have you checked out the amp and cables and everything else? What happens if you use a different amp? What about the tone and volume controls on the washburn? If you turn those knobs without playing is there any noise?
Comment: Your question proves the problem is nothing to do with the pickups so you need to look at the rest of the signal chain. Wiring, pots, capacitor, all solder joints, plug.
Comment: "crunchy" probably means "humbucker" and possibly "active," but without info...
Answer: New pickups won't necessarily make your guitar sound better or sound the way you want it to. I actually have made this same mistake in the past, I wanted my guitar to sound better and installed a Dimarzio X2N on the bridge position of my old Washburn WR120 and it's sound got worse (way too much gain and high frequencies). Years later I replaced all the wiring, installed new pots and replaced the bridge pickup with the original low gain pickup. It sounds much better now. I strongly advise you to take your guitar to a trustworthy luthier, state your problem and ask his suggestions on how to proceed to fix your guitar.


Working on an approximation of $\pi$. How do I demonstrate an inequality on the taylor expansion of arctan?

Question: I'm struggling  with the following inequality.  In particular, I don't understand how to demonstrate that this term is larger than the left hand side for all $n \in \mathbb{N}$.  It seems to be another term for the sequence but I don't have the intuition for its growth.
Main Question:
Show that $$\left| \tan^{-1}(x) -\left(x  -  \frac{x^3}{3} + \frac{x^5}{5} - \dots + (-1)^{n-1}\frac{t^{2n-1}}{2n-1 } \right)  \right| \leq \frac{x^{2n+1}}{2n+1}$$

For context,  I am trying to show an approximation of $\pi$. The steps for the proof are as follows:
Show that $$\frac{1}{1+t^2} = 1 - t^2 + t^4 - \dots +(-1)^{n-1}t^{2n-2} + (-1)^n \frac{t^{2n}}{1+t^2}$$
Integrate both sides to show that  $$\tan^{-1} (x) = x - \frac{x^3}{3}+\frac{x^5}{5} - \dots +\frac{(-1)^{n-1}x^{2n-1}}{2n-1} + \int_0^{x} \frac{(-1)^nt^{2n}}{1+t^2}dt$$
Show that $$\left| \tan^{-1}(x) -\left(x  -  \frac{x^3}{3} +\frac{x^5}{5} - \dots + (-1)^{n-1}\frac{t^{2n-1}}{2n-1 } \right)  \right| \leq \frac{x^{2n+1}}{2n+1}$$
Show that  $$\tan^{-1}\frac{1}{2} + \tan^{-1}\frac{1}{3}  \frac{\pi}{4}$$
Finally show that  $$\left|\frac{\pi}{4} - \left(\left(\frac{1}{2} +\frac{1}{3}\right) - \frac{1}{3}\left(\frac{1}{2^2} + \frac{1}{3^2}\right) + \frac{1}{5}\left(\frac{1}{2^5} +
\frac{1}{3^5}\right) - \cdots + \frac{(-1)^{n-1}}{2n-1} \left(\frac{1}{2^{2n-1}} + \frac{1}{3^{2n-1}}\right)\right) \right| \leq \frac{1}{n\cdot2^{2n-1}} $$
Answer: Here are some hints.
I assume you have already shown that
$$\frac{1}{1+t^2} = 1 - t^2 + t^4 - \dots +(-1)^{n-1}t^{2n-2} + (-1)^n \frac{t^{2n}}{1+t^2}.$$
This implies that
$$\left|\frac{1}{1+t^2} -\left( 1 - t^2 + t^4 - \dots +(-1)^{n-1}t^{2n-2} \right)\right| = \frac{t^{2n}}{1+t^2} \le t^{2n}.$$
That is,
$$-t^{2n}\le \frac{1}{1+t^2} -\left( 1 - t^2 + t^4 - \dots +(-1)^{n-1}t^{2n-2} \right)\le t^{2n}.$$
Now try integrating this inequality.
Comment: Welcome! I realised the question also got you to the step $$\tan^{-1} (x) = x - \frac{x^3}{3}+\frac{x^5}{5} - \dots +\frac{(-1)^{n-1}x^{2n-1}}{2n-1} + \int_0^{x} \frac{(-1)^nt^{2n}}{1+t^2}dt.$$ So you can also use this: this equation tells us that $$\tan^{-1} (x) -\left( x - \frac{x^3}{3}+\frac{x^5}{5} - \dots +\frac{(-1)^{n-1}x^{2n-1}}{2n-1} \right) = \int_0^{x} \frac{(-1)^nt^{2n}}{1+t^2}dt.$$ You can now take absolute values and use the triangle inequality for integrals (noting that $\left|\frac{(-1)^n t^{2n}}{1+t^2}\right| \le t^{2n}$).
Comment: Correct, we don't need to integrate the original right-hand side, we can use the triangle inequality and that note to simplify it and achieve the desired bounds as follows: $$\begin{align*}\left| \int_0^x \frac{(-1)^n t^{2n}}{1+t^2}\, dt \right|&\le \int_0^x \left|\frac{(-1)^n t^{2n}}{1+t^2} \right| \, dt \quad (\text{assuming }x \ge 0) \\ &\le \int_0^x t^{2n}\, dt \quad \Bigg{(}\text{since }\left|\frac{(-1)^n t^{2n}}{1+t^2} \right| \le t^{2n} \Bigg{)}\\ &= \frac{x^{2n+1}}{2n+1}. \end{align*}$$
Comment: Thank you! I knew I was missing something "obvious"
Comment: Yes, however I am unfamiliar with integrating the right hand side (rusty with calculus), and figured there was an elementary way to handle it.
Comment: Oh I see, with the note that you wrote, it simplifies the inequality, and makes applying the triangle inequality much simpler


Switching month numbers to month names on x-axis of histogram matplotlib

Question: I have a histogram with data points over one year. Everything works well, except that the month get displayed as a number. I would like to display them with their names. Instead of "01" it should say "January" (also slightly rotated, but I can do that myself.)
How do I tell maplotlib to use the month names?
I already looked in the documentation and other posts, but couldn't make it work.
My code:
fig = plt.figure(figsize=(12,6))
s = fig.add_subplot(111)
s.hist(mydata,bins=120,stacked=True, color=mycolors, alpha=1)
s.xaxis.set_major_locator(mdates.MonthLocator())
s.xaxis.set_major_formatter(mdates.DateFormatter('%m'))
s.legend(legend)

With mydata being a list of dataframes of shape (n,1).
I am new to matplotlib and don't fully understand what is happening in s.xaxis.set_major_formatter(mdates.DateFormatter('%m')) but my guess is this line needs to be modified?
My Code results in the following Graph:

Any help is greatly appreciated :)
Answer: Use %B in the DateFormatter to get month names instead of the month numbers that %m gives. You can also use %b to get abbreviated names.
Comment: Awesome, thanks! How do I look something like this up?
Answer: just need to replace the month format in mdates.DateFormatter:
#fig = plt.figure(figsize=(12,6))
#s = fig.add_subplot(111)
#s.hist(mydata,bins=120,stacked=True, color=mycolors, alpha=1)
#s.xaxis.set_major_locator(mdates.MonthLocator())

s.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
OR
s.xaxis.set_major_formatter(mdates.DateFormatter('%B'))

#s.legend(legend)

B = long name
b = abbreviated name


How do I multiply two big numbers if their digits are stored in two different arrays?

Question: I got a hint that it's possible to multiply them by the standard multiplication method(using 2d arrays). But can anyone please show me how it's done?
Here's my code so far, I couldn't figure out how to handle the carry. I have spent several hours and I just started with coding recently.
<code>    int main()
{
    int n, m, i, j;
    printf("Enter multiplicand(n) size: ");
    scanf("%d", &n);
    printf("Enter multiplier(m) size: ");
    scanf("%d", &m);
    int a[n], b[m];
    printf("Enter multiplicands: ");
    for(i = 0; i<n; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Enter multipliers: ");
    for(i = 0; i<m; i++)
    {
        scanf("%d", &b[i]);
    }

    int c[m][n+m];
    int k = 0 , l = m+n-1 , p = 2;
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<m+n; j++)
        {
            c[i][j] = 0;
        }
    }
    for(i = m-1; i>=0; i--)
    {
        for(j = n-1; j>=0; j--)
        {
            if(a[j]*b[i] < 10)
            {
                c[k][l] = a[j]*b[i] + carry;
                l--;
            }
            else
            {
                carry = a[j]*b[i]%10;
                c[k][l] = carry;
            }
        }
        l = m+n-p;
        p++;
        k++;
    }
    for(i = 0; i<m; i++)
    {
        for(j = 0; j<m+n; j++)
        {
            printf("%d ", c[i][j]);
        }
        printf("\n");
    }
}
</code>
Comment: Imagine how you would do it by hand with a pencil and paper.  Now do that in code.
Comment: I'm voting to close this question because it indicates the OP has not put any effort into solving the problem.
Comment: sorry but I tried and couldn't figure out how to code it.
Comment: in general, your question should focus on a specific problem in YOUR code.  Unfortunately, you have not posted your code.  For this kind of question, suggest posting a [mcve] showing what you have tried and why it is not doing what you want/expect
Answer: Read wikipedia pages on bignums, then read the related conference papers. You can get a PhD in improving multiplication techniques on them. This report and that one (and many others) should interest you.
Then, study the source code of some open source bignum library, such as GMPlib.
Better yet, just use that library (or some other bignum library, see this list) from your C program.


Use #define macro in C++ to choose implementations from different namespaces

Question: The multiplatform engine we're developing for our game uses the EASTL to replace the STL, because of memory, performance and portability reasons. The EASTL can be found here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html
Because Visual Studio is really good for debugging the STL we're not using the EASTL on Windows while the engine is in development. Also some STL containers as std::queue, std::deque, ... aren't available in the EASTL. Because it doesn't matter we're using the eastl::string on Windows as well, because it's fine for debugging.
What we're doing until now is
#if (GIN_USE_EASTL)
    #define ginstl eastl
#else
    #define ginstl std
#endif

and GIN_USE_EASTL is defined as 0 on windows. The engine is called Ginkgo, thats where the GIN comes from.
We're using lists, vectors, ... like this
ginstl::list myList;
ginstl::vector myVector;

which works quite fine. But when we use a string or a queue, because of reasons I explained above, we have to write
eastl::string myString;
std::queue myQueue;

which is the reason why i'm posting here, because this is not optimal! What I want to do is use the ginstl:: macro for everything in the engine, without thinking about what implementation to use. So my approach on the problem was this:
#if (GIN_USE_EASTL)
    #define ginstl::list eastl::list
    #define ginstl::vector eastl::vector
    #define ginstl::string eastl::string
    #define ginstl::queue std::queue
#else
    #define ginstl::list std::list
    #define ginstl::vector std::vector
    #define ginstl::string eastl::string
    #define ginstl::queue std::queue
#endif

But unfortunalty that's not working, because the :: is not allowed in the #define macro.
Is there any way to achieve the same thing (be able to specify which implementation I want to use for a specific datastructure) somehow different? I could go for
#define ginstl_list eastl::list

but I would prefer the structure from above! Is there a way (except writing a custom pre-processor) around the problem?
Comment: +1 for developing a cross-platform game :)
Comment: Do you actually **need** the EASTL (yet)? Why not use the default STL implementation until you know that it's actually insufficient for your needs? Premature optimization and all that :)
Comment: actually no, we don't need it ATM, but for not using it now, the benefit of using ginstl:: would even be bigger, because we can just swap the implementation at the end.
Comment: And I forgot, we actually do use some eastl specific implementations of the string class (.toUpper(), .toLower(), ...)
Answer: What about using namespace:
namespace ginstl
{
#if (GIN_USE_EASTL)
    using eastl::list
    using eastl::vector
    using eastl::string
    using std::queue
#else
    using std::list
    using std::vector
    using eastl::string
    using std::queue
#endif
}

Comment: that sounds promising! will try it tomorrow (beer-o-clock)!
Comment: Thanks for the helping lead! Could also have done it this way, but @Krizz's way is the more comfortable one, because using a different implementation then the default one if rare. And you also see at a glace where the exceptions are!
Answer: Developing further on the Mark B's way (no need to list all types used):
namespace ginstl
{
#if (GIN_USE_EASTL)
    using namespace eastl;
#else
    using namespace std;
#endif
    using eastl::string
    using std::queue
}

Comment: Awesome! Exactly what I needed, couldn't wait to try it, and it works! Just make sure to use it in a C++ environment (won't compile in C context)
Comment: Of course, there is no such a thing as namespace in C. Glad to hear that it helped you.
Answer: If you use namespace aliases instead of macros:
#if (GIN_USE_EASTL)
    namespace ginstl = eastl;
#else
    namespace ginstl = std;
#endif

You can then do this:
using namespace ginstl;
using std::queue;
using std::deque;

list<int> x; // from eastl or std, depending on GIN_USE_EASTL
queue<int> y; // always from std

Comment: I don't want to use the using lines in every file I'm using one of the structures, but thanks for the equals syntax… didn't know that existed


$ b_{n + 1} = \frac {b_n^2 + 2b_n}{b_n^2 + 2b_n+2}$ and $ b_1 = 1$, show that $ \left|\frac{2}{n}-\frac{2\ln{n}}{n^2}-b_n\right|\leq\frac{1}{n^2}$

Question: In the recursion $ b_{n + 1} = \frac {b_n^2 + 2b_n}{b_n^2 + 2b_n+2}$, with $ b_1 = 1,$ how can one prove that  $ \left|\frac{2}{n}-\frac{2\ln{n}}{n^2}-b_n\right|\leq\frac{1}{n^2}$?
Comment: Have you tried? Try induction and use the recursion.
Comment: @Jonas: It was an (evidently failed) attempt to educate Amir, see my comments [here](http://math.stackexchange.com/questions/57057/challenging-inequality-abcde-1-show-that-frac1a-frac1b-frac1c) and [here](http://math.stackexchange.com/questions/57377/true-or-false-the-largest-k-such-that-akabkb-geq-akbbka-holds).
Comment: I edited the tags, because I don't think this has much to do with algebra. But: this has the air of another past contest problem. Do you even try to work on these on your own? Show your work, and then there is much better chance of making progress. Sincerely, I don't think that posting many contest questions here in quick succession is the best way to train your abilities. Honestly: if you are training for a contest, I am trying to be helpful here. If this is not a contest problem from the past, then I apologize.
Comment: Why does this question has 4 close-votes for "too localized"? The technique used to show this can surely be of interest to others.
Comment: The function $f(x)=(x^2+2x)/(x^2+2x+2)$ gives the single iteration here. If instead of $f$ the function $$g(x)=\frac{x^2+2x}{(x^2/2)+2x+2}=\frac{2x}{x+2}$$ were used, then starting with $b_1=1$ we would have $b_n=2/(n+1)$ for all $n$.  The difference $g(x)-f(x)$ increases about cubically in $x$ from $0$ to $1/15$ in the interval $x\in[0,1]$, so the question is about some kind of stability of the recursively generated sequence under small variations in the function being iterated. I don't know if this helps :-(
Comment: @Jonas: I consider this to be a very nice question, and not trivial, since no fast answer was posted. Sure, if the OP would have explained more about the problem and what he tried, he wouldn't have so many close votes.
Comment: @Jonas: Nothing wrong about this particular question really. The negative feelings are probably a result of OP posting several questions in a short span, and apparently not having done any work on any of them. At least nothing s/he wanted to share with us. Probably won't get closed now that many people have thought about the problem. The votes to close are mostly a message to the OP. I am one of those voters.
Comment: I voted to close with similar reasons as Jyrki and Theo, but would happily vote to reopen if Amir edits in his motivation and what he's tried in solving this. I'll note that similar interventions helped a former offender change his habits...
Comment: @Didier: It took quite a bit of prodding+downvotes, TBH. I don't want to name names, but a search of meta might net you the name of the former offender. SFAICT he no longer dumps questions.
Comment: @J. M. *similar interventions helped a former offender change his habits*... **REALLY??** This would be terrific news but I missed the case. Until now, I only saw zillions of examples of the opposite. (Surprise, I voted to close. Not really happy about the "too localized" motive though, but one must choose a reason from a limited list.)
Comment: Sorry to hear it's closed. If it is reopened, I'll continue.
Answer: Note that
$$
b_{n+1}+1=2\frac{(b_n+1)^2}{(b_n+1)^2+1}
$$
Letting $b_n=c_n-1$, we get
$$
c_{n+1}=2\frac{c_n^2}{c_n^2+1}
$$
Letting $c_n=\frac{1}{d_n}$, we get
$$
d_{n+1}=\frac{1}{2}(1+d_n^2)
$$
Note that $d_1=\frac{1}{2}$, and if $0\le d_n\le 1$, then $0\le d_{n+1}\le 1$. Thus, $0\le d_n\le 1$ for all $n$.
Letting $d_n=1-e_n$, we get
$$
e_{n+1}=e_n-\frac{1}{2}e_n^2
$$
Note that $e_n$ is non-increasing and $0\le e_n\le 1$ for all $n$. Therefore, $\lim_{n\to\infty}e_n$ exists. Thus, $\lim_{n\to\infty}\;\frac{1}{2}e_n^2=\lim_{n\to\infty}(e_n-e_{n+1})=\lim_{n\to\infty}\;e_n-\lim_{n\to\infty}\;e_{n+1}=0$. Therefore, $\lim_{n\to\infty}\;e_n=0$.
Letting $e_n=\frac{1}{f_n}$ (whereby $\lim_{n\to\infty}f_n=\infty$), we get
$$
\begin{align}
f_{n+1}-f_n&=\frac{1}{2}\frac{f_{n+1}}{f_n}\\
&=\frac{1}{2}\left(1+\frac{f_{n+1}-f_n}{f_n}\right)
\end{align}
$$
Collecting the $f_{n+1}-f_n$ on the left, we get
$$
(f_{n+1}-f_n)\left(1-\frac{1}{2f_n}\right)=\frac{1}{2}
$$
So that
$$
f_{n+1}-f_n=\frac{1}{2}\left(1+\frac{1}{2f_n}+\frac{1}{4f_n^2}+\frac{1}{8f_n^3}+\dots\right)
$$
We can iteratively apply the Euler-Maclaurin Sum Formula starting with $f_n=\frac{a+n}{2}$. Two passses gives
$$
f_n=\frac{1}{2}((a+n)+\log(a+n)+\frac{\log(a+n)}{a+n})+O\left(\frac{1}{a+n}\right)
$$
Note that $b_n=\frac{1}{f_n-1}$. This yields $b_n=\frac{2}{n}-\frac{2\log(a+n)}{n^2}-\frac{2(a-2)}{n^2}+\dots$.
Had a few minutes, so I added a bit more. Gotta go again; I will finish this later.
Comment: I ran into this thread just now. Just reminding you about the answer, in case you want to finish it. :)
Comment: @Srivatsan: The question was closed, so I didn't revisit the answer. However, the asymptotic expansion given yields the requested inequality. I was simply going to add more terms.


How to show link upload option on statuses updates form which converts to embedded content?

Question: I am using Statuses (Social Microblog) module to allow users to post status updates like other social networks. To enable users to upload photos and videos, there is a module called Facebook-style Micropublisher, which allows users to upload links, photos, videos and documents. The problem with this is that all photos and videos will be saved on my server and for a community site, it is an expensive thing.
To counter that, I installed the great oEmbed module. When the oEmbed input filter is turned on in any of the text formats, It allows users to share a url of the video or photo and it embeds it into the statuses update a user shares. The oEmbed filter is working perfectly, but when a user shares a url of a video or photo with text before or after the url, the content is not embedded and it simply shows a link in the status update.
Now there are few ideas I have in my mind, but I do not know whether those ideas are possible or not. I guess it's a challenge.
Here are the ideas:
IDEA 1. The Facebook style micro publisher (fbsmp) module allows to attach a link with the status update. It is designed to work as I want, it is not working as it should. If you install and see this module, i think you will get the idea of how it works.
I have read some where that the statuses module's api is flexible and customizations can be done. I am using the dev version of the statuses and flag 2.
Important note: It is not necessary that the answer is restricted to my ideas. Anything which solves my problem will do.
Comment: It seems you have reported this as a bug to the oEmbed module twice already (I just closed one of them). If you genuinely think this is a bug, there is nothing we can for you here, nor is this the place to ask for alternative modules. The way the question is currently written makes it look like you want us to try and validate your ideas. Do not get me wrong, but you are the developer. Don't expect from us to start trying your ideas. Please explain what you have tried with the other modules and what did and did not work.
Comment: These modules might be of some help [custom filter](https://www.drupal.org/project/customfilter) and [flexi filter](https://www.drupal.org/project/flexifilter)
Comment: I'm not sure whether it will work for links in content as well, but did you tried [Statuses with Scald integration](https://www.drupal.org/project/statuses_scald) Module as well?
Comment: @Neograph734 I am not here to ask help for removing bug from oembed. If you read my question, I have told the readers that "What I want to do" and "What I have tried". I did not understand what you mean by "you are a developer". FYI, I do not know how to code.
Comment: See also [What types of questions should I avoid asking?](http://drupal.stackexchange.com/help/dont-ask): _your answer is provided along with the question, and you expect more answers: "I use ... for ..., what do you use?"_
Answer: So do you want it to act like Facebook aka pulling in content from the link automadgicly?
If so then I did have some success with a alter / Ajax callback and then file read contents and pulling in an image tag at appropriate size was not the best solution but look in to https://stackoverflow.com/questions/6476212/save-image-from-url-with-curl-php
And file_get_contents()
Comment: If I put it simply. I want a solution which converts url into an embedded content. Currently, oembed filter is working perfectly. The only problem I am having with it is that when I write text with the url, it does not convert. For example: **Will Convert**: https://www.youtube.com/watch?v=T26oz9H-VBY **Will Not convert**: Nice video must watch https://www.youtube.com/watch?v=T26oz9H-VBY
Answer: I went through the module, however I didn't have the time to try out the module. I think there should be a manner to change the way the request is interpreted. Maybe you should try reading parts of the module to see where you can intercept.

Implement hook_oembed_request_alter() to see if you can alter the way the module interprets the request or to see if the module gets a request at all.
Implement your own provider (if need be) and extract / interpret the URL yourself.

I hope it helps. I am interested in the problem. Will see if I can check it out this weekend.
Comment: I would recommend you to try the module and see its docs as well. I am sure it will encourage you. See the above links I  have shared in my comments.


Get node ID in a form submit

Question: I am struggling with how to get node id in my user_register_form_submit.
I need to get the node id of the node where my form is, let me explain :
I have created a tpl for my user register form in order to print it in nodes of a special content type, those nodes prepopulate my form and helps to create users, I need this node id to delete the node after submiting the form wich means delete the node after a user is created.
here is my hook :
    function hook_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'user_register_form'){
            $form['#submit'][] = 'user_register_form_submit';
        }
    }

    function user_register_form_submit($form, &$form_state) {
    // print the node id
    }

Last thing, I'm working with Drupal 7.
Thanks !
Comment: So you want a node id in user registration form, to know what node user was viewing when he registered? May be hard. Especially that there is no guarantee that there will be any node at all, and if so, that there will be only one. I wonder what your reason is, maybe there is an easier solution to achieve your business goal.
Comment: Why you are embeding user register form in node? what is your requirement?
Comment: Thank you for your answer.
I just need to know the node id where the form was submitted to delete this node.

My goal is to create a custom way to create users, I allow anonymous users to submit a form (with my content type) and I take this data and prepopulate it in my user register form, so the thing is for each content of this content type there is my user register form.
Comment: @ARUN I'm trying to create a light back office for a client where he just need to validate his users (Drupal default admin approbation is not a solution for this)
Comment: @MouhyeddineBourabaa, In Drupal 7, you can attach `field api` with `user registration` form, so you can implement same validation with `user registration` whatever you have implemented with `content type`.
Comment: What you could do is on submit of that node add user programatically and then it would be as simple as $form_state['nid'].
Comment: @sly Thanks for your answer, unfortunately no, my user register form is not linked to a node, I output my form with php code and when I paste the $form_state['nid'] I get and undefined index.
Comment: you embedding the form in node? node is coming dynamically?
Comment: function MODULE_form_CONTENT_TYPE_NAME_node_form_alter(&$form, &$form_state, $form_id) {
   $form['actions']['submit']['#submit'][] = 'my_custom_submit';
}

function my_custom_submit(&$form, &$form_state, $form_id) {
   print $form_state['nid'];
}

that will for sure print the nid and there you can add user programmatically. It is a different aproach to what you set out to do.
Comment: @ARUN Yes, I print my form in every node of that content type and with a javascript script I prepopulate my user register form so I just have to sumbit my form to create my user, when it's done I don't need that node anymore, that's why I need the id in the submit form.
Comment: @sly I tried your code and I have this error :  Missing argument 3 for user_register_form_submit() and the Undefined index.
Comment: please provide your user register form embeding code.
Comment: @ARUN I put this code in a block (with php code) and I display this block only for my nodes so here is the code :
Answer: For Drupal 8 Add your custom submit handler in form alter:
$form['actions']['submit']['#submit'][] = '_custom_node_form_submit';

And add custom submit handler:
function _custom_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  echo $form_state->getValue('nid');
}

Comment: For me the new `nid` is also available in `$form['node']->nid` and `$form_state['values']['nid']` at this point. However, interestingly if using `$form['#submit'][]` instead of `$form['actions']['submit']['#submit']`, the newly created node's `nid` will be `null`.
Answer: Add one more line below your user register form embed code,
$form = drupal_get_form('user_register_form');
print drupal_render($form);

echo "";

Then you will get the nid of node inside user register submit function like this:
function user_register_form_submit($form, &$form_state) {
  // print the node id
  echo $form_state['input']['nid'];
}

Also you can do it with hook_form_alter. Add one hidden field and assign nid as value for it.
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#submit'][] = 'user_register_form_submit';
    $form['nid'] = array(
      '#value' => arg(1),
      '#type' => 'hidden',
    );
  }
}

Comment: Don't use JavaScript, use form_alter for it!
Comment: @ram4nd This works for me, how can I do it with form_alter ?
Comment: Add the hidden value to the form with form alter not JavaScript. I can't explain the whole hook system here in comments.
Answer: To expand on Niks answer.
function custom_module_form_validate(&$form, &$form_state) {
  // This will print the node id.
  var_dump(arg(1));
}

I didn't actually know this until I tried it just now. Credit should go to Niks.
Note; From the Drupal docs arg(), "Returns a component of the current Drupal path." In this case the second. That means that this will not work on all forms because not all forms will use the node path.
Edit: Incorporating info from MPD's comment below
Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu_get_object() instead.
Comment: arg() is a bad function, and should be avoided.  Use `menu_get_object()` instead.

Get node ID in a form submit