What fingers should I use to play this section?

Question: I'm learning a song on piano (the "Dungeon Theme" from The Legend of Zelda) and I'm having trouble with one particular section because I'm having trouble moving my fingers fast enough to play the passage, and the placement of the keys means I can't just keep my fingers on the keys, because I can't reach all the notes at the same time.
The way I am currently playing the passage is to have my thumb on the F♭, my index finger on the G, then move my hand slightly so I can play the D with my ring finger and the E♭ with my pinky. However, this is very awkward and I am wondering if there is a better way to play this passage. I am pretty new to playing piano so I don't know much about proper technique when it comes to which fingers play which keys or things like that.
In short: What would be the best way to play this passage? What fingers should I use to play each note in order to play it quickly?
Here is the passage in question. The part I am having trouble with is circled in red.
Comment: You're fingering it correctly. Maybe you are keeping your wrist too rigid. You need to rotate it as you play.
Comment: I've 'fingered it correctly' and still can't reach!  Without seeing the l.h. and hoping the Fb could be played with l.h.thumb, there's no way I can play this.
Comment: @Tim I added a new image that includes the left hand part, if that helps
Answer: Yes, this is a relatively awkward passage to play. If you try things out with the right hand, it seems the only valid options are 1-2-4-5 or 2-1-4-5 (and possibly 2-1-3-5 or 2-1-3-4). You could also use your left hand thumb to play the F♭.
If you can do 1-2-4-5, but just barely, then the awkwardness is probably in going from your index finger to ring finger, since that is quite a stretch. The idea here is then to rotate/move your wrist (this might be easier said than done). Not necessarily in an exaggerated, huge way, but just such that it helps you make the stretch and so that your hand isn't rigid. If you're interested, you might want to watch some videos on wrist movement (and/or ask your teacher, if you have one).
If you choose to do 2-1-4-5, it will require turning over from index to thumb to ring, and also there is quite a leap from pinky to index when repeating the four-note sequence. This will require some dexterity and is also not so easy, especially if the piece is fast-paced.
Using your left hand thumb to play the F♭ might be easiest, but some might disagree with this approach. In particular, it can be hard to make the passage sound smooth/equal because you're using two hands (and also because the thumb is usually a lot easier to play louder than the other fingers). So, I would say that while this approach might be technically convenient, it could make the musicality/musical interpretation harder, but not everyone cares so much about that especially if they "just want to play the piece".
Answer: I think you should use 5,4,2, and 1. (Pinky, ring finger, pointer finger, and thumb.)
Comment: Hi A.Nonny.Mouse - can you provide a bit more info please. As commented, it appears you are using your left hand, which could make the stretch from the G to the D simpler, but as Tim pointed out, without seeing the left hand on the notation, we can't be sure that this is possible. The OP is using their right hand, which seems more logical but is a stretch
Comment: Only if s/he is using his left hand!
Comment: But not necessarily in that order!


Como criar um .JAR para a automação de testes?

Question: Olá, estou criando scripts automatizados utilizando o Selenium WebDriver e estou executando dentro da IDE IntelliJ.
Gostaria de saber como é possível criar um arquivo .JAR dos meus scripts, dessa forma não seria necessário ter que abrir a IDE e executar o script.
Pesquisei bastante e não encontrei nenhuma solução, o mais próximo que cheguei foi que disseram que é necessário ter a classe "main", porém nos meus scripts não tem a classe main.
Meus scripts foram criados no caminho : src/test/java
Abaixo segue o script bem básico, apenas para abrir o navegador, como consigo gerar um .JAR desse script ?
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

public class AbrirNavegador {
    private WebDriver navegador;

    @Test
    public void abrirNavegador() {

    //Abrindo o navegador

    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Cesar\\Documents\\ChromeDriver\\chromedriver.exe");
    WebDriver navegador = new ChromeDriver();
    navegador.manage().window().maximize();
    navegador.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        navegador.get("http://www.google.com");
    }

}

Comment: Você quer executar o jar gerado, ou quer utilizar este jar em outros testes?
Comment: Ou você quer sempre executar este teste, independente do módulo em que ele esteja?
Comment: Quero sempre executar esse teste, é que tenho diversos scripts que nunca vão ser alterados, então sempre vão ser executados da mesma forma.
Answer: Recomendo você utilizar a estratégia de implementar os testes em um módulo comum, e executar uma suite padrão por módulo utilizando @Suite:
// Teste padrão - NOTE que a classe é abstrata
public abstract class AbstractAbrirNavegadorTest {

    private WebDriver navegador;

    @Test
    public void abrirNavegador() {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Cesar\\Documents\\ChromeDriver\\chromedriver.exe");
        WebDriver navegador = new ChromeDriver();
        navegador.manage().window().maximize();
        navegador.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        navegador.get("http://www.google.com");
    }
}

Nos submódulos que você deseja executar sempre o teste, inclua o jar comum como dependência e crie uma classe concreta para o teste:
// Implementação do teste padrão em todos os submódulos necessários
public class AbrirNavegadorTest extends AbstractAbrirNavegadorTest {

}

Ainda no submódulo, crie uma suite de testes executando a(s) classe(s) concreta(s):
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
  AbrirNavegadorTest.class
  // Inclua aqui os testes padrões a serem executados
})
public class TestesPadroes {
    // Executa a suite com todos os testes padrões
}

Comment: Mas esse procedimento irá gerar o arquivo .JAR ?
Comment: Eu imaginei que pudesse ser algo um pouco simples, procurando pela IDE eu vi que tem a opção de "Build", que pelo o que eu pesquisei seria para criar o executável correto ?
Comment: Não, este procedimento cria um teste reutilizável para ser reaproveitado em N módulos. A criação do JAR depende de como você está fazendo seu empacotamento hoje (maven, gradle...)
Comment: Meu empacotamento está sendo em maven.
Comment: Então você deve gerar um `test-jar` deste módulo


Find the sum of the number of all continuous runs of all possible sequences with $2019$ ones and $2019$ zeros

Question: I recently had a test that is quite difficult because it is for selecting people to participate important mathematics competition. It has 6 questions like IMO, and the last question is pretty hard. Although I have done it, it takes me a long time. I hope someone would give me a better solution. The question is that:

For a sequence with some ones and zeros, we count the number of continuous runs of equal digits in it. For example, the sequence $011001010$ has $7$ continuous runs; $0,11,00,1,0,1,0$. Find the sum of the number of all continuous runs of all possible sequences with $2019$ ones and $2019$ zeros

That's the question. I did an answer $$4040 \begin{pmatrix} 4037 \\  2018 \end{pmatrix}$$
I think it is true that I have checked the answer in different ways. However, I hope there are faster or more elegant ways to solve this question because I use a lot of algebraic-combinatorics. I hope you guys will help me. Thank you!
Spoiler(my answer)

 Let $a_n$ be the number of the sequences with $n$ continuous runs. Obviously, $a_n \ne 0$ if and only if $n$ is a positive integer between $2$ and $4038$ inclusive. After some simple calculation, we know that: $$\text{For any positive integer }n\text{ between }2\text{ and }4038\text{ inclusive, }a_n=\begin{cases} 2{\begin{pmatrix} 2018 \\  \frac{n}{2}-1 \end{pmatrix}}^2 & \text{if }n\text{ is even}\\ 2\begin{pmatrix} 2018 \\  \frac{n-1}{2} \end{pmatrix} \begin{pmatrix} 2018 \\  \frac{n-3}{2} \end{pmatrix}& \text{if }n\text{ is odd}\end{cases}$$ However, our answer is to find the sum of all continuous runs of all possible sequence, so the answer is $\sum_{k=2}^{2018} ka_k$. After some horrible calculation, you'll get $4040 \begin{pmatrix} 4037 \\  2018 \end{pmatrix}$.
Comment: It appears that the result is $$(2n+2)\binom{2n-1}{n-1}=(n+1)\binom{2n}{n}$$in general for $n$ ones/zeroes by calculating the first few terms.
Comment: I don't know what your 'simple calculation' would be (though I haven't had coffee yet), but more importantly, I don't think $\sum_{k=2}^{2018}a_k$ is the value you want to compute. I understood the question as asking to add up all the individual runs. So a lot of $1$'s, a lot of $11$'s, a lot of $111$'s, etc, and finally about $2020$ runs of $111\ldots111$ (consisting of $2019$ ones).
Comment: It's unclear what "the sum of all continuous runs" is.
Comment: Ok then. Then there is two questions in this problem
Answer: Let us consider the general case with $n$ ones and $n$ zeroes.
We have to count the total number of runs $a_n$ in all the $\binom{2n}{n}$ sequences.
For $i=1,\dots,2n-1$, the space between the $i$th digit and the $(i+1)$th digit marks the end of a run in $2\binom{2n-2}{n-1}$ cases (note that it does not depend on $i$). The space on the right side of the $2n$-th digit marks the end of the last run for all the $\binom{2n}{n}$ sequences. Since each run has a space on its right side, counting the runs is equivalent to count such spaces, that is
$$a_n=2\binom{2n-2}{n-1}\cdot (2n-1)+\binom{2n}{n}=(n+1)\binom{2n}{n}.$$
For $n=2019$ we find that
$$a_{2019}=2020\binom{2\cdot 2019}{2019}=4040\binom{2\cdot 2019-1}{2018}=4040
\binom{4037}{2018}.$$
Comment: @IsaacYIUMathStudio I think your original interpretation was the correct one.  Otherwise, there would be no point in "counting the continuous runs" as the question says.  I think it should be interpreted as the "sum of the numbers of continuous runs" for all admissible sequences.
Comment: The question seems to ask for *the sum of all runs*, not *the number of runs*.
Comment: I am very confused sorry, but I really don't what are you saying about.
Comment: @IsaacYIUMathStudio I edited my answer. Any question?
Comment: @RobertZ I am sorry that you are saying right, so we need to calculate again.
Comment: @RobertZ The question is completely copied from the test, so you guys are right.
Comment: For a sanity check, note that this formula gives $a_1 = 4, a_2 = 18, a_3 = 80$ which can be checked by brute force.
Comment: i am so sorry that I have edit again. I found that I was correct at first. There should be " the number of " here.
Comment: @IsaacYIUMathStudio Fine. Then I remove the related comments.
Answer: Number of Arrangements with $\boldsymbol{k}$ Runs
Using Stars and Bars, The number of ways to get a sum of $n$ with $k$ positive numbers is $\binom{n-1}{k-1}$.
The number of arrangements with $k$ runs is twice the number of ways (one starting with $0$ and one starting with $1$) to get a sum of $n$ with $\left\lfloor\frac{k+1}2\right\rfloor$ positive numbers times the number of ways to get a sum of $n$ with $\left\lfloor\frac{k}2\right\rfloor$ positive numbers.
My Interpretation of "The Sum of All Continuous Runs"
The question explicitly states that "the sequence $011001010$ has $7$ continuous runs". Here we sum the number of continuous runs for all sequences consisting of $n$ zeros and $n$ ones.
$$
\begin{align}
&\sum_{k=1}^n2(2k)\binom{n-1}{k-1}\binom{n-1}{k-1}+\sum_{k=1}^n2(2k+1)\binom{n-1}{k}\binom{n-1}{k-1}\tag1\\
&=\sum_{k=1}^n\left[4(k-1)\binom{n-1}{k-1}\binom{n-1}{k-1}+4\binom{n-1}{k-1}\binom{n-1}{k-1}\right]\tag{2a}\\
&+\sum_{k=1}^n\left[4k\binom{n-1}{k}\binom{n-1}{k-1}+2\binom{n-1}{k}\binom{n-1}{k-1}\right]\tag{2b}\\
&=\sum_{k=1}^n4(n-1)\left[\binom{n-2}{k-2}\binom{n-1}{n-k}+4\binom{n-1}{k-1}\binom{n-1}{n-k}\right]\tag{3a}\\
&+\sum_{k=1}^n\left[4(n-1)\binom{n-2}{k-1}\binom{n-1}{n-k}+2\binom{n-1}{k}\binom{n-1}{n-k}\right]\tag{3b}\\
&=4(n-1)\binom{2n-3}{n-2}+4\binom{2n-2}{n-1}+4(n-1)\binom{2n-3}{n-1}+2\binom{2n-2}{n}\tag4\\
&=2(n+1)\binom{2n-1}{n}\tag5
\end{align}
$$
Explanation:
$\phantom{\text{a}}\text{(1)}$: separate the even and odd cases
$\text{(2a)}$: $2(2k)=4(k-1)+4$
$\text{(2b)}$: $2(2k+1)=4k+2$
$\text{(3a)}$: $(k-1)\binom{n-1}{k-1}=(n-1)\binom{n-2}{k-2}$
$\text{(3b)}$: $k\binom{n-1}{k}=(n-1)\binom{n-2}{k-1}$
$\phantom{\text{a}}\text{(4)}$: Vandermonde's Identity
$\phantom{\text{a}}\text{(5)}$: put everything over $n!(n-1)!$ and simplify
Plug in $n=2019$ and we get $4040\binom{4037}{2019}$.
Comment: Since the question gives the number $7$ for the "number of continuous runs" in the string "$011001010$", that is the interpretation I used.
Answer: We prove that a $2n$-letter-long sequence with $n$ zeros and ones each has $n+1$ continuous runs in average. More precisely, we prove that the following construction is bijective:
$$
\begin{Bmatrix}\text{sequence starts with $1$}\\\text{with $m$ continuous runs} \end{Bmatrix} \xrightarrow{F} \begin{Bmatrix}\text{sequence starts with $1$}\\\text{with $2n + 2 - m$ continuous runs} \end{Bmatrix}.
$$
To abbreviate, let $S_m := \{\text{sequences with $m$ continuous runs}\}$. Let $\chi \in S_m$.
We define a function $g(\chi) = (\chi_1, \chi_0)$, where
$$
\begin{aligned}
\text{$\chi_1$ is a sequence with $n$ letters}, &\text{ the $i$-th letter is C if the $i$-th $1$ follows with a $0$}\\
&\text{ the $i$-th letter is N if the $i$-th $1$ follows with a $1$ or is at the end;}\\
\text{$\chi_0$ is a sequence with $n$ letters}, &\text{ the $i$-th letter is C if the $i$-th $0$ follows with a $1$}\\
&\text{ the $i$-th letter is N if the $i$-th $0$ follows with a $0$ or is at the end.}
\end{aligned}
$$
For instance, if $\chi = 11001001$, then $(\chi_1, \chi_0)= (\text{NCCN, NCNC})$. Also, we denote $\overline{\chi_1}$ to be the sequence where all N is changed to C and all C is changed to N. So in the example above, $\overline{\chi_1} = \text{CNNC}$.
Show that the function constructed as $F(\chi) = g^{-1}(\overline{\chi_0}, \overline{\chi_1})$ work, where $g^{-1}$ is the "inverse", or "reconstruction" function of $g$.


OpenDKIM not signing mail sent to relay host with Ubuntu 18.04

Question: I recently migrated a server from Ubuntu 14.04 to one running 18.04 but with the same mail setup. I simply copied over Postfix's main.cf and the contents of /etc/mail/opendkim over.
The server is sending mail to a remote mail host over the LAN without problems. However, opendkim refuses to sign the emails as it was before.
My postfix.cf file:
myhostname = host.domain.com
myorigin = $mydomain
relayhost = 10.10.10.105
inet_interfaces = loopback-only
mydestination =
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:8892
non_smtpd_milters = inet:localhost:8892
compatibility_level = 2

/etc/opendkim.conf
Syslog                  yes
UMask                   007
Socket                  inet:8892@localhost
PidFile                 /var/run/opendkim/opendkim.pid
OversignHeaders         From
UserID                  opendkim
Canonicalization        relaxed/simple
KeyTable                /etc/mail/opendkim/KeyTable
SigningTable            /etc/mail/opendkim/SigningTable
ExternalIgnoreList      /etc/mail/opendkim/TrustedHosts
InternalHosts           /etc/mail/opendkim/TrustedHosts

The TrustedHosts file contains both the IP and the host name of the sending machine (and hostname -f is correct). Both machines are on the same domain.
I see no errors in either the sender's logs or that of remote mail host. If I shut down the opendkim daemon on the sender, I see postfix complain that it can't connect to the opendkim socket.
I have tried setting the milter_protocol to 2 (it was originally 6) but that has no effect.
Looking at the headers on the mail received from the affected host, there is no mention of dkim.
Comment: What are the `From:` and maybe `Sender:` headers of an outgoing message? What is the SigningTable?
Comment: @kubanczyk The From: header shows the sending user with the hostname of the sending machine (not the relay, but that's correct I think as it's in the TrustedHosts). There doesn't seem to be a Sender: header. The SigningTable shows domain.com default._domainkey.domain.com. I have not changed anything in /etc/mail/opendkim from when it was working with Ubuntu 14.04
Comment: BTW the sending host and the relay are on the same domain.
Answer: Adding LogWhy yes to to opendkim.conf turns on verbose logging. This reveals that there is no signing key for the sending host (host.domain.com).
SigningTable is set to sign mails from specific domains, but not individual hosts on those domains. This is correct behaviour.
The sending host is giving a FQDN when it sends out mail through the relay (firstname.lastname@example.com). I therefore need to work out how to get the sending host to send out as email@example.com, not email@example.com so that the relay will sign its mail on behalf of the domain. I don't need to run opendkim on the sending host.
With the Postfix configuration on Ubuntu 18.04, I had to add masquerade_domains = domain.com to main.cf, whereas Ubuntu 14.04 did not need this.


How much of a dependent variable is explained by each of a bunch of independent variables?

Question: I determined the hierarchy of a small herd of milking cows. It is obvious that the rank of a given cow does highly depend on her age. Not as substantial as the age, but probably still quite meaningful is her weight. Other variables that might explain her rank to some extent (as number of calves she gave birth to, sacral height etc.) are available as well.
I can determine how much (variance) of the hierarchy is explained by any one of these variables when calculating the R² value of the respective bivariate linear model.
But I can not simply sum the R² values up, since they yield much more than 100 % in total. I guess this is, because the explanatory variables are correlated themselves as well. I can neither sum them all up and scale the results down to 100 % in total, since they don't explain 100 % of the hierarchy (a multiple linear regression model with all of the possibly explaining variables has an (multiple) R² value of almost 0.9, an adjusted R² value of almost 0.86, respectively). Scaling down to 90 % wouldn't work either, if I'm not mistaken, because the multiple linear regression model does not (necessarily) weigh the single explanatory variables equally. Furthermore I don't see the possibly explanatory variables do indeed all explain something.
How would one determine, which explanatory variable does contribute how much on it's own?
Answer: The important thing is that the influence that each predictor has depends on which other predictors are in the model.  So the effect of each predictor depends on the model you're using, and which other variables are in it.  For example, you might have two highly collinear variables that both have a large $R^2$ when used in a bivariate linear model, but, because of the collinearity, that doesn't mean that you need them both in your model, or that your model will be better if both variables are in it.
So start by using methods to address collinearity among your predictors and find a plausible model with several variables.  Once you do have a model, you can assess which predictor variables are more or less important to predicting the response by using added variable plots.  If there's a strong linear relationship in a plot, that variable is important to the model when it already contains the other variables.
What does an Added Variable Plot (Partial Regression Plot) explain in a multiple regression?
Comment: +1, especially for the initial remark, which gets to the heart of the problem.  Welcome to our site, Nick!
Comment: Upvoted for the clarity and excellence of the answer.
Comment: The influence of each predictor also depends on the experimental design. For example, if the design matrix is orthogonal, the effect of each predictor does not depend on the other predictors in the model.
Answer: For the question: "How much of a dependent variable is explained by each of a bunch of independent variables?", the short answer is the so-called adjusted R-squared.
It is a modified version of R-squared that has been adjusted for the number of predictors (degrees of freedom) in the model. The adjusted R-squared increases only if the new variable actually improves the model more than would be expected by chance alone. In fact, it can actually decrease when a predictor fit improvement to the model is less than expected by chance.


Returning two values immediately surrounding a test value in an IEnumerable

Question: I have an IEnumerable<float> containing distinct values found in a three dimensional array.
Given a test value, I want to take two elements from my distinct IEnumerable, the closest value which is greater than or equal to the test value, and the closest value which is less than the test.
In other words, if my test value is 80.5, and my list contains:

1.0
1.65
2.345
99.439

Then I want an IEnumerable<float> or a Tuple<float,float> back which contains 2.345 and 99.439.
Is there a LINQ statement or combination of such which will do that? An approach without LINQ?
Comment: is the input `IEnumerable` sorted?
Comment: Not necessarily, though I know it's not hard to put an `OrderBy(item => item)` onto it. I don't need the positions of the values, just the two values around my test.
Comment: What would the output be if the _exact_ value is in the list?
Comment: It would be the test value, and closest lesser value.
Answer: Without using LINQ and assuming that there are only values > 0 in an input collection. There's no need to sort the collection first.
public Tuple<float, float> GetClosestValues(IEnumerable<float> values, float target)
{
    float lower = 0;
    float upper = Single.MaxValue;
    foreach (var v in values)
    {
        if (v < target && v > lower) lower = v;
        if (v > target && v < upper) upper = v;
    }

    return Tuple.Create(lower, upper);
}

Comment: If all values are greater than zero that upper will never change
Comment: If I'm reading this correctly, then the values in the list don't even have to be run through `Distinct` in order for this to work correctly, right?
Comment: This is by far the fastest based on the timing tests I'm doing today, which is a surprising result to me.
Comment: @RobPerkins - makes sense to me - it's one pass instead of two or more for most other solutions.
Comment: @OndrejJanacek, my thanks to you. This is simpler to read and faster than a parallelized LINQ query.
Comment: @RobPerkins Athough it does not answer your question about existence of a LINQ statement, I'm glad you have not gone crazy about LINQ and used a reasonable (and in my opinion more readable) solution.
Comment: There is irony; I ended up using an algorithm that doesn't require it! But, a question like this belongs on the SO site. Maybe I should post the timings as comments under each correct solution... (after further inspection, this and the `Aggregate` approach were similar in timing. All the others were slower.)
Comment: @RobPerkins You can and you don't have to :) Whoever will seek help from this question will likely also test it or will not be interested at all.
Answer: In a tuple:
var t = Tuple.Create(list.Where(x => x <= value).Max(),
                     list.Where(x => x >= value).Min()
                    );

Although you don't state what the output should be if the value is in the list - in this case it would be a tuple with the same value for both "nodes"
Answer: Tuple.Create(
    values.OrderBy(i => i)
          .SkipWhile(i => i < test)
          .FirstOrDefault(),
    values.OrderByDescending(i => i)
          .SkipWhile(i => i >= test)
          .FirstOrDefault());

Sort (ascending), skip all values less than test, take the first value greater than or equal to test.
Sort (descending), skip all values greater than or equal to test, take the first value less than test.
Answer: double[] data = { .1,5.34,3.0,5.6 };
double test = 4.0;

var result = data.Aggregate(Tuple.Create(double.MinValue, double.MaxValue),
(minMax, x) => Tuple.Create(
    x < test && x > minMax.Item1 ? x : minMax.Item1,
    x >= test && x < minMax.Item2 ? x : minMax.Item2));

Answer: Assuming your list is sorted (and few other assumptions on the requirements (such as what happens if there is a direct hit).
float prev=0;
foreach(float item in YourIEnumerableFloatVar)
{
   if (item > target)
   {
       return new Tuple<float, float> (prev, item);
   }

   prev = item;
}


How do I add fields to a specific node?

Question: I want to create a Basic page that, in addition to its title and body, has a list of other nodes. The list of other nodes has to be entirely administered through the admin. However, I don't want to add the other node field onto all Basic pages, as it only applies to this one specific case. How do I do that?
To clarify, I'm asking about the backend portion of this. How do I get it so that, when I edit a certain node, only specific fields show up in the admin?
Answer: There are two main ways of doing this: You can create a second content type which is the same as the Basic Page content type except with the additional fields that you require, or you can just add those fields to the Basic Page content type and only fill them out on the single node you want them to appear on.
As for how to show a list of nodes on another node, I would highly recommend the Entity Reference module. This allows you to add a field that is just stored as a reference to another node.

Original answer (I am leaving this in because it is another way to accomplish a similar outcome):
Using Views you can create the list of nodes that you would like to display on the page. The new version of views makes it super easy to do that. From there you have a couple options, depending your level of skill with theming and how much control you need to have over where the list of nodes displays:

A Block - Create a block display for your view. Place the block in the same region as the main content block.
node--NODEID.tpl.php - You could add a template suggestion to your theme to override the specific node that you want to add the list to. To do that you would need to:

Create a node--NODEID.tpl.php file, replacing the NODEID with the nid of the node you want your list of nodes to show up on.
Embed your view in the node template using the following code:
<?php print views_embed_view('MY_VIEW', 'MY_DISPLAY', $node->nid); ?>

Where MY_VIEW is the machine name of the view you created and MY_DISPLAY is either "default" or the machine name of a specific display in your view.
Here is an example: http://api.drupal.org/api/views/views.module/function/views_embed_view/7#comment-32858
Comment: Sorry, I should have been a bit clearer on this. My question was more about the admin/CMS portion of this. How should I add fields to just the backend for a specific node?
Comment: No worries. I updated my answer to more specifically answer your question. I left my original answer to, since it is another way to accomplish what you appear to be trying to do without adding fields.
Comment: @gregatetr - if this worked for you, would you mind selecting my answer as correct?
Answer: Create a unique content type, that mirrors the basic page content type, and then just use it the once (with your added fields) ?

How do I add fields to a specific node?


Why does mail always come from @localhost on my ubuntu server from exim4?

Question: I have an up-to-date Ubuntu Server (14.04.01) and want to be able to send out status e-mails.  I've also got 2 other computers running Debian Sid.
I have exim4 installed on all 3.  I've gone through "sudo dpkg-reconfigure exim4-config" on all 3 of them, and all 3 have the same settings.
When I send mail from my Debian boxes, it comes from the correct address (firstname.lastname@example.com for example) but whenever I send mail from my server, it comes from root@localhost or user@localhost.
I've validated /etc/hosts, /etc/hostname, I've re-run through dpkg-reconfigure...nothing seems to change it.  I can post any config outputs as needed.  Any guidance is appreciated.
EDIT: By request, full headers of a sample email:
Delivered-To: email@example.com
Received: by 10.112.164.198 with SMTP id ys6csp308507lbb;
        Tue, 11 Nov 2014 12:51:19 -0800 (PST)
X-Received: by 10.70.27.225 with SMTP id w1mr43034811pdg.40.1415739078530;
        Tue, 11 Nov 2014 12:51:18 -0800 (PST)
Return-Path: <surfrock66@localhost>
Received: from localhost (c-98-255-144-176.hsd1.ca.comcast.net. [126.96.36.199])
        by mx.google.com with ESMTPS id oj8si20849377pbb.207.2014.11.11.12.51.17
        for <email@example.com>
        (version=TLSv1.2 cipher=RC4-SHA bits=128/128);
        Tue, 11 Nov 2014 12:51:18 -0800 (PST)
Received-SPF: none (google.com: surfrock66@localhost does not designate permitted sender hosts)     client-ip=126.96.36.199;
Authentication-Results: mx.google.com;
       spf=neutral (google.com: surfrock66@localhost does not designate permitted sender hosts) smtp.mail=surfrock66@localhost
Received: from surfrock66 by localhost with local (Exim 4.82)
    (envelope-from <surfrock66@localhost>)
    id 1XoIQI-0005bx-WC
    for email@example.com; Tue, 11 Nov 2014 12:52:23 -0800
Subject: SR66 Network Mapping: Scanned 2014.11.11 12:40
To: <email@example.com>
X-Mailer: mail (GNU Mailutils 2.99.98)
Message-Id: <E1XoIQI-0005bx-WC@localhost>
From: surfrock66 <surfrock66@localhost>
    Date: Tue, 11 Nov 2014 12:52:22 -0800

Comment: Can you post the full headers of the email received from root@localhost?
Comment: How exactly is the mail generated? What does your exim config look like?
Answer: Check the value of /etc/mailname.  This is the normally the file that contains the domain name used to qualify addresses.
Comment: Nope, that file has the correct name in it.  Curious though, I'd never seen that file before.
Answer: Figured it out, you need to set up an alias in /etc/email-addresses to identify the "from" address for each of your accounts.


Improving the "preview" of a node

Question: I know how to override the preview of a node being edited, but for some reason in the "trimmed" portion it displays a node's title and in the "full" version only the body. I'd like to be able to display the node's title in the "full" version also.
The theme method I'm overriding is theme_node_preview($variables).
I'm actually removing the "trimmed" portion completely, since it's not relevant to my content types. The method looks something like:
function theme_node_preview($variables) {
  $node = $variables['node'];

  $output = '
';

  $preview_trimmed_version = FALSE;

  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  $output .= $full;
  $output .= "
\n";

  return $output;
}

Comment: Your Display settings for that node type (Default or Full page view) must not have the Title field outputted. The title field is usually outside the normal node render in those modes. Look at your page template, or node template, the title field is probably output separately.
Answer: You could also try Page Preview, which shows a simulated full-page preview of a node:

This module re-implements the Preview area of the node edit form as an
  IFRAME that renders and displays the full page view of your edited
  content as the anonymous user would see it, including elements such as
  blocks that display as a reaction to the page context.
Answer: This is my version of previewing the node, could be useful (ctools version):
    function foo_preview_node($form, $form_state) {
      $node = clone ctools_object_cache_get('foo', 'node'); // get the latest node object from the cache
      $node->in_preview = TRUE;
      _field_invoke_multiple('load', 'node', array(NULL => $node)); // additional stuff from other modules
      field_attach_prepare_view('node', array(NULL => &$node), 'full'); // lets field types and formatters load additional data needed for display
      $build = @node_view($node, 'full');
      $form['preview'] = array(
          '#type' => 'item',
          // '#title' => 'optional title',
          '#markup' => drupal_render($build),
      );
      return $form;
    }

See: http://drupal.org/node/1622952

Improving the "preview" of a node


Coordinate values arent stored in processing

Question: I really have no idea why the x and y values wont go to the drawLines function
float x, x1, x2;
float y, y1, y2;
float rad; //radius
int lines = 30; //number of lines
int colorNumber = 1;

void setup() {
  background(#FFFFFF);
  size (800, 600);
  rad = 8;
}

void draw() {
}

This creates the three dots or vertices of the mathematical envelope
void mouseClicked() {
  float x = mouseX;
  float x1 = mouseX;
  float x2 = mouseX;
  float y = mouseY;
  float y1 = mouseY;
  float y2 = mouseY;
  if (colorNumber == 1) {
    fill(#9393ff);
    ellipse(x, y, rad, rad);
  } else if (colorNumber == 2) {
    fill(#FF9393);
    ellipse(x1, y1, rad, rad);
  } else if (colorNumber == 3) {
    fill(#93ff93);
    ellipse(x2, y2, rad, rad);
  }
}

This is supposed to draw the envelope using the coordinates of the vertices
void drawLines(int numLines) {
  for (int i = 0; i < numLines; i = i + 1) {
    float x = mouseX;
    float x1 = mouseX;
    float x2 = mouseX;
    float y = mouseY;
    float y1 = mouseY;
    float y2 = mouseY;
    float t = (float) i/(numLines-1);
    float startX = x + t * (x1 - x);
    float startY = y + t * (y1 - y);
    float endX = x1 + t * (x2 - x1);
    float endY = y1 + t * (y2 - y1);
    line (startX, startY, endX, endY);
  }
}

void mouseReleased() {
  colorNumber++;
  if (colorNumber == 4) {
    colorNumber = 1;
  }
  println(colorNumber);
}

void keyPressed() {
  if (keyPressed == true) {
    background(#FFFFFF);
  }
}

this last stuff just tells the code if you press a key, it will reset the backround
Comment: It looks like you are shadowing the variables `x` and `y` - which ones do you want to to use - only declare them once? Although I have no idea from your code where the values `mouseX` etc are being set/declared
Comment: Well I have three coordinate pairs therefore 6 coordinate points (x,x1,x2,y,y1,y2) which are equal to the mouseX and mouseY values of each on of the three clicks respectively. you click a spot in the window and it creates a dot which is where mouseX and mouseY values come into play.
Comment: where is `drawLines` called from?  [Please add a minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve)
Comment: I have called it from everywhere and it hasn't worked. As sad at it is I have been working on this for hours and can't figure out what is wrong
Comment: *I have called it from everywhere and it hasn't worked* so basically you have no idea?  Please share the **real** code that you are using - this code does not called `drawLines`  - Just noticed that you are using `processing` - correct?
Comment: https://ghostbin.com/paste/uxyt9 and yes I am using processing
Comment: So now, give us some information as to what it is doing, what methods are being entered into? what is being printed? This is called debugging, which I believe you can do in `processing` - see https://debug.martinleopold.com/ - maybe you should `print` from `drawLines`
Comment: ok so its pretty much what I expected - all of the x and y variables are being changes because they are all mouseX and mousY - Im not sure how to make them still mouseX and mouseY but not to change the others.
Comment: Dylan, step back, relax and figure out what you really want to ask.  Your first statement *I really have no idea why the x and y values wont go to the drawLines function* is meaningless and unsupported by fact.  **State clearly** what you do not understand.  Also *Im not sure how to make them still mouseX and mouseY but not to change the others* is non-understandable
Comment: I have done some debugging of your code, this code `if (mousePressed == true) {
    ellipse(mouseX, mouseY, 8, 8);
    drawLines(30);
  }` is never executed.  Maybe I just do not know how to run your application, but I would change the logic to be `if the mouse is clicked 4 times then just the `dots`
Answer: I understand your intention with using mouseX and mouseY to specify the coordinates of one of the 3 points of the envelope on click. The current issue is that all 3 points are being set to the same coordinate with each click. You need to introduce a variable to keep track of which coordinate to set on-click, such that only one pair is set. Then, only once all 3 coordinates are set, drawLines() can be called.
I propose the following:
Introduce 2 variables, one to keep track of which point is being modified; the other an array of PVectors (just to make it cleaner).
int index = 0;
PVector[] coords = new PVector[3];

Modify mouseClicked() to include the following:
void mouseClicked() {

    ellipse(mouseX, mouseY, 8, 8);
    coords[index] = new PVector(mouseX, mouseY);
    index += 1;
    if (index == 3) {
        drawLines(lines);
    }
    index %= 3;
}

drawLines() becomes:
void drawLines(int numLines) {

    for (int i = 0; i < numLines; i = i + 1) {
        x = coords[0].x;
        x1 = coords[1].x;
        x2 = coords[2].x;
        y = coords[0].y;
        y1 = coords[1].y;
        y2 = coords[2].y;
        float t = (float) i / (numLines - 1);
        float startX = x + t * (x1 - x);
        float startY = y + t * (y1 - y);
        float endX = x1 + t * (x2 - x1);
        float endY = y1 + t * (y2 - y1);
        line(startX, startY, endX, endY);
    }
}

Finally, since your drawing on a black background, and the default stroke colour is black, use strokeColour() to change the colour of the lines so that you can see the envelope once its drawn.


Why does creating Apache wildcard subdomain and IP create an infinite redirect?

Question: I have Apache configure with several IP addresses:
Listen 220.127.116.11:80
Listen 184.108.40.206:443

Listen 22.214.171.124:80
Listen 18.104.22.168:443

Listen 333.333.333.333:80
Listen 333.333.333.333:443

(IPs are fake)
I have several VirtualHosts, one of which is a wildcard subdomain.
<VirtualHost *:80>
        ServerName *.example1.com
        DocumentRoot /var/www/vhosts/example1-wc/docs
</VirtualHost>

<VirtualHost *:80>
        ServerName www.example1.com
        DocumentRoot /var/www/vhosts/example1/docs
</VirtualHost>

<VirtualHost *:80>
        ServerName www.example2.com
        DocumentRoot /var/www/vhosts/example2/docs
</VirtualHost>

This works fine. Requests to www.example1.com are served under the example1 docroot, requests for example.example1.com are served under the example1-wc docroot and www.example2.com for example2 docroot.
I can change www.example2.com to use a specific IP without any problems however if I change the wildcard vhost *.example1.com to a specific IP:
<VirtualHost 184.108.40.206:80>
        ServerName *.example1.com
        DocumentRoot /var/www/vhosts/example1-wc/docs
</VirtualHost>

Then requests to www.example1.com create an infinite redirect loop on itself. This happens regardless of whether I use:
<VirtualHost 126.96.36.199:80>
        ServerName www.example1.com
        DocumentRoot /var/www/vhosts/example1/docs
</VirtualHost>

or
<VirtualHost *:80>
        ServerName www.example1.com
        DocumentRoot /var/www/vhosts/example1/docs
</VirtualHost>

Why is this happening and how can I get each virtualhost on its own IP?
Answer: I'm not sure if this is the root of your problem, but you should probably have the directives
NameVirtualHost 22.214.171.124:80
NameVirtualHost 188.8.131.52:80
NameVirtualHost 333.333.333.333:80

So the full configuration would have these directives in it:
Listen 22.214.171.124:80
NameVirtualHost 126.96.36.199:80
<VirtualHost 18.104.22.168:80>
    ServerName *.example1.com
    DocumentRoot /var/www/vhosts/example1-wc/docs
</VirtualHost>

Listen 126.96.36.199:80
NameVirtualHost 22.214.171.124:80
<VirtualHost 220.127.116.11:80>
    ServerName www.example1.com
    DocumentRoot /var/www/vhosts/example1/docs
</VirtualHost>

Listen 333.333.333.333:80
NameVirtualHost 333.333.333.333:80
<VirtualHost 333.333.333.333:80>
    ServerName www.example2.com
    DocumentRoot /var/www/vhosts/example2/docs
</VirtualHost>

but this should not appear anywhere:
NameVirtualHost *:80

Here's some further reading, if you're interested: http://httpd.apache.org/docs/2.2/vhosts/details.html (good luck making sense of it ;-)
Comment: If you check the /var/log/httpd/error.log or similar apache will warn you about overlapping vhosts. You should follow Davids advice to correct that error
Answer: Just a wild guess, but have you tried putting the definition for the wildcard subdomain after the www.example1.com definition?


Why can't we leave all mics on during a gig?

Question: We have a six person blues band. Our bass player is also our sound person. During a gig, he periodically forgets to turn on mics for soloists or turn on instruments from the board. My husband has asked him why he can't leave all the mics on, as he does when the five of us sing backup to the soloist. He says that "it doesn't work that way; we don't know what the audience hears."
Can anyone explain why all mics can't be left on throughout the gig? We know that we need to turn our mics away from us/our instrument when we're not singing. Isn't that enough?
Comment: One telling part here is 'we don't know what the audience hears'. If it's that vague, how can the guy get anything like a good mix from where he is - presumably somewhere on the stage?
Comment: @Tim The only other way to handle it is to cut severely into the bands take for the night by paying for a sound guy. Smaller audiences don't know a good mix from a hole in the ground and if it's just vocals in the PA you can fake it and save a lot of money.
Comment: Nice job, this has to be one of the most heated discussions on Music.SE yet that you've kicked off here...
Comment: What kind of microphones are you using that you actually have to turn them when not in use?  I'm guessing obviously not *all* SM 57s. Do you do a sound check or is everything done on the fly?
Answer: Well, every mic you toss into the mix also adds more ambience, a bit of feedback from PA and monitors, and will pick up sounds that aren't really supposed to be heard at all, like breathing. Now, this isn't necessarily bad – in particular in the studio, I rather like the compact room sensation caused by many mics picking up bleed from different sources.
However, in a live situation you more typically can't avoid hearing too much of the (less than ideal, acoustically) room, you already have plenty enough background noise from the crowd to fight with, and you're close to getting feedback problems. All of these issues are exacerbated by many open mics on stage.Thus, yes, the fewer open mics on stage the better is a pretty good guideline for live sound.
Nevertheless, I don't agree with Tim and would in fact support your husband's complaint. I used to always turn off unused channels too when mixing bands live, but don't do that anymore now, except for particularly troublesome sources (mostly quiet acoustic instruments).
In most cases, you will need to have all channels on at some point anyway, so you need to somehow make sure the mix sounds good even then. If anything is really close to feedback, then the sound will probably be destroyed by resonances already, so the only fix is to go back to the cause. Make sure the overall sound level is quiet enough, optimise the mic positions, tell the guitarist to turn his bleeding amp down a bit... tell the vocalist to make proper use of the mic, as well...
Such measures tend to have a much stronger effect on the final sound than turning down a few vocal mics, which, if placed cleverly, don't generally pick up that much unwanted sound. Overhead drum mics are more of an inevitable troublemaker in that regard.
As you say, any mic that's turned off is a risk of humilation for both singer and engineer, also a typical cause of overly hectic search for the problem, possibly dabbling with the wrong channel... it's just not worth it. Even if the engineer gets every mute right, that alone will keep them somewhat busy and distract from other things that might be more important to worry about. Better just pull the level of those channels down a couple dB, that usually already lets any interference become a non-issue yet if someone is determined to get through to the audience they'll be able to do it, albeit less than easily until the engineer gets the level right again.
A compromise that's getting ever more popular on these days' digital consoles is to just put noise gates on every channel. That certainly avoids breathing etc. to be heard in pauses, though it doesn't generally work that great for avoiding bleed (nor feedback, as Aaron remarks), because either you need to put the threshold so high that quietly sung or spoken parts get chopped up, or louder passages will have bleed from other instruments (particularly snare and guitars) trigger the gate open. Therefore I prefer to set the gates expansion ratio only to something low like 3:1, which gives a similar compromise to only slightly pulling down unused channels: unwanted noise will vanish in the mix, but important yet not-that-loud contributions will at least be audible at all.
Comment: Another point about noise gates: Don't be tempted to use them to kill feedback.  It seems like it should work, and it almost does...until a stray drum hit or stage stomp or whatever opens it up when there's no one handy to stop the howl.  Been there, done that, never again.
Comment: I've run my own live sound business and this is the answer. Muting vocal mikes is a cardinal error of inexperienced engineers. Dropping the fader about 6 dB is the most you ever want to do until the show is over and no one needs a mic. You never know what's going to happen and the expectation of the audience and the band is that all mikes are live all the time, so they will try to sing in them and you just can't unmute fast enough. It ends up feeling really unprofessional to have dead mikes on stage.
Comment: I would tend to agree with this answer over Tims but I'd also add that much can be done to avoid bleed (or at least nasty-sounding bleed) with well-thought through placement of mics, instruments and monitors.  As a sound engineer I'd recommend experimenting with making bleed "sound good" if you can't eliminate it altogether, it can become your friend!   You should really get a proper FOH sound engineer to do it rather than doing it from the stage though, that would be the best solution.
Comment: @SargeBorsch: well, unprofessional _is_ a bad thing; only, some musical styles make this badness an element of their artistic style. But even by that (rather backwards) logic it can't really be an argument for turning off mics, because feedback or background noises make just as "effective" imperfections.
Comment: @ToddWilcox Unprofessional is not necessarily a bad thing. At least in some genres like punk. I saw a GG Allin live recording and he picked up dead mics several times, and once even sang an entire song into dead mic, but everyone were okay with that
Comment: @leftaroundabout feedback is worse. It can even physically harm people if there's no limiter or some other "safety net" and loudspeakers & final amplifier are powerful enough.
Answer: Never understood why any mic needs to be live when not in use. Every mic I use on a gig will be equipped with an on/off switch, and it's expected to be used. My own vox mic is only ever on when I sing. (I don't want the audience hearing my asides!)
As a former soundman, I would always pull a mic down if it wasn't being used - it saves any possibility of feedback, someone knocking the stand with the resulting clunk, etc.Especially if I knew there was no switch, or the person using it couldn't/wouldn't use its switch. BUT - I needed to be aware that a certain mic was about to be used, so to fade it up.
'That's not how it works' is a pretty lame reasoning - explanations please, we're not idiots.Get used to being in charge of your own mic, which can be left faded up, but turned off till needed. And don't come up with 'my sm58 doesn't have a switch'. Get a switched XLR soldered onto the lead, so it does! Try Neutrik.
Lead question answered - feedback potential, noises from stage floor, messing up sound balance with bleed from sources close to open mics. Close them!
Comment: I dread mics with switch, my first impetus when I find one is always to tape it down in ON position. Yes, _in principle_ switched mics could be the perfect solution, however _in practice_ what will usually happen is that the switches are forgotten (either the singer leaving a mic one after use, forgetting the need to turn it on before use and then loudly complaining to the poor engineer, or indeed _turning a (wrongly) turned-on mic off just before use_!), inadvertently switched while adjusting the mic position, or mic released and dropped from the stand while grabbling for the switch.
Comment: "Never understood why any mic needs to be live when not in use. Every mic I use on a gig will be equipped with an on/off switch, and it's expected to be used. " You sir, have spent almost zero time as a live sound engineer. No on/off switches are ever allowed on a stage that I'm mixing. They break often and the last thing you want is a dead mic at the beginning of the second chorus when the harmony vocals come in, so never mute vocal mics during a show, and even worse is when you can't unmute because some joker turned the mic off! **No on/off switches ever!** -1
Comment: @ToddWilcox - which is why I suggest using leads (cables!) with switched sockets at the mic end. I have several leads that go to gigs, so I can use SM58s, 57s, and any mics with cannon fittings - which is 99% of the quality stuff. I did a two year stint as soundman covering jazz acts from all over the world, so I have a bit of a clue. Quality switches don't break often. Never had jokers at the gigs! Ity would appear we're at opposite ends of the same spectrum - I'm happy at mine, you at yours, others will have to believe one or the other...or something inbetween.
Comment: @jdjazz - Certainly not when using the XLR connections mentioned, and there shouldn't be when using a good quality mic with a switch - which, in a live gig situation, unless we're talking stadia, should be available. I can't believe the number of gigs I've done where the supplied mics weren't switched - with or without a sound guy. Although if he's good, they shouldn't be necessary.
Comment: @leftaroundabout - maybe there should be a short course available for those vocalists less endowed than average. It really is basic and not difficult. Just like every vocalist is expected (by me at least) to understand and know which keys they need, they should be able to control a simple mic. there's a 50:50, o.k., but it ain't difficult... is it?
Comment: This is a much better solution (when it's possible) than turning the microphones away from instruments/vocalists when not in use. The sound guy's worst nightmare is someone on stage turning a microphone towards the crowd/a monitor because it's away from their guitar. Musos don't necessarily think about feedback before it happens, but sound guys definitely do. Maybe the bassist/sound guy in question is trying to head off that behaviour before it happens.
Comment: Also if you start looking for good sounding, reliable live mics, you'll find the best ones aren't even available with on/off switches because there's no market for that. Switches are amateur hour and audiences subconsciously know that because they see them at the elementary school but not at the Radiohead concert.
Comment: Perhaps there is a gap in expectations between jazz and rock. I've never done jazz. Certainly never having jokers at gigs sounds like an alien planet compared with my experience. Jazz cats are probably less likely to kick, stand on, drop, spill beer on, and break things, so it makes sense that we would have different perspectives.
Comment: +1, this seems like a perfect solution. In your experience, is there any risk of a bumping/clicking sound when a mic turns on? I'm not very familiar with the sound tech side.
Comment: @ToddWilcox - it seems to be that way! All the jazz guys seemed to respect gear and a lot were sympathetic to its workings - and extremely fastidious as to the sound - making it very pressured at times. But they seemed happy enough with the way things were run, generally.
Answer: In principle, I agree with him.  If you don't need a channel, mute it.
In practise though, I would disagree here.  It sounds very much like he's heard that principle but hasn't yet got the experience to know when to ignore it.  This sounds like one of those instances.  When you don't have a soundman out front and one of the players has to set up the mix, the main thing is to get the sound right at soundcheck and don't touch it.  You make sure it sounds OK out front, and you make sure the foldback is good enough to hear everything you need, and then you know that you're OK so long as nothing changes.
Every instrument volume knob should be at max during soundcheck, so there's no possibility for one player to turn themselves up during the gig and spoil the balance.  (If they want to turn down and vanish out of the mix, that's their choice, but at least they're not crapping on everyone else.)  Once the amps are balanced for levels, no player should touch the volume or gain controls for the duration of the gig.  Balance of amps should be checked on clean/dirty/hi-gain/FX settings as needed.  Acoustic instruments with pickups are the same situation.
The main caveat here is that if a player changes instruments (or just aren't playing on a song), they have to take ownership of making their instrument silent.  That could be changing the volume control from fully-on to fully-off, or it could be a volume pedal that can go from fully-on to fully-off, or it could be a mute switch somewhere.  Doesn't matter how - if you don't want your bassist/soundman to control muting, then you each individually need to control it.
For vocal mics, do not "move them away from you".  Vocal mics should be positioned as far as possible so that foldback speakers are in the mic's "null" area.  Usually this means having the mic cable pointing directly at the foldback speaker.  This isn't always possible though, and the more it's away from that "null" area, the more your mic is prone to feeding back.  So don't move your vocal mics once they're set up, because you will most likely make things worse.  A mute switch is a reasonable option though, so long as each vocalist can take responsibility for that.
Acoustic instrument mics are the one place where I'd say the soundman does need to get involved, because generally you need a lot of gain on them, and you really don't want to leave those live during the rest of your set.  Most instrument mics (SM57 etc) don't have switches either, although you can get mic mute footswitches.  So for these, I'd go with the soundman controlling them as a necessary evil.  You should consider asking those musicians to invest in pickups for those instruments though.
And really do invest in a 31-band EQ on the monitors, and preferably on front of house too.  Your soundman needs to learn how to use it to ring out the system to kill off the most troublesome bits of feedback at soundcheck.  If the mics don't move and the gains don't change, you can reasonably rely on this staying OK all night.
Comment: A couple of disagreements for you! A sound check can only be accurate if it's done with the audience *in* the auditorium. Which never happens. Volume balance is hand in hand with tone and instrument frequency, so it's never going to be good enough to leave alone afterwards. I say this after thousands of gigs, both as sound guy and performer. The part about every instrument being on max to get a balance was one cause of me leaving a band.On keys, every sound will come out differently - piano, organ, horns, strings, so it's down to the player to balance in the absence of an off-stage sound guy..
Comment: ..If the mics  feed back, one main reason is they're too loud - particularly in foldback. Sound pressure on stage needs to be enough so players van still talk to each other.It's volume out front that maybe needs to be up, but not on stage.And - electric guitars are often used in such a way that their volume control becomes an overdrive control, so checking with full volume isn't the best way. And - will the drummer play his loudest in a sound check?Somehow doubt it!My muting for SM57s in front of my gtr amp when the soundman wasn't doing his job properly involved kicking it gently out the way!
Comment: @Tim Of course the soundcheck isn't totally accurate - it's just the best you can do with what you have, and you develop those listening skills to figure out how it'll sound with the audience in. :)  I agree that stage volume levels are usually the biggest problem, and that unreliable drummers can screw your balance up too!  That's a matter of training your fellow band members.  Re guitar volume controls, yes it can control overdrive too, but that makes it more forward in the mix as well so it still works.  An overdrive FX pedal is more repeatable level-wise though, which is more gig-friendly.
Comment: @Tim Re the keys though - if your patches are all different levels, then surely you'd spend some time at practises or between practises to get them evened out?  I say this as someone who used to play guitar and guitar synth in a covers band, with something like 20 guitar multi-FX patches and 10 guitar synth patches.  We practised in a village hall, so I got levels and tones fine-tuned during practises.  When it came to the gig, all I had to do was hit the footswitch.
Comment: My keyboard of choice doesn't do that, I'm afraid. With patches like you use, it's different, and also the thing is touch sensitive - but with a volume pedal in line, I get round it fine, except when someone says turn up your ludest. Funny, it's the same with vocal mics...
Answer: In your band's case, I'd say you want to balance how much the bass player has to do to run sound vs. how complicated you want your sound to be. Having been in this position - being both a professional engineer & guitarist - I can tell you that it is really not possible to do both without compromising either (or both) jobs. That said, here's my 2 cents worth:

Don't turn your mic away when not in use, you're only asking for trouble doing that. Getting a sound system up to an appropriate level is a balancing act, and moving the mics throws off that balance - rather than focusing on your mouth, it's now focusing on the ceiling, or the stage, or something else. If it stays in position, at least it's focusing on the band.
If you really want to have mics turning on & off (there's an argument to be made either way) then what you want is to set up the sound with ALL mics open (so there are no surprises when they come on) and rely on individual switches, be they foot controls or using mics with built-in switches. Then, it's on the person singing to turn on their mic rather than the bass player. I'd also suggest only switching mics that are rarely used - if one person sings 50% of the time then it's probably better to leave their mic up, but if you have a member who only sings on one or two songs then give them a switch.
I agree with the bass player having a wireless or a really l-o-n-g cable. The only way you're going to know how it sounds in the room is to get out in front.
One tip, for the bass player: try to leave a little room for increased energy at showtime. Most players don't put out 100% during a check, but when the adrenaline gets going they'll push harder - so if you set up during check to be right at the brink of feedback, you'll probably find that the band pushes it over when things get cooking.
Gates, Graphic EQs, etc are useful tools but they really increase the complexity of your setup (see my original statement about balance!).
If you guys play mostly the same venues, it might be good for you to invest in a digital system where you can dial in a particular venue and save it as a preset. Then, you can refine the setting over time, adding gates, EQs, etc. as appropriate but it doesn't end up being a bunch of gear that you have to constantly monitor.
Comment: "when the five of us sing backup" ??? Every sound engineer I've ever met would look at you funny and ask if you really need 6 freaking vocal microphones. And they want the bassist to do it?
Answer: Advantages of turning mics off when not in use:

Less chance of feedback. Turning the mic away to avoid being heard is a huge feedback risk, particularly when the pa is 'hot' (basically, nearly too loud for the room).
Less noise from footfalls on stage, kicking stands etc.
Less chance of hearing the bassist chat to the drummer during solos (yes, really)
Stage invasions by audience members are less disruptive.

Disadvantages

If your sound tech is in the band, they might forget to switch them on, oops!

Basically, if you have a dedicated sound tech (i.e. someone who's taking care of your sound and nothing else), you should always close the channel for mics that aren't being used. Be aware that leaving all the mics up does carry a lot of risks.
Being mixed by a member of the band isn't ideal anyway, but sometimes it's the only pracitcal way.Hhere's a few strategies for getting a better sound in that situation:

If you know an audience member, or bring along friends/family, ask them, particularly in the sound check, if it sounds okay to them, and if they can hear everything.
Get your bassist a radio pack, or a very long lead. They should be able to step off stage and hear the 'front of house' sound, again, more so in sound checks.
Get a digital recorder, ideally record directly from the PA, and play back through the PA, so you can listen to the gig later on a similar system and find out what you do or don't like about the sound.
Comment: If you have a dedicated engineer, make sure they always have an accurate set list and then let them do their job and don't tell them whether to mute or unmute channels. Only judge them on the results they get. I never mute channels because then I have to unmute in time and in rock, you never know what's going to happen.
Comment: Frankly, I don't think any of your points carry much weight. Sure, turning away mics is a no-no... but this isn't really among the stupid things that musicians commonly do, I've only seen it very seldom. Kicking-sounds etc. aren't much of an issue for SM58 or other decent live vocal mics, unless you needed to crank the gain for some reason... in which case the sound would be ruined anyway. If the drummer literally chats with the bassist during a solo then, let's face it, the band only deserves to perish. And in case of a stage invasion, the engineer can still mute mics as needed.
Comment: @leftaroundabout I'm so glad you feel able to be completely frank with me. I'm sure you'd want to leave no stones unturned with your scathing criticism and that your answer is in every conceivable respect better than mine. In other news, please think before you post. Take care now.
Answer: "We don't know what the audience hears" ⇒ "our stage monitoring doesn't work".  Why are you even playing live when your own acoustic impression does not correspond in a meaningful manner with that of the audience?  And to add insult to injury, your "sound man" plays bass on the stage and has no chance to notice missing mics once the sound has been set up?
You need to stock up on your monitoring equipment and/or personnel.  It's nice blaming the bass player, but this is an accident waiting to happen.  Repeatedly.
Comment: Only an engineer at FOH knows what part of the audience is hearing. No monitor system can make the stage sound like FOH.
Comment: Often the sound balance and tone of the foldback is very different from what the audience hears. Imagine a big band - the horns want to hear themselves, while the vocalists want to hear little horns, but mostly themselves. We've already got two different mixes, and hardly started! The audience wouldn't want either, in particular!


Allow 2 different subnets to have access to the internet but not each other

Question: How would I go about getting say 10.0.1.100 and 10.0.0.100 to both have access to the same internet, but not see each other.
My Topology can change to make this happen.
Currently I have a router/gateway which connects to the internet via LAN cable.
This router at the moment is basically stock setup, apart from a static IP (10.0.0.1), which is what my 10.0.0.x subnet uses to connect to the net... but this doesn't work for the other subnet.
Answer: You set up a firewall rules on the device that routes the two subnets to the Internet.  If your router doesn't support creating rules to do this, then replace it.  Linux appliances are cheap and flexible.
Comment: Router is running DD-WRT so should be able to


Pegar apenas um valor do mysqli_fetch_assoc

Question: Estou tentando fazer um código para controle de estoque usando PHP.
Cada vez que o usuário for usar o programa, este deve selecionar um funcionário e partir disso selecionar o resto dos campos conforme necessário.
Esta parte do código funciona perfeitamente:

            <?php echo $row[funcionario] ?>
            <?php echo $row[origem] ?>
            <?php echo $row[destino] ?>
            <?php echo $row[quantidade] ?>
            <?php echo $row[package] ?>
            <?php echo $row[conteudo] ?>
            <?php echo $row[sabor] ?>
            <a onclick="excluiProduto(<?php echo $row[id_saida] ?>)" class="btn btn-sm btn-danger" id="deleta">

<?php

    }
    $func = $row[funcionario];
    echo $func;
?>

        <form method="GET" action="imprimirRel.php">
        <button value="<?php echo $func ?>" type="submit" name="submit" class="btn btn-sm btn-info" style="<?php echo $mostraTabela ?>">Confirmar saída</button>
        </form>

Agora estou tentando pegar esse valor e passar pra outra página afim de imprimir um relatório com o seguinte código:
<?php

    INCLUDE "conexao.php";

  $func = $_GET['submit'];
  echo $func; die;

    $sql = "SELECT * FROM controle_saida WHERE DATE(data_saida)=CURDATE() AND funcionario='".$func."'";
    //DATE(date)=CURDATE()
    $result = mysqli_query($conexao, $sql);

    if (mysqli_num_rows($result)==0){
        $mostraTabela = "display:none";
    }
    else {
        $mostraTabela = "";
    }

    ?>

O problema é que não estou conseguindo pegar esse funcionário pelo valor do submit, uma vez que este está fora do mysqli_fetch_assoc. Se eu colocar dentro, ele puxa todos os valores que vão aparecer dentro do loop while.
Eu imagino que não esteja fazendo da melhor forma, existe alguma outra forma de fazer?
Lembrando que o funcionário não precisa estar dentro do loop, uma vez que a cada utilização todas as linhas terão apenas um funcionário, porém os outros campos se alteram.

MODIFICADO:
O código que estou fazendo é pra controle de saída de produtos. Nele possuo o cadastro abaixo:

Conforme completo o cadastro e clico em adicionar, eu adiciono na lista abaixo:
O problema é: Imaginemos que estamos fazendo o cadastro do 3º funcionário, e utilizando apenas esse código:
$sql = "SELECT * FROM controle_saida WHERE DATE(data_saida)=CURDATE()";

Não será o suficiente para trazer a tabela apenas de um funcionário, e acabará trazendo todos os registros que foram feitos hoje, inclusivo dos outros 2 funcionários.
Com isso o que quero é: Estou preenchendo o cadastro de produtos do Eduardo, quero chamar apenas nome dele na próxima pagina para imprimir um relatório, e não estou conseguindo fazer isso.
Comment: Não entendi.. Tem que aparecer um botão para cada funcionário isso? E depois preencher
Comment: Na verdade, você seleciona um funcionário e partir disso preenche o resto do relatório. É um controle de saída de produto, ou seja, como sairá uma página para impressão,não convém que seja feito com vários funcionários ao mesmo tempo.
Comment: $func = $row[funcionario]; echo $func; ele imprime o valor desejado ?
Comment: Isso funciona, mas como estou tratando de uma tabela, ele vai trazer todos os valores da tabela, uma vez que está dentro do while. Mesmo que fosse apenas um funcionário, Felipe por exemplo, no echo traria "Felipe Felipe Felipe Felipe"
Comment: E qual é o valor que você deseja, desculpa mas ainda não estou entendendo?
Comment: O correto seria explicares o que faz este teu sistema, ou como queres que ele funcione, e só depois poderias expor o problema.
Comment: Eu achei que tivesse explicado o suficiente. Já editei minha pergunta.
Answer: Felipe, deixa eu ver se entendi.

Crie uma coluna em sua tabela controle_saida com nome ex.: id_funcionario
Quando realizar o "Adicionar" passe o valor do id do funcionário da tabela onde está os funcionários que acredito ser outra para esta nova coluna id_funcionario.
Quando fizer a consulta na tabela controle_saida, faça assim:

.
$sql = "SELECT * FROM controle_saida WHERE DATE(data_saida)=CURDATE() AND id_funcionario = '".$func["id"]."'";

Comment: Isso funciona, mas como estou tratando de uma tabela, ele vai trazer todos os valores da tabela, uma vez que está dentro do while. Mesmo que fosse apenas um funcionário, Felipe por exemplo, no echo traria "Felipe Felipe Felipe Felipe"
Comment: Então, consegue nos passar o restante do código que vem antes? Para eu poder ver de onde e como está obtendo o valor `.........`
Comment: Vou modificar a pergunta já que não consegui deixar claro de entender.
Comment: Modifiquei minha resposta...
Comment: Thyago, acho que era isso que estava faltando, criar outra tabela para funcionários. Sou iniciante e ainda tenho problema em fazer um MER correto. Vou tentar e posto aqui a resposta, mas já vou dar como resposta correta, pois acredito que você está certo. Obrigado
Comment: Maravilha, fico feliz com isso... Quando quiser saber um pouco mais sobre isso que deseja fazer, pesquise por "Relacionamento de Tabelas", neste caso estamos fazendo uma "gambiarra" com relacionamento manualmente, veja opções de relacionamento 1:1 - 1:N - N:N Abraços!
Answer: Crie um botão do tipo hidden e coloque o valor nele:
    <form method="GET" action="imprimirRel.php">
          <input type="hidden" value="<?php echo $func; ?>" name="submit"/>
          <button type="submit" class="btn btn-sm btn-info" style="<?php echo $mostraTabela ?>">Confirmar saída</button>
    </form>

Nota: A váriavel $func deve conter o valor que deseja passar
Comment: Hiago, acho que não consegui explicar direito. Não gostaria de ter um botão para cada funcionário, mas sim selecionar um funcionário e partir disso preencher o resto do relatório. Pense que estou tentando criar um controle de saída de produtos, e como haverá uma página impressa para assinatura de cada funcionário confirmando os produtos que estão saindo, não convém que seja feito com mais funcionários ao mesmo tempo. Ficou mais claro?
Comment: Sim, me desculpe vou reanalisar e modificar a resposta
Comment: Modifiquei a pergunta, caso a váriavel $func tenha o valor desejado vai ser passado corretamente o valor para a imprimirRel.php
Comment: Editei minha pergunta. Acha que ficou mais claro?
Comment: Sim ficou, mas o @Thiago já lhe deu a solução.


Função recursiva JS

Question: estou estudando um pouco de função recursiva e me deparei com um exercicio que ta tirando o meu sono, por ser um exercicio básico e nao estou entendendo a saida.
Basicamente o livro pede para criar uma função para testar se um número é PAR ou nao, retornando um valor boleano. Mas a função teria que cumprir os seguintes requisitos.
se o valor passado for 0 return true
se o valor passado for 1 return false
para qualquer outro valor faça n - 2 ate reduzi-lo a 0 ou 1.

a minha função ficou assim:
function epar(x){
    if(x==0){
        return true
    }
    else if(x==1){
        return false
    }
    else{
        epar(x-2)
    }
}
console.log(epar('parametro'))

O que não entendendo é que quando eu coloco algum valor diferente de 1 ou 0, ele retorna um valor undefined. Eu fiz alguns testes por exemplo fazendo imprimir o valor passado cada vez que retornasse a função e realmente o valor vai diminuindo como eu gostaria, mas por algum motivo ele tao ta retornando nem true nem false.
Comment: tens de dar `return` nesse `epar(x-2)`, senão a função não retorna nada nesse ciclo recursivo.
Comment: Vc precisa retornar o valor, dentro do `else` deve ser  `return epar(x-2)`. E como essa função só trabalha com números, não faz sentido chamar passando uma string, então deveria ser algo como `console.log(epar(5))` (passo 5 ou qualquer outro número, pois não faz sentido passar o texto `'parametro'` se ela só trabalha com números)
Comment: entendo, muito obrigado, esse valor ai ta uma string so pra exemplificar que estaria passando um parametro qualquer, eu tava passando numeros, irei testar com o return mt obrigado
Answer: Tens de dar return nesse epar(x-2), senão a função não retorna nada e esse ciclo recursivo não passa o resultado para fora.

function epar(x) {
  if (x == 0) {
    return true
  } else if (x == 1) {
    return false
  } else {
    return epar(x - 2)
  }
}
console.log(epar(24));
console.log(epar(23));
Comment: Muito obrigado, não sabia disso não!!

Função recursiva JS


Remove emoji from a String in Swift

Question: How can emojis also be filtered out of string using the following extension?
extension String {
    func removeCharacters() -> String {
        let removeCharacters: CharacterSet = [" ", ";", ",", ":", ".", "!", "%", "$", "&", "#", "*", "^", "@", "(", ")", "/"]
        let filteredString = self.unicodeScalars.filter { !removeCharacters.contains($0) }
        return String(String.UnicodeScalarView(filteredString))
    }
}

I understand isEmojiPresentation == false property can be used, just not sure how to add it to the function. To clarify all emoji should be removed from strings passed through the extension.
Comment: @LeoDabus It's a pretty clear cut case of BSODD: blind StackOverflow-driven development.
Comment: You should spend some more time reading about how `filter` works
Comment: @Alexander I have already posted what OP needs to make filter return any type that conform to `RangeReplaceableCollection` in this case a String but not sure why he is asking that again https://stackoverflow.com/a/68852194/2303865
Answer: I wrote this Swift 5 extension that removes emoji characters:
extension String {
    func withoutEmoji() -> String {
        filter { $0.isASCII }
    }
}

You can run this unit test to see if it works:
func test_removingEmoji_shouldReturnStringWithoutEmoji() {
        // Given
        let inputText = "Hell☺o World❤"

        // When
        let emojilessText = inputText.withoutEmoji()

        // Then
        let expectedString = "Hello World"
        XCTAssertEqual(emojilessText, expectedString, "\(String(describing: asData(emojilessText))) should be equal to \(String(describing: asData(expectedString)))")
    }

// Helper function that returns the string as Data.
// Reveals any invisible characters that might have remained in the string.
// This can help you to understand why two strings might not be considered equal, even if they look the same.
private func asData(_ text: String) -> NSData? {
    text.data(using: .utf8) as? NSData
}

Limitation: As "hotdougsoup.nl" pointed out in the comment, this also removes international characters.

Alternative solution
By building upon Leo Dabus great answer, I wrote this small extension that excludes emoji characters to the visible eye. However, the unit test revealed that some invisible characters remained. That's why I decided to go with the shorter snippet above (.isASCII).
// This does not remove all characters reliably. Use the solution above.
extension String {
    func withoutEmoji() -> String {
        unicodeScalars
            .filter { (!$0.properties.isEmojiPresentation && !$0.properties.isEmoji) || $0.properties.numericType == .decimal }
            .reduce(into: "") { $0 += String($1) }
    }
}

Comment: please note that `.isASCII` also removes international characters such as: éëüñß
Comment: That is a great remark. Thank you @hotdogsoup.nl. I will add that limitation to the answer.
Answer: You need to access the Unicode.Scalar's property properties. Btw filter on a UnicodeScalarView already returns a UnicodeScalarView:
extension String {
    func removeCharacters() -> String {
        let removeCharacters: CharacterSet = .init(charactersIn: " ;,:.!%$&#*^@()/")
        return .init(
            unicodeScalars.filter {
                !removeCharacters.contains($0) &&
                $0.properties.isEmojiPresentation == false
            }
        )
    }
}

edit/update:
The reason a digit would return true for isEmoji is explained in the docs isEmoji

The final result is true because the ASCII digits have non-default emoji presentations; some platforms render these with an alternate appearance.

You can avoid removing them from your string adding an extra condition to your filter method:
extension RangeReplaceableCollection where Self: StringProtocol {
    var removingEmoji: Self  {
        filter { !($0.unicodeScalars.first?.properties.isEmoji == true && !("0"..."9" ~= $0)) }
    }
}

let noEmoji = "abc123".removingEmoji

noEmoji  // "abc123"

Expanding on that:
extension Character {
    var isEmoji: Bool { unicodeScalars.first?.properties.isEmoji == true && !isDigit }
    var isDigit: Bool { "0"..."9" ~= self }
    var isNotEmoji: Bool { !isEmoji }
}

extension RangeReplaceableCollection where Self: StringProtocol {
    var removingEmoji: Self  { filter(\.isNotEmoji) }
    var emojis: Self  { filter(\.isEmoji) }
}

Playground testing:
let notEmoji = "abc✈123".removingEmoji
notEmoji  // "abc123"
let emojis = "abc✈123".emojis
emojis  // "✈"

Comment: Leo, why are airplane emoji still allowed?
Comment: show which emoji you are trying to remove
Comment: ✈ still seems to appear even with your code - I think there may be more like it
Comment: Just use `isEmoji` property instead of `isEmojiPresentation`
Comment: Actually isEmoji is also removing numbers from appearing
Comment: Leo, I understand - but this property is causing a lot of confusion, it removes some but not all emojis and your suggestion ended up removing all emojis + numbers. If I mark your answer as correct do mind helping solve how to remove all emojis but keep numbers?
Comment: Just add another condition checking if the character is a digit
Comment: Yes its pretty strange
Comment: How can I make sure that digits are allowed and emojis are not? I am currently trying, just not sure with scalar property to use - `$0.properties.isEmoji == false &&
                    ($0.properties.numericValue != nil) == true`
Answer: In addition to the previous responses, it's important not to overlook the ZWJ (Zero Width Joiner) sequence in emojis. Failing to properly remove this can lead to the accumulation of ZWJ codes, so "\u{200D}" should also be removed correctly.
Exactly, it's like this.
func withoutEmoji() -> String {
    unicodeScalars
        .filter { (!$0.properties.isEmojiPresentation && !$0.properties.isEmoji && $0 != "\u{200D}") || $0.properties.numericType == .decimal }
        .reduce(into: "") { $0 += String($1) }
}

Remove emoji from a String in Swift


Calculadora utilizando Socket em Java

Question: Estou fazendo um trabalho da faculdade e peguei algumas informações da Internet, o professor pediu um cliente que envie 2 valores e uma operação básica, o servidor deve pegar isso e retornar o total. Acontece que o cliente só pega as variáveis dele mesmo, não pega o total que vem do servidor e nem o opr que é o simbolo da operação.
public class Servidor2 {

    public static void main(String[] args) throws IOException {

        int num1, num2, total = 0;
        int operacao = 0;
        char opr = 0;

        //Cria um socket na porta 12342
        ServerSocket servidor = new ServerSocket(12342);
        System.out.println("Porta 12342 aberta!");

        // Aguarda alguém se conectar. A execução do servidor
        // fica bloqueada na chamada do método accept da classe
        // ServerSocket. Quando alguém se conectar ao servidor, o
        // método desbloqueia e retorna com um objeto da classe
        // Socket, que é uma porta da comunicação.

        System.out.print("Aguardando conexão do cliente...");
        Socket cliente = servidor.accept();

        System.out.println("Nova conexao com o cliente " + cliente.getInetAddress().getHostAddress());

        ObjectOutputStream resultado = new ObjectOutputStream(cliente.getOutputStream());
        ObjectInputStream dados = new ObjectInputStream(cliente.getInputStream());

        num1 = dados.readInt();
        num2 = dados.readInt();

        operacao = dados.readInt();
        if (operacao == 1) {

            opr = '+';
            total = (num1 + num2);

        }
        if (operacao == 2) {

            opr = '-';
            total = (num1 - num2);
        }
        if (operacao == 3) {

            opr = 'x';
            total = (num1 * num2);
        }
        if (operacao == 4) {

            opr = '/';
            total = (num1 / num2);
        } else {

            System.out.printf("Você digitou uma operação inválida.");

        }

        resultado.writeInt(total);
        resultado.writeChar(opr);
        resultado.flush();
        resultado.flush();
        servidor.close();
    }
}

public class Cliente2 {

    public static void main(String[] args) throws UnknownHostException, IOException {
        int num1 = 0;
        int num2 = 0;
        int operacao = 0;
        char opr;
        Socket cliente = new Socket("127.0.0.1", 12342);
        System.out.println("O cliente conectou ao servidor");

        ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());
        ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());

        num1 = Integer.parseInt(JOptionPane.showInputDialog("Digite o primeiro número"));
        num2 = Integer.parseInt(JOptionPane.showInputDialog("Digite o segundo número"));
        operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
        dados.writeInt(operacao);
        dados.writeDouble(num1);
        dados.writeDouble(num2);

        dados.flush();

        int total = resultado.readInt();
        opr = resultado.readChar();
        System.out.println("Total de " + num1 + opr + num2 + " = " + total);

        cliente.close();
    }
}

Comment: Veja o [tour], se acha que o objetivo principal desta pergunta foi alcançado você pode aceitar a resposta. Também poderá votar em tudo no site que achar útil, não só nas coisas ligadas aos seus posts.
Answer: O problema no seu código está na hora de enviar e receber os dados, no cliente você está usando:
dados.writeInt(operacao);
dados.writeDouble(num1);
dados.writeDouble(num2);

E no servidor:
num1 = dados.readInt();
num2 = dados.readInt();
operacao = dados.readInt();

Dois problemas são notados aqui, o primeiro seria o fato de você estar enviando um  Double e querer receber um Integer, e o outro seria a ordem que os dados são enviados e recebidos, pois no cliente você envia operacao, num1 e num2, e no servidor você está recebendo num1, num2 e operacao, o fato das variáveis terem o mesmo nome não significa nada nesse caso.
Para resolver seu problema, ajuste as duas classes com Integer ou com Double e coloque a mesma ordem de envio e recebimento, vou postar como ficaria utilizando Double.
public class Servidor2 {

    public static void main(String[] args) throws IOException {

        double num1, num2, total = 0.0;
        int operacao;
        char opr = '\n';

        //Cria um socket na porta 12342
        ServerSocket servidor = new ServerSocket(12342);
        System.out.println("Porta 12342 aberta!");

        // Aguarda alguém se conectar. A execução do servidor
        // fica bloqueada na chamada do método accept da classe
        // ServerSocket. Quando alguém se conectar ao servidor, o
        // método desbloqueia e retorna com um objeto da classe
        // Socket, que é uma porta da comunicação.

        System.out.print("Aguardando conexão do cliente...");
        Socket cliente = servidor.accept();

        System.out.println("Nova conexao com o cliente " + cliente.getInetAddress().getHostAddress());

        ObjectOutputStream resultado = new ObjectOutputStream(cliente.getOutputStream());
        ObjectInputStream dados = new ObjectInputStream(cliente.getInputStream());

        operacao = dados.readInt();
        num1 = dados.readDouble();
        num2 = dados.readDouble();

        if (operacao == 1) {

            opr = '+';
            total = (num1 + num2);

        } else if (operacao == 2) {

            opr = '-';
            total = (num1 - num2);

        } else if (operacao == 3) {

            opr = 'x';
            total = (num1 * num2);

        } else {

            opr = '/';
            total = (num1 / num2);

        }

        resultado.writeDouble(total);
        resultado.writeChar(opr);
        resultado.flush();

        resultado.close();
        dados.close();
        servidor.close();
    }
}

Nota: nesse caso você pode utilizar if e else if ao invés de somente if, isso evita verificações desnecessárias dependendo do valor de opr.
Nota 2: a validação da operação fica mais fácil de ser feita direto no cliente.
Nota 3: não é necessário utilizar resultado.flush(); duas vezes.

public class Cliente2 {

    public static void main(String[] args) throws UnknownHostException, IOException {
        double num1;
        double num2;
        int operacao = 0;
        char opr;
        Socket cliente = new Socket("127.0.0.1", 12342);
        System.out.println("O cliente conectou ao servidor");

        ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());
        ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());

        num1 = Double.parseDouble(JOptionPane.showInputDialog("Digite o primeiro número"));
        num2 = Double.parseDouble(JOptionPane.showInputDialog("Digite o segundo número"));
        while (!((operacao >= 1) && (operacao <= 4))) {
            operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
            if (!((operacao >= 1) && (operacao <= 4))) {
                System.out.println("Você digitou uma operação inválida.");
            }
        }
        dados.writeInt(operacao);
        dados.writeDouble(num1);
        dados.writeDouble(num2);
        dados.flush();

        double total = resultado.readDouble();
        opr = resultado.readChar();
        System.out.println("Total de " + num1 + opr + num2 + " = " + total);

        resultado.close();
        dados.close();
        cliente.close();
    }
}

Nota: a validação feita consiste em um loop que verifica se a operação digitada está em 1 e 4, caso não esteja, imprime no console e solicita novamente a operação para o usuário.
Comment: Mateus, fiz as alterações que você disse, mas continua sem funcionar as operações, ele retorna os números digitados, porém não faz a operação e nem retorna o simbolo da operação, acredito que não esteja pegando os dados retornados pelo servidor, não sei debugar isso, to apanhando desde muito cedo hoje pra fazer isso.
Comment: você recebe algum erro? Eu testei com a seguinte entrada `40`, `2` e `4`, o resultado foi `O cliente conectou ao servidor    Total de 40.0/2.0 = 20.0`, qual IDE está usando?
Comment: Mateus, estou utilizando o Eclipse Luna, não recebo nenhum erro, ele me retorna isso no console  'O cliente conectou ao servidor
Total de 40.0
20.0 = 0.0'
Comment: dê  uma olhada na classe `Servidor2`, você corrigiu a ordem para `operacao = dados.readInt(); num1 = dados.readInt(); num2 = dados.readInt();`?
Comment: Mateus, realmente, era isso o que estava errado, agradeço muito a ajuda. Agora tenho outra questão a quebrar a cabeça.Sobre threads, 2 usuários se conectando.
Comment: @brenoguto, você realmente precisa trabalhar com threads? Fazer um `while` na classe `Servidor2` para ficar recebendo os clientes não te atenderia?
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/19242/discussion-between-brenoguto-and-mateus-alexandre).

Calculadora utilizando Socket em Java


Serial Port Returning Invalid Data

Question: I have a weighing machine that is connected to a computer using a serial port. It is a very old machine and we are trying to get the weights off it and save in a database.
The weight returned by the machine has some invalid characters like ?, and the weight is displayed as ??2?0, where it should have been 02220.
I understand it has something to do with encoding as results on a web search suggest. But I can not figure out what exactly am I missing.
Here is my code:
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // This method will be called when there is data waiting in the port buffer
    // Read all the data waiting in the buffer
    // string data = comport.ReadExisting();
    // Display the text to the user in the Rich Text Box
    Log(LogMsgType1.Incoming, s);
}

public void OpenThisPort()
{
    bool error = false;

    // If the port is open, close it
    if (comport.IsOpen)
    {
        comport.Close();
    }
    else
    {
        comport.BaudRate = int.Parse("1200");
        comport.DataBits = int.Parse("8");
        comport.StopBits = StopBits.One;
        comport.Parity = Parity.None;
        comport.PortName = "COM1";
        delStart = 0;
        delLength = 9;
        comport.RtsEnable = true;
        comport.DtrEnable = true;
        comport.Encoding = System.Text.Encoding.GetEncoding(28591);
    }

How do I determine exactly which encoding will be applied?
Any idea what I'm missing here?
Comment: Have you tried simple ASCII encoding?  Read the data as `byte[]` and examine that. Post it here if you can't solve it.
Comment: did you mean       byte[] Bdata = new byte[comport.BytesToRead];

                comport.Read(Bdata, 0, Bdata.Length);

                string s = comport.Encoding.GetString(Bdata);
Comment: NO LUCK with reading it by byte[]
Comment: I recommend using a serial port monitor or at least display each received byte in some debug output (you can use myByte.ToString("x2") to print the actual hex value). Then you can compare the data against some codepages and decide what encoding is required.
Comment: I used several serial port monitors... all are returning garbage.. this shows that the problem is not with my software. However, when i connect the same cable to a DOS based computer (which was previously used to get weight off this weighing machine), the data is showing just fine...
Answer: It may not by the encoding issue but error on hardware.
Try detecting it:
    #region comPort_ErrorReceived
    ///
    /// This method will be called when there's data waiting in the buffer
    ///  and error occured.
    /// DisplayData is a custom method used for logging
    ///
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void comPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
    {
        SerialError sr = e.EventType;
        switch (sr)
        {
            case SerialError.Frame:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the hardware detected a framing error.\n", 45);
                break;
            case SerialError.Overrun:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " a character-buffer overrun has occurred. The next character is lost.\n", 46);
                break;
            case SerialError.RXOver:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " an input buffer overflow has occured. There is either no room in the input buffer,"
                    + " or a character was received after the End-Of-File (EOF) character.\n", 47);
                break;
            case SerialError.RXParity:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the hardware detected a parity error.\n", 48);
                break;
            case SerialError.TXFull:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the application tried to transmit a character, but the output buffer was full.\n", 49);
                break;
            default:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " an unknown error occurred.\n", 50);
                break;
        }
    }

At first glance it looks like framing error, as part of the data seem to be correct. For starters make sure that your cable is good. Also you may try connecting to your device with some other application, e.g putty.
Also reading your data as bytes may be a good idea (and then you may convert it to hex before displaying). This way you will find out what is actually getting sent.
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int btr = comPort.BytesToRead;
byte[] comBuffer = new byte[btr];
comPort.Read(comBuffer, 0, btr);
Console.WriteLine(ByteToHex(comBuffer));
}

private string ByteToHex(byte[] comByte)
        {
            StringBuilder builder = new StringBuilder(comByte.Length * 3);
            foreach (byte data in comByte)
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
            return builder.ToString().ToUpper();
        }

Comment: I used several serial port monitors... all are returning garbage.. this shows that the problem is not with my software. However, when i connect the same cable to a DOS based computer (which was previously used to get weight off this weighing machine), the data is showing just fine
Comment: are you sure that your serial port settings are correct? Try setting RtsEnable and DtrEnable to false. You can also leave alone the encoding and get data in binary form (here is usefull translator http://home.paulschou.net/tools/xlate/). Are you using RS-232 or something else? Post your data in hex and what it's supposed to be. Are there no ErrorReceived events fired?
Comment: I am working on your solution, will revert back once i have implemented displayData method. Also i shall post the HEX data
Comment: You can use log.WriteEntry method, or simply write it to console output, it will be fastest.
Comment: dear @Arie, I am stilll having difficulties getting the data from the serial port. It is working properly on DOS Based software however, not working with .NET... what shall i do?
Comment: ok It turned out that the serial port settings were incorrect... I double checked it as you suggested , thanks
Answer: I faced the same problem.
Try changing DataBits to 7 and Parity to Parity.Even, then it should work.

Serial Port Returning Invalid Data


Inequation solving. $\frac{(x+2)²}{x+1}<4$

Question: I am trying to solve this inequality, but I always get the wrong score. This is how I did it.
$$
\frac{(x+2)^2}{x+1}<4\\
(x+2)^2< 4(x+1)\\
(x+2)^2 < 4x+4\\
x^2+4x+4 < 4x+4\\
x^2+4x+4-4x-4 < 0\\
x^2<0\\
x<0
$$
I know that I should get $x<-1$ but I always get $0$. What is my mistake???
Thanks
Comment: The first multiplication can be wrong. if x+1 is negative you must invert the inequality
Comment: $x^2 < 0 \not\Rightarrow x < 0$. In fact, on $\mathbb{R}$, it implies that $x$ cannot exist.
Answer: It goes like this
$$
\frac{(x+2)²}{x+1}<4\\
(x+2)² < 4(x+1),\space x+1>0 \space or \space (x+2)² > 4(x+1),\space x+1<0\\
(x+2)² < 4x+4, \space x>-1 \space or \space (x+2)² > 4x+4, \space x<-1\\
x²+4x+4 < 4x+4, \space x>-1 \space or \space x²+4x+4 > 4x+4, \space x<-1\\
x²+4x+4-4x-4 < 0, \space x>-1 \space or \space x²+4x+4-4x-4 > 0, \space x<-1\\
x²<0, x>-1 \space (impossible)\space or \space x^2>0, x<-1\\
x<-1
$$
EDIT:
There is another method:
$$
\frac{(x+2)²}{x+1}<4\\
\frac{(x+2)²}{x+1}-4 < 0\\
\frac{(x+2)²-4x-4}{x+1} < 0\\
\frac{x^2+4x+4-4x-4}{x+1} < 0\\
\frac{x^2}{x+1}<0
$$
Since $x^2>0$ for any rational $x$, the sign depends only in $x+1$.
 When x+1 negtive ($x<-1$), the expression is negative, and when it is positive ($x>-1$) the expression is potitive.
Answer: simply write the expression as -
$ {(x+1)^2 - 4(x+1)}$ / $ x+1 $ < 0
=> $x^2/x+1 $ < 0
here $ x^2 $ is always positive .
=> $ x+1 < 0 $   => $x < -1 $.
Answer: $\dfrac{(x+2)^2}{x+1}<4
\implies\dfrac{(x+2)^2}{x+1}-4<0
\implies\dfrac{(x+2)^2-4(x+1)}{x+1}<0
\implies\dfrac{x^2}{x+1}<0$
$x^2$ can't be less than zero so the only solution is $x+1<0 \implies x<-1$.


How to specify time format for php-fpm pool access.format

Question: When configuring a PHP5-FPM pool, one can specify the format for all access log entries by setting the value for access.format.
The default provided .conf file stated:

;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)

However, I searched high and low and cannot find any documentation as to how I can modify the strftime format for the %t/%T variables.
Can you provide me with an example on how I can change the format of the %t/%T variable to my liking?
Answer: Here is an example where we log the time only:
access.format = "%R - %u %{%H:%M:%S}t \"%m %r\" %s"