remove the mean over multiple measurements

Question: I have a set of multiple measurements for each subject (i.e. each subject is assessed several days).
For each set of measurements (several days of the same subject) I am calculating the mean value of the measurements and I am substracting it to the original measurement values.
I am doing it for each subject.
Which operation (I am interested in the 2 words name) am I performing? (normalization, centering...)
Can I write something like this in my report: "Temperature and galvanic skin response data were first cleaned from missing values and outliers and then, for each subject, were centered across the mean over multiple days."
Answer: What you're doing is called centering.
Comment: @gung there's really nothing to add. Simple question, simple answer. If it's flagged, it's flagged.
Comment: Thanks! Is it correct (undestandable) then my statement?
Comment: This is being automatically flagged as low quality, probably because it is so short.
At present it is more of a comment than an answer by our standards. Can you expand
on it, perhaps by discussing its implications for the correctness of the OP's statement? You can also turn it into a comment.
Comment: You could explain the implications of your point for whether the OP can write their given statement in their report, eg.
Comment: @gung The problem lies in the question.  Questions that ask for the names of things tend not to fit our format well: as linksys says, they really need only a one or two word answer.


Generalization of integrating factor?

Question: For example, if we have $y'+p(x)y=q(x)$, we can obtain $\mu(x)=e^{\int p(x)dx}$ as integrating factor. My question is: exist a generalization of this? ie, if I have $y^{(n)}+p_{n-1}(x)y^{(n-1)}+...+p_0(x)y=q(x)$, exist a "integrating factor" for this?
Comment: Did you try to evaluate and use it for $n=2$?
Comment: Use what? For n=2 I have two p(x)
Comment: I try to find \mu(x) such that \mu(x)(y^{(n)}...)=(\mu(x)q(x))^{(n)} but didn't work :(
Comment: Most textbooks on ordinary differential equations have several generalizations.
Answer: Integrating factor for higher order equations like $y^{(n)}+p_{n-1}(x)y^{(n-1)}+...+p_0(x)y=q(x)$ does exist, for example one integrating factor of $y''+V(y)=0$ is $y'$, because $y'y''+V(y)y'=0$ can be integrated to get
$$ \frac{1}{2}y'^2 + \int V(y) = C,$$
from which you can write $y'$ in terms of $y$ and integrate again.
In general the integrating factor is a function $\mu\big(x,y,y',\cdots,y^{(n-1)}\big)$ such that there exists another function $\Psi(x,y,y',\cdots,y^{(n-1)})$, such that
$$ \frac{d}{dx}\Psi(x,y,\cdots,y^{(n-1)}) = \mu\big(x,y,\cdots,y^{(n-1)}\big)\big(y^{(n)}+p_{n-1}(x)y^{(n-1)}+...+p_0(x)y-q(x)\big),$$
where $\frac{d}{dx}$ is the total derivative (like $\frac{d}{dx}(x+y+y'^2)=1+y'+2y'y''$) instead of the partial derivative. For higher order equations, you can find integrating factors systematically by using the so called symmetry methods originated by Norwegian mathematician Sophus Lie. Details can be found in books like Symmetry and integration methods for differential equations by Bluman and Anco or Symmetry Methods for Differential Equations by Hydon (the function $\Psi$ is usually called a first integral).

Generalization of integrating factor?


Check for value (list) existence in immutable map builder

Question: I have a map defined like this:
Map<String, List<SomeClass>> map = new HashMap<>();

I figured it would be nice to make it immutable, by using ImmutableMap.Builder construct.
But in my case, when putting new elements in map, I need to first check for their existence, if list for given key doesn't exist, create it and add element to it:
for(final SomeClass elem : elements){
    final String key = elem.getKey();
    if(!map.containsKey(target)){
        map.put(key, new LinkedList<SomeClass>());
    }
    map.get(key).add(elem);
}

If there target key in map, I need to create new list assigned to it, and then add element to that list.
Is there any way to make that map immutable without using unnecessary code like more loops to first initialize lists for target keys?
Btw. I'm using Java 7
Answer: You should use ListMultimap here. Using ImmutableListMultimap.builder():
ImmutableListMultimap.Builder<String, SomeClass> builder = ImmutableListMultimap.builder();
for (final SomeClass elem : elements) {
    final String key = elem.getKey();
    builder.put(key, elem);
}
ImmutableListMultimap<String, SomeClass> multimap = builder.build();

But wait! There's built-in method for your use case - Multimaps#index(Iterable, Function):
ImmutableListMultimap<String, SomeClass> multimap = Multimaps.index(
    elements,
    new Function<SomeClass, String>() {
        @Override public String apply(final SomeClass element) {
            return element.getKey();
        }
    });

(In Java 8):
ImmutableListMultimap<String, SomeClass> multimap =
    Multimaps.index(elements, SomeClass::getKey);


Disable auditing of specific ldap attributes

Question: I'm working on some auditing for PCI-DSS, notably "Audit Directory Service Access". This creates a huge volume of logs, mostly based on a couple specific recurring properties being accessed in the same fashion.
I've been able to identify these attributes via TechNet. None of the ones I'm having issues with are visible in the auditing UI in AD Users and Computers.
I'm thinking I can edit the schema settings in adsiedit and disable the inheritance? It seems counterintuitive but it should work.
Answer: What you want is to modify the searchFlags attribute of the schema attribute that needs to have auditing suppressed.
AD DS Auditing Step-by-Step Guide
https://technet.microsoft.com/en-us/library/cc731607(v=ws.10).aspx
"Schema
"To avoid the possibility of an excessive number of events being generated, there is an additional control in the schema that you can use to create exceptions to what is audited.
"For example, if you want to see what values have changed as a result of all but a few attribute modifications on a user object, you can set a flag in the schema for the attributes that you do not want audited. The searchFlags property of each attribute defines behavior such as whether the attribute is indexed or replicated to the global catalog. The searchFlags property has seven currently-defined bits.
"If bit 8 (zero-based indexing, value 256) is set for an attribute, AD DS will not log change events when modifications are made to the attribute. This applies to all objects that contain that attribute."
Comment: Thanks Greg. Really good to know.. I looked over that answer but didn't realize I needed adsiedit in order to access searchFlags. Do I need to reboot or anything to see the changes? I addressed a couple attributes last night and they are still showing up in the logs.
Comment: I'm not sure about the reboot, but given it hasn't taken effect, it would seem to be the case.


Why outer measure of Vitali set is greater than 0 or equals to 0?

Question: In the following conservation (link below)
https://www.researchgate.net/post/Bounds_on_the_outer_measure_of_Vitali_Set_in_0_1
There is a person who said that outer measure of the Vitali set on $[0,1]$ is greater than 0. Anyone can tells me why?
Answer:
$m^{\star}(A) \ge 0$

$m^{\star}(A) =0$ implies $A$ is measurable.

Let $\mathcal{V}$ denote the Vitali set.
If $m^{\star} (\mathcal{V}) \not >0$ , then $m^{\star}(\mathcal{V}) =0$ implies $\mathcal{V}$ is measurable.
But $\mathcal{V}$ is non measurable.
Infact $\mathcal{V}$ has full outer measure.
( See here)


finding a route to form mode and add it local tasks

Question: I have a content type named "film" and a form mode named "film_artistic"
in my_module.routing.yml, I have added this entry:
my_module.film.artistic:
  path: 'node/{node}/artistic/edit'
  defauts:
    _entity_form: node.film_artistic
    _title: 'Edit artistic info'
  requirements:
    _permission: 'access content'

But when I try to reach, let say "/node/6/artistic/edit" I got a "Page not found" result
I don't know what I am missing...
My ultimate goal is to have several form mode for my film content type (ex: Artistic, Technical,...) and for each of them, I would like to create a "Local Task" sharing the same base_route: "entity.node.edit_form".
For my first local task, I have to add the following in my_module.links.task.yml:
film.artist:
  route_name: my_module.film.artistic
  title: Edit artistic info
  base_route: entity.node.edit_form
  weight: 20

But of course I can't test it as my main route is not working (node/{node}/artistic/edit)
Answer: I could find a solution with an handy module: https://www.drupal.org/project/form_mode_control
After installation, you can reach any form by using :
 www.your-site.com/node/add/my_content_type?display=machine_name_of_your_form

or
www.your-site.com/node/{node}/edit?display=machine_name_of_your_form

More then this, this module allow you to set permission to access each form mode.
I am still looking for how to add those forms as local task... but the main thing is done
My objective is: if I go to node/add, or node/{node}/edit, I would like to have the default form displayed but also, all the form mode accessible as Tabs (local task)


Integral of Brownian motion is Gaussian?

Question: Let $(W_t)$ be a standard Brownian motion, so that $W_t \sim N(0,t)$. I'm trying to show that the random variable defined by $Z_t = \int_0^t W_s \ ds$ is a Gaussian random variable, but have not gotten very far.
I tried approximating the integral by a Riemann sum: choose $\delta, M$ such that $M\delta = t$, then the integral is approximated by
$$
\sum_{k=0}^{M-1} (W_{(k+1)\delta} - W_{k\delta}  )\delta = \delta \sum\limits_{k=0}^{M-1} X_k
$$
where using standard properties of the Brownian motion, the $X_k$'s are independent identically distributed $N(0, \delta)$ random variables. So I find that $Z_t$ is approximated by a random variable with distribution $ N(0, M\delta^3) = N(0,t\delta^2) $. Now letting $ \delta \to 0$, I find the variance of $Z_t$ is also $0$, which does not make sense to me.
Any help is appreciated!
Comment: That's not the Riemann sum; you want $\sum_{k=0}^{M-1}  \delta W_{k\delta}$.
Answer: First of all, the Riemann sum is given by
$$\sum_{k=0}^{M-1} W_{k \delta} \cdot (\delta (k+1)-\delta k).$$
Note that this expression does not equal
$$\sum_{k=0}^{M-1} (W_{(k+1)\delta}-W_{k \delta}) \cdot \delta.$$

Let $t_k := \delta \cdot k$, then
$$\begin{align} G_M &:= \sum_{k=0}^{M-1} W_{k \cdot \delta} \cdot (t_{k+1}-t_k) =\ldots= \sum_{k=0}^{M-1} (W_{t_{k-1}} - W_{t_k}) \cdot t_k + W_{t_{M-1}} \cdot t \\ &= \sum_{k=0}^{M-1} (W_{t_{k-1}}-W_{t_k}) \cdot (t_k-t) \end{align}$$
where $t_{-1}:=0$. Clearly, $G_M$ is Gaussian, $\mathbb{E}G_M=0$ and (using the independence of the increments)
$$\begin{align*} \mathbb{E}(G_M^2)& = \sum_{k=0}^{M-1} (t_k-t)^2 \cdot \underbrace{\mathbb{E}((W_{t_k}-W_{t_{k-1}})^2)}_{t_k-t_{k-1}} \\ &\to \int_0^t (s-t)^2 \, ds \quad \text{as} \, \, M \to \infty. \end{align*}$$
Hence, as $G_M \to Z_t$ as $M \to \infty$ almost surely, we conclude that $Z_t$ is Gaussian with mean $0$ and variance $\int_0^t (s-t)^2 \, ds$ (see this question for further details).
Remark: In fact, the statement holds in a more general setting. The random variable $Y_t := \int_0^t X_s \, ds$ is Gaussian for any (measurable) Gaussian process $(X_t)_{t \geq 0}$, see this question.
Comment: @Jonas: The factors in the cross terms are indepedent, aren't they?
Comment: @Matteo Note that $W_{k \cdot \delta} = W_{t_k}$. Thus, $$\begin{align*} \sum_{k=0}^{M-1} W_{k \cdot \delta} (t_{k+1}-t_k) &= \sum_{k=0}^{M-1} W_{t_k} \cdot t_{k+1} - \sum_{k=0}^{M-1} W_{t_k} \cdot t_k \\ &= \sum_{k=1}^{M} W_{t_{k-1}} \cdot t_{k} - \sum_{k=0}^{M-1} W_{t_k} \cdot t_k \\ &= W_{t_{M-1}} \cdot t_{M} + \sum_{k=0}^{M-1} (W_{t_{k-1}}-W_{t_k}) \cdot t_k \end{align*}$$ where we used in the last step $W_{t_0}=0$.
Comment: @Calculon Where have I claimed/used this? Anyway, we can apply Fubini's theorem to interchange expectation and integration: $$\mathbb{E} \left( \int_0^t W_s \, ds \right) = \int_0^t \mathbb{E}(W_s) \, ds=0.$$
Comment: @Calculon "Expectation of the square of the integral"..? Could you please be a bit more specific: Which integral are you exactly talking about? And what do you (exactly) want to know? In my answer, I have calculated $\mathbb{E}(G_M)$ and $\mathbb{E}(G_M^2)$. Since $G_M$ is a finite sum for each $M$, we don't need to interchange limit and expectation.
Comment: @Calculon I see. Well, it is not obvious that $\mathbb{E}(G_M^2)$ converges to $\mathbb{E}(Z_t^2)$. In this particular case, this follows from the fact that $G_M$ and $Z_t$ are Gaussian. (Mind: If a sequence $(G_n)_n$ converges pointwise to some random variable $Z$ and $\mathbb{E}(G_n^2)$ converges to some constant $c$, then in general $c \neq \mathbb{E}(Z^2)$. However, under the additional assumption that $G_n$ and $Z$ are Gaussian, we have $c= \mathbb{E}(Z^2)$.)
Comment: This is quite helpful, but I don't understand why when computing $\mathbb{E}(G_M^2)$ you're allowed to simply square the summand. Shouldn't there be a double sum involving cross terms and the like? I'm not seeing why those terms vanish.
Comment: @StefanHansen That makes sense. Thanks!
Comment: @StefanHansen or Saz - Can you please explain me what happened in the dots of this equation? $$\begin{align} G_M &:= \sum_{k=0}^{M-1} W_{k \cdot \delta} \cdot (t_{k+1}-t_k) =\ldots= \sum_{k=0}^{M-1} (W_{t_{k-1}} - W_{t_k}) \cdot t_k + W_{t_{M-1}} \cdot t \\ &= \sum_{k=0}^{M-1} (W_{t_{k-1}}-W_{t_k}) \cdot (t_k-t) \end{align}$$
Comment: All clear now! thanks a lot for the clarifications and prompt reply!
Comment: @saz We have that $\int_0^t W_s(\omega)\ ds := \lim_{mesh(\pi)\rightarrow 0} \sum_{i=0}^{n-1}B_{t_i}(\omega)(t_{i+1}-t_i)$ where $\pi: 0 = t_0<t_1<\ldots<t_n=t$. When you take the expectation of this, what is the justification to interchange the limit and the expectation?
Comment: @saz I thought it was implicit in your answer. But how does Fubini help when you want to compute the expectation of the square of the integral?
Comment: @saz Sorry, by the expectation of the square of the integral I meant $E\left(\int_0^t W_s\ ds\right)^2$. I understand how you manipulate $G_M$ and such but I am having trouble understanding the link between the expectation of $G_M$ (or $G_M^2$) and the expectation of $Z_t$ (or $Z_t^2$).
Comment: @saz Thanks a lot. But then how do we know $Z_t$ is Gaussian?
Comment: @Calculon $Z_t$ is Gaussian as an almost sure limit of Gaussian random variables; see this question: http://math.stackexchange.com/q/232540/. If you have a closer look at the proof (of the linked answer), then you'll see that it actually shows that the $\mathbb{E}(G_n) \to \mathbb{E}(Z)$ and $\mathbb{E}(G_n^2) \to \mathbb{E}(Z^2)$ (as in my last comment, $G_n \to Z$ almost surely, $G_n$ and $Z$ are Gaussian).
Comment: @saz Thank you. Things are much more clear to me now.
Comment: @Calculon You are welcome. :)
Answer: I just found out that we can use the following fact:
If $f:[0,T] \rightarrow [0,T]$ is continuous and deterministic, then
\begin{equation}
\int_{0}^T \bigg( \int_{0}^T f(s,t) \,dW_s \bigg) \,dt =  \int_{0}^T \bigg( \int_{0}^T f(s,t) \, dt \bigg) \,dW_s.
\end{equation}
Hence (I suppose that it works for piecewise continuous functions),
\begin{eqnarray}
\int_{0}^T W_t \,dt & = & \int_0^T \int_0^T \mathbf{1}_{[0,t]} (s) \,dW_s \,dt \\
& = & \int_0^T \int_0^T \mathbf{1}_{[0,t]} (s) \,dt  \,dW_s\\
& = &  \int_0^T T-s \,dW_s\\
& \sim & N \bigg( 0, \int_{0}^T (T-s)^2 \,ds \bigg).
\end{eqnarray}
Comment: This is the "stochastic Fubini theorem" or "Fubini's theorem for stochastic integrals."
Comment: fuar that's a great solution
Answer: This is an old question, but it may be worth providing a better answer:
Let $\phi(Y,t,\omega)$ be the conditional characteristic function $\mathbb{E}[\exp(i\omega Y_T)|Y_t=Y] $.  By the law of iterated expectations this quantity is a martingale. It is then straightforward to derive a partial differential equation for $\phi$ using Ito's lemma and setting the drift to zero. It will become apparent that the solution takes a Gaussian form.
Comment: Using a hammer to kill a fly does not necessarily makes for "better" answers.


For loop csv combination

Question: Trying to combine two csv files using the following code:
<code>df_source1 = pd.read_csv("3_2_conv_perc_1.csv")
df_source2 = pd.read_csv("3_2_conv_perc_{}.csv".format(i))

df_source1[f'column_{i}'] = df_source2[2]
</code>
no idea why it is coming up with an error, though my hunch would be it having something to do with f'' operator.
I am using python but in OSGeo4W shell, though I don't think that should be a reason for the code to not work.
here's the error which doesn't explain easily what the problem is to me:
<code>>>> df_source1[f'column_{i}'] = df_source2[2]
Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3652, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 147, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 176, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 2

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\frame.py", line 3761, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3654, in get_loc
    raise KeyError(key) from err
KeyError: 2
</code>
The data for both files looks like the following:
<code>             0        1  2
0          500  1299500  0
1         1500  1299500  0
2         2500  1299500  0
3         3500  1299500  0
4         4500  1299500  0
</code>
And goes on for more than 909000 rows but I don't think this is a memory issue...
Comment: I believe the problem is `df_source2[2]`, which tries to access a column in the dataframe named `2`, but there is no such column.  It's using `2` as the column _name_, not the _index_.
Comment: We'd need to see the data to find the problem. Make a [mre] and provide all details as text, [not a picture](//meta.stackoverflow.com/q/285551/4518341). For specifics, see [How to make good reproducible pandas examples](/q/20109391/4518341). For more tips, like how to write a good title, see [ask].
Comment: @John You *can* use `.iloc[:, 2]` (note the square brackets), but if you look at the data OP added, the column actually is called "2". It seems like OP was expecting `read_csv` to convert it to int, and I found an existing question about that.
Comment: Is this the data **in** the file or is this what the dfs look like?
Comment: @wjandrea the data presented is what the dfs look like when called
Comment: @JohnGordon I do not understand how I would prevent 2 being read as name rather than number. it currently seems that that is the problem.
Comment: I believe you would use `.iloc()` to select a column by its numeric index.
Comment: Is this what you're looking for? [converting column names to integer with read_csv](/q/37243551/4518341)
Answer: You should join the other dataframe to the first one: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html
And then drop the unused columns: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html
I strongly prefer Polars over Pandas: https://pola.rs/

For loop csv combination


Does trivial fundamental group imply contractible?

Question:
Let $X$ be a path-connected topological space with a trivial fundamental group:
  $$\pi_1(X,x_0)=\{e\}.$$
  Does $X$ have to be homotopic to a point?

I know that the converse is true: a contractible space has trivial fundamental group. But what about the converse? Does the fundamental group tells us enough of the space to fix its homotopy type when it is trivial?
Answer: No, consider the sphere $S^2$.


How to properly practice music in rock band?

Question: We play rock/grunge/punk, our band is composed of drummer (me), 2 guitarists, bass player.
We're not pro, we play for fun but we want to play good and correct. I play drums for about 10 years now, other guys are around 5-6 years of practice. We've been playing together for 3 months, and we do only covers.
We enjoy playing together, but we loose energy on "random/jam/noisy" moments between two covers, and we don't repeat much songs we need to play : for example we start a song, we finish it, we play another one..and we come back to first one only if we'll have time.
Is there any "pattern" to follow, a structure for a beginner musicians playing in a band ?
Comment: There are probably as many ways to go about this as there are bands. You might decide spend part of your practice time on tunes the band already knows, and the remaining part on new tunes. It might be good to play any tune again when one of you hears a trouble spot to try to work out problems. Maybe take a break every four or five tunes. As for "random/jam/noisy moments," that is another topic. I think that answers here would quickly devolve into lots of opinion.
Comment: One thing that to me wastes a lot of rehearsal time is always going back to the beginning of a song when there's a mistake. First - try to recover and continue: when you do play for people, and someone messes up, will you really stop and start again? Hope not! So start at the beginning of that verse, that middle 8, that chorus, and get good enough to start on an anacrucis or the third line of a verse. Proper counting in (you're the drummer!) is sacrosanct.
Comment: Some might say being 'practiced' and 'correct' in styles like punk and grunge is contrary to the styles!
Comment: You need to be honest about why the mistakes are happening.  Are you all just not playing well together or is someone a weak link on one song?  Are you losing the beat?  If you are playing covers there is no reason why each of you can't play with the "album" at home until your part is tight!  Then, in theory, rehearsal should be uneventful.  This is how orchestral musicians work it out (but with sheet music not an album).
Comment: You already accepted an answer, but I began to wonder if I understood the problem correctly. Is the problem that even though you think the playing is not good enough, instead of focusing on making specific aspects of the music better, you just play through songs from beginning to end as if in a karaoke? And even waste time between songs? Do you ever comment on specific things like "I think the bass and kick should play tighter together in this part" or "I think the rhythm guitar in the beginning is sloppy" - and then work on those specific things? Does each player practice at home too?
Comment: @piiperi , thank you for interest ! well, it's a mixture between all questions : when we find out that the song we just played was like 60% fine, we just go to another one, when we find it like 40% good, we do it again but only once. guitarists play at home but not enough (one or two days before we play all together). another problem is that we have a big tracklist, everyone is proposing songs every week
Answer: This is a very complex question and solutions depend on your inter-personal chemistry, personal ambitions, sources of motivation etc.
Picking up on your saying that you lose energy on "random/jam/noisy" moments, try concentrating your efforts on simple, mutually agreed-upon ideas that you can make to work, but that are still enjoyable by everyone. All of you should have a clear idea on what the most essential musical idea is for each song, and what each player's role is in that idea. And then try to execute that idea as clearly and effectively as possible. Keep it simple. If things get random or noisy, it might mean a lack of control, or lack of a central idea, or not committing to the idea.
It's possible that some of you lack the needed technical ability to succesfully perform something that you're trying to do. Then you'll have to slow down, leave out something, do something simpler. Only play things that you can actually make to work.
Rhythm and harmony need coordination between players, so that everybody is playing the same idea, not multiple conflicting ideas.
What is the rhythm? Can you "hum" the essential thing about the accompaniment's rhythm? Agree and coordinate simple ideas for the following "instrument axis". (If you can't agree on these, you need an arranger person or other kind of "boss" to plan and dictate it.)

Kick+snare <--> Bass. Does the bass mute when the snare hits, or does it play on both kick and snare hits? Does the bass and the kick drum play in unison?
Hi-hat+Snare <--> Guitar. Does the guitar play the same hits as the hi-hat, or the same as the snare? Or both?
Guitar <--> Bass. Should they play the same rhythm. At least the guitars shouldn't play very low notes that disagree with what the bass player is doing.
Guitar 1 <--> Guitar 2. Do they play the same rhythm, or complementary rhythms? Are you sure they're playing the right chords and notes, and should they play in different positions (higher and lower on the neck) or the same position?

That said, every rock band should be able to enjoy jamming together, like a 12-bar blues or 8/16 bar loop. It's a sign of a healthy band. Keep a simple, enjoyable groove going. Everyone should contribute to the common rhythm, without messing around. Let each player have a turn playing a solo, but only one at a time. Creating and improvising stuff on the fly can be rewarding - but playing tightly together with other instruments is rewarding too. Let everyone have their moment doing some improvisation, but what comes to playing as a band, it's the tight playing that you should seek your gratification from.
If some of you can't get enough motivation and enjoyment from just playing tightly together, then try to figure out what the problem is. Is the playing not tight enough? Or is the rhythmic (or harmonic) idea too boring? Is the whole genre not enjoyable from someone's point of view? Then you'll have to do something about it. Write more interesting and more enjoyable ideas - but you'll have to stay within the limits of what you can actually do. There are people who just cannot commit to any predetermined musical idea, and want to mess around all the time, elbowing everyone else... but I hope that's not your problem. If it is, you'll have to somehow restrict or contain that sort of compulsive creativity so that it contributes something enjoyable and constructive, and doesn't destroy the simple musical ideas of each song.


Error during "composer drupal-update" for Drupal 8.0.5

Question: I've been running a Drupal 8 site since 8.0.0, using the Address module. As this required some CommerceGuys dependencies in the /vendor folder, I've been using the following commands to load dependencies (and update to newer versions of other components):
<code>php sites/all/modules/composer_manager/scripts/init.php
composer drupal-update
</code>
However when I run this for 8.0.5, I'm getting the following error (not all output included):

Drupal\Core\Composer\Composer::vendorTestCodeCleanup

Removing guzzlehttp/promises (1.0.2)
Installing guzzlehttp/promises (1.0.3)

Drupal\Core\Composer\Composer::vendorTestCodeCleanup

Removing guzzlehttp/guzzle (6.1.0)
Installing guzzlehttp/guzzle (6.1.1)

Drupal\Core\Composer\Composer::vendorTestCodeCleanup

Removing symfony/browser-kit (v2.7.6)
Installing symfony/browser-kit (v3.0.3)

Drupal\Core\Composer\Composer::vendorTestCodeCleanup

Removing fabpot/goutte (v3.1.1)
Installing fabpot/goutte (v3.1.2)

Drupal\Core\Composer\Composer::vendorTestCodeCleanup

Removing behat/mink (v1.7.0)
Installing behat/mink (v1.7.1)

Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  Script Drupal\Core\Composer\Composer::vendorTestCodeCleanup handling the post-package-update event terminated with an exception
[RuntimeException]
    The directory 'tests' in package 'behat/mink' does not exist.

The CommerceGuys modules components are not getting loaded. I'm not sure if this is because of the above exception.
This has worked for every previous Drupal 8 update, so I'm not sure what's different this time.
Comment: See https://www.drupal.org/node/2682003
Answer: There is a patch available here - https://www.drupal.org/node/2664274#comment-10954323, which is RTBC.
I can confirm it's working :)
Comment: Yes, I found the patch and it resolved the problem. Then Drupal 8.0.6 came out a couple of days later. :-)


arg() dependent hidden field in AJAX form

Question: Basically, I have a hidden field I set using arg().
$form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => arg(2)
);

$form['fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#default_value' => "",
    '#size' => 40,
    '#description' => t("Image should be less than xxxxxxxxxxxx."),
    '#upload_location' => 'public://',
    '#prefix' => '
',
    '#suffix' => '
',
);

This value is set correctly once the form loads, but after a call to a AJAX field (managed_file), the form is refreshed and I get the wrong value in arg(2).
I have found arg(1) changed when doing AJAX, which doesn't give me any solution.
Is there any alternative that can be used, or can we skip the hidden field in the AJAX re-build? Is it possible to use a managed_file element without the AJAX submit?
Comment: Are you implementing a new content type, or are you simply building a form?
Comment: actually the hook_form is being used for a Custom Entity...
Comment: That is because the form is rebuilt from the Ajax path, which in this case, `systen/ajax`. You can store the slide ID in form_state, and check if it exists before overwriting (if it is already set, do not overwrite which means the form is rebuilt from Ajax callback).
Comment: `hook_form()` is the hook used by Drupal for content type, which means it is implemented from a module that creates a new content type (for example, the  Blog or the Forum module). In the other cases, you are not implementing `hook_form()`, but you are simply writing a form builder: a function that build a form using the form element provided from the form API.
Comment: I am explaining this because many users confuse the two concepts, which are completely different. In fact, the parameters provided to [`hook_form()`](https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_form/7) are totally different from the parameters provided to a form builder, or other hooks.
Answer: As suggested by @AyeshK, I checked the $form_state in the hook_form before i set the value from arg()
 $form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => (!empty($form_state['input']['slideid']) ? $form_state['input']['slideid'] : arg(2))
);

This could also be done in the hook_form_submit ...
function hook_form_submit($form, &$form_state){

    if($form_state['values']['slideid'] != $form_state['input']['slideid']){
        $form_state['values']['slideid'] = (int)$form_state['input']['slideid'];
    }
   //====save the form data...

}

It looks like a crude fix, but it works for me.
Thank you for your help @AyeshK & @kiamlaluno
Answer: If you want to use ajax submit you need to set callback path using #ajax['path'] otherwise it will automatically set to system/ajax.


Should item nonresponses be removed before calculating Welch's t-test?

Question: I performed a survey in which one of the questions used a grid to let people
express preferences for different features of something, using a Likert-like
scale for each feature.  I coded the values as 1-5.  The people surveyed fall
into two disjoint subgroups; one subgroup had more individuals in it.  Here's
an illustration of the results (the real survey had more people and more
questions). The columns are individual people's responses:
group1 = {
 "feature1" : [5, 1, 4, 5, 2, 5, 5, 4, 4, 2],
 "feature3" : [3, 5, 2, 3, 4, 2, 0, 2, 1, 2],
 "feature2" : [3, 3, 2, 1, 2, 3, 3, 1, 2, 4],
}

group2 = {
 "feature1" : [5, 4, 5, 0, 4, 3],
 "feature2" : [1, 4, 1, 0, 4, 4],
 "feature3" : [2, 5, 3, 4, 3, 2],
}

In a few cases, sometimes a person didn't give a rating for a given feature.
This is represented as 0's in the lists above.  For example, the 4th person
in group 2 didn't give responses for features 1 and 2 and only responded to
feature 3 (here, with a rating of "4").  I have no way to know why people
occasionally did that.  (Not always the same person, not always the same
question.)
Question: If I want to do Welch's unequal variances t-test for the
responses of the two groups to each feature, how should I treat the item
nonresponses?  In concrete terms, if I use Python SciPy's stats.ttest_ind
and pass it two lists of values (one for each group's responses to a given
feature question, or in other words, for a row in the two dictionaries of
responses shown above), then which of the following is the correction approach?

leave the 0's in the lists of values passed to stats.ttest_ind
remove the 0's from the lists of values passed to stats.ttest_ind

On the one hand, I can argue that removing the 0's is correct because they
are not actual responses—they are just place holders we used to code the
results.  On the other hand, if the 0's are removed, then it seems like it
would change the sample mean for one or the other group in the t-test
calculation, because there would be fewer responses than there are people in
the subgroup.
I don't know enough statistics to know whether what's right. Can someone
please explain what the right thing to do is in this situation?
Answer: '0' is an arbitrary label you've used for non-response. Treating it as a number would imply that non-response expresses less satisfaction than any of the other values on the scales—as you've said you don't have any idea why people didn't respond, that hardly seems sensible. What if you'd coded non-response as '99'?
Mapping '0' to any of other the values on the scale is similarly problematic. @Carl suggests mapping to '3', citing a study that claims it makes little difference whether the 'midpoint' on a Likert scale is labelled 'undecided' or 'neutral': I can't see how that bears on the matter of how to treat non-responses (moreover—is '3' in any sense a midpoint in your Likert-like scale?). Potential reasons for someone's not responding might include their never having used that feature, not understanding the question, skipping the item by mistake; so it's a courageous decision to equate it with selecting a response that, after all, they could have selected—indeed were prompted to select—had they wanted to. You'd have to be pretty sure you could tell why people didn't respond, & that it made no odds to lump them in with people who did pick some particular answer, at least for the purposes of your study. Better in general to concede simply that they didn't tell what they think & see where you can go from there.
Excluding non-responses raises two questions. First, what's the population you're interested in making inferences about? Unfortunately it's unlikely to be just people who respond to survey questions about a feature. But it may well be just people who are familiar with a feature, so no harm in excluding people who aren't, if that's who the non-responders are. Second, are non-responders typically going to have different opinions to the responders (within each group)? Probably not when they skip an item owing to a momentary distraction; possibly when they can't follow the question; probably when they think they'll get into trouble if they say they're not keen on a feature.†
I'll note in passing that it's good practice to use feedback from a pilot study to tweak the design to minimize rates of non-response, & to follow up some non-responders to investigate further.
Of course, you know your survey better than me, so you'll have to decide what assumptions you can sensibly make to justify excluding non-responses, if you can at all. That you say there are "a few" cases is grounds for optimism. A sensitivity check of some kind is advisable: a simple, though stringent, one would be to set all the non-responses to 1 for Group 1 & 5 for Group 5, then vice versa; & see just how much difference it makes to your conclusions. It might be a good idea to compare non-response rates between the two groups, if that can help test your assumptions.
A more complex approach is to impute the missing values. If you can predict someone's response to the item on Feature 2, say, fairly well from their response to the items on Features 1 & 3, then you've a way to fill in the blanks for non-responders. The assumption here is that the non-responders on a particular item are typically not going to have different opinions to the responder given their responses to other items. You'd probably need to do some studying or get some help if you wanted to go down this route.
† To be a little more technical, casewise deletion is appropriate when responses are Missing Completely At Random or Missing At Random with respect to a model's predictors (here just 'Group'): no biases are introduced into estimates, & imputation (based on those same predictors) would add no extra information. The early chapters of Little & Rubin (2014), Statistical Analysis with Missing Data introduce these ideas.
Comment: (-1) Folly to exclude what one does not understand. Typically, one ignores questions that do not deserve to be answered. I deleted my response, which I think was misunderstood, badly, and wrongly.
Comment: OP explicit about instruction to answer all questions. Likely the questions were biased or otherwise hopeless as despite instruction to the contrary, they went unanswered. Trump got elected despite surveys, why? Impune inappropriate questions asked of the wrong people? Biased questioning might be taken as an argument in favor of discarding question containing zeros, not zero answers. Otherwise, biased question remains to skew outcome. Converting 0's to neutral response is only one option, true enough, but your answer does not cite anything.
Comment: @Carl: I'm afraid I didn't quite follow all that - consider having another try at an answer if you don't think mine's useful. Certainly having *a lot of* non-responses for an item indicates a problem with it (that should have been picked up before the survey went out), & it might well be sensible to drop it from your analysis altogether if it's not of primary interest (e.g. a candidate predictor in a predictive model for responses to another item). But *a few* non-responses may well be unavoidable, & manageable. You're right that I could do with a reference - I wanted just to ...
Comment: ... introduce, informally, some of the key ideas in the analysis of missing data relevant to this situation, but it'd be helpful to point to somewhere they could be followed up. I was thinking the early chapters of Little & Rubin, but it's a bit of a jump.


CSS Fixed / Absolute positioning to an earlier relative?

Question: I have a sort of super special-case here I guess.
I'm working with many includes. Right now I'm coding in an included content-file. There I need a lightbox which has a 20% black background covering the whole page, including the header which is fixed itself and set in prior PHP files to z-index 200.
The #overlay-wrapper is, because of these includes, placed in #content, which is for other reasons position: relative. The wrapper has 100% width and height and z-index of 1000. Still, logically, it only covers the content-area and not the whole viewport.
Basically I now need a way to tell the #overlay-wrapper to be positioned relatively to the body without telling the content not to be relative, because as mentioned I need it to be relative in other cases.
Putting the overlay in another file would be a pain and I'm just curious if it's possible to tell a box to be positioned relatively to an "earlier" parent and not just the first he finds.
Comment: I think you forgot to post your code. :) As for the question, if you have access to jQuery UI you could use `.position()`.
Comment: an absolutely positioned element will always be relative to the first relatively positioned parent it has.  When you say the overlay is 100% width and height, should that be of the screen or the #content div?  If it is the screen then just make it fixed instead of absolute as fixed is always positioned relative to the viewport
Answer: As long as #overlay-wrapper is within #content and #content is relatively positioned, #overlay-wrapper will always be positioned relative to #content. There is no way to work around this without relocating #overlay-wrapper in the DOM.
You will need to move #overlay-wrapper out of #content, either by modifying your PHP includes (by perhaps even moving it to a separate include of its own and including that elsewhere), or by using JavaScript to relocate it on page load.


Proving that $\liminf_{n\to\infty} x_n = \sup\left\{z : \{n : x_n < z\} \text{ is finite}\right\}$; what does the answer mean?

Question: Suppose $x_n$ is a bounded sequence.
Prove that
$$\liminf_{n\to\infty} x_n = \sup\left\{z : \{n : x_n < z\} \text{ is finite}\right\}$$
I'm having trouble even interpreting what this is suppose to mean. Please could somebody explain it for me?
Comment: What do you mean by "interpreting"? What exactly do you not understand? Do you know what $\liminf_{n\to\infty} x_n$ is?
Answer: Maybe a proof of this can help you understand what this is supposed to mean.
Equivalent are:

$y<\sup\left\{ z\mid\left\{ n\mid x_{n}<z\right\} \text{ is finite}\right\} $
$\exists z\left[y<z\wedge\left\{ n\mid x_{n}<z\right\} \text{ is finite}\right]$
$\exists z\left[y<z\wedge\exists n\; z\leq\inf_{k\geq n}x_{k}\right]$
$\exists n\; y<\inf_{k\geq n}x_{k}$
$y<\lim_{n\rightarrow\infty}\inf_{k\geq n}x_{k}=\liminf_{n\rightarrow\infty}x_{n}$

If the statements $y<a$ and $y<b$ are equivalent then $a=b$


Is it possible to store a new mysql database on another drive?

Question: I am running MySQL on Windows XP.  My data directory is: c:/database/data/
I want to create a new database but store it's data on m:/database/data/
Is it possible to keep the existing data on c:\ and the new data in m:\?
Answer: Yes, using NTFS symbolic links. Create a link in your database directory, pointing to m:\database\data\yourdatabasename.


Joda-Time duration in exact decimal days

Question: I'm trying to use Joda-Time's duration class to calculate the exact days different between two days. Meaning I would like the result to be something like 25.48 days rather than just 25 days. Right now I have:
private static final double MILLISECONDS_IN_DAY = 86400000;

DateTime today = new DateTime();
Duration dur = new Duration(foo.getExpirationDate(), today);
double diff_days = dur.getMillis()/MILLISECONDS_IN_DAY;

But I'm wondering if there's a way to combine the 1st and last line into one that just gives me a double.
Answer: You could eliminate the first line by using Joda-Time's constant instead of declaring your own.
org.joda.time.DateTimeConstants.MILLIS_PER_DAY

Don't forget that if you're trying to calculate another date, there may be a better way to do this. The irregularities in calendars such as leap years are well accounted for within Joda-Time.
Comment: the constant is very helpful, thank you. Do you have an idea of the better way?
Comment: The plus and minus methods of the DateTime object are the best ways to get from one DateTime to another by adding or subtracting a duration or period.

[DateTime.plus(ReadablePeriod period)](http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#plus(org.joda.time.ReadablePeriod))

If all you want to do is calculate the number of days between two times, the above code you have will be accurate for any Duration that includes normal length days. If you want perfect accuracy, you should use a Period and convert each element of the period to days then sum them.


Showing if $f' \in L^2([1,\infty),m)$, then $\frac{f(x)}{x} \in L^2([1,\infty),m)$

Question: Let $f:[1,\infty) \to \Bbb{R}$ be such that $f(1)=0$, $f'$ exists, is bounded, and $f' \in L^2([1,\infty),m)$, then if $g(x)=\frac{f(x)}{x}$, we have $g \in L^2([1,\infty),m)$.
Furthermore, show this fails when we replace $L^2$ with $L^1$.
Attempt
For the first part, I was planning on using integration by parts then realized it gets too messy with the absolute values and all so I tried a change of variables, would I be correct in putting say $x=yt$ then $dx=dt$.
And I get stuck at this step.
For the second part, I found a function and I want to know if it works. I found $f$ to being
$$f(x)=\frac{\ln x}{x}.$$
Clearly $f(1)=0$. And $f'=\frac{1-\ln x}{x^2}$ and this has integral from $1$ to $\infty$ of $0$ while $f(x)/x=\ln x$ diverges. So our $g$ wouldnt be in $L^1([1,\infty),m)$. Shoot n evermind $f(x)/x=\frac{\ln x}{x^2}$..I just noticed that sorry so neither one of my parts for this problem are ok..wow I was so excited
Comment: You could try Poincares inequality
Comment: Hardy's inequality
Comment: im not sure I see how Hardys inequality might be useful here, maybe you meant Holders inequality? @fwd
Answer: Hardy's inequality.
We have for each $R>1$, and $\epsilon>0$,
\begin{align}
\int_{1}^{R}\frac{|f(x)|^2}{x^2}\,dx&=\left[-\frac{|f(x)|^2}{x}\right]_{1}^{R}-\int_1^R\left(\frac{-1}{x}\right)2ff'\,dx\\
&=-\frac{|f(R)|^2}{R}+2\int_1^R\frac{1}{x}ff'\,dx\\
&\leq 0+\int_1^R\epsilon\frac{|f(x)|^2}{x^2}+\frac{|f'(x)|^2}{\epsilon}\,dx.
\end{align}
Here, we have used the trivial inequality $2|ab|\leq |a|^2+|b|^2$ with $a= \sqrt{\epsilon}\frac{f(x)}{x}$ and $b=\frac{f'(x)}{\sqrt{\epsilon}}$.
So, by subtracting the $\int_1^R\epsilon\frac{|f(x)|^2}{x^2}\,dx$ term from both sides, we can rearrange the inequality (once $\epsilon$ is small enough, say $0<\epsilon<1$) and then take the limit $R\to\infty$ to get
\begin{align}
\int_1^{\infty}\frac{|f(x)|^2}{x^2}\,dx&\leq\frac{1}{\epsilon(1-\epsilon)}\int_1^{\infty}|f'(x)|^2\,dx.
\end{align}
If you really wanted to, you could now optimize over $\epsilon$ as well to get a better constant.

So, the point is that when doing the integration by parts, the boundary term at $x=1$ vanishes by hypothesis, while the one at $\infty$ appears with the correct sign so that the inequality points in the right way at the end. So, the upshot is that the boundary terms don't matter. The rest is the standard trick of absorbing part of the RHS into a good LHS.
Comment: Question, could you help me on the second part? Ive tried all sort of functions prob like 20-30 diff functions. Neither work :(
Comment: @anonymous smooth out a function which has a graph like $/^{————————}$, i.e a smooth function which starts off $0$, say $f|_{(-\infty,1]}=0$, then increases for a little bit, then stays constant, say $f|_{[2,\infty)}=1$. Then, $f'$ is compactly supported (between $[1,2]$) so it is obviously integrable, but $f(x)/x$ looks like $1/x$ at infinity so not integrable.
Answer: This deals with the case $f'\in L_2(1,\infty)$ with $f(1)=0$.
An application of the generalized Minkowski inequality yields
\begin{align}
\Big(\int^\infty_1\Big|\frac{1}{x}\int^\infty_0 \mathbb{1}_{[1,x)}(t)\,f'(t)\,dt\Big|^2\,dx\Big)^{1/2}&= \Big(\int^\infty_1\Big|\frac{1}{x}\int^\infty_0 \mathbb{1}_{[1/x,1)}(t/x)\,f'(xt/x)\,dt\Big|^2\,dx\Big)^{1/2}\\\
&=\Big(\int^\infty_1\Big|\int^\infty_0 \mathbb{1}_{[1/x,1)}(u)\,f'(xu)\,du\Big|^2\,dx\Big)^{1/2}\\
&\leq\int^\infty_0\Big(\int^\infty_1|f'(xu)|^2\mathbb{1}_{[1/x,1)}(u)\,dx\Big)^{1/2}\,du\\
&\leq\int^\infty_0\Big(\int^\infty_0|f'(xu)|^2\mathbb{1}(xu>1)\mathbb{1}(u<1)\,dx\Big)^{1/2}\,du\\
&\stackrel{s=xu}{=}\int^1_0u^{-1/2}\Big(\int^\infty_1|f'(s)|^2\,ds\Big)^{1/2}\,du\\
&\leq2\|f'\|_{L_2([1,\infty)}
\end{align}
Comment: and as $f' \in L^2$ we are done, right? since $\vert \vert f' \vert \vert_2 < \infty$, we have $\vert \vert g \vert \vert_2 \in L^2$?
Comment: Also, should you be starting with $\int_1^\infty \frac{\vert f(x) \vert^2}{\vert x \vert^2}dx$ as apposed to $\bigg( \int_1^\infty \bigg\vert \frac{1}{x} \int_0^\infty \chi_{[1,x)}(t)f'(t) dt \bigg\vert^2 dx \bigg)^{\frac{1}{2}}$?
Comment: @anonymous: Notice that  $\big|\frac{f(x)}{x}\Big|^2=\Big|\frac1x\int^\infty_0\mathbb{1}_{[1,x)}(t)f'(t)\,dt\Big|^2$.


A simpler (o rather direct) proof for $P(\{a\})=\big\{ \emptyset, \{a\}\big\}$.

Question: Here's my proof but I'm looking for a simpler or at least direct proof for the indirect part of this proof.
Proof. Given two sets, say $a$ and $x$, it all boils down to stablish.\begin{align*}x\subseteq \{a\}\iff x=\emptyset\vee x=\{a\}\end{align*}
($\impliedby$)Trivial.

It's trivial once we know $\forall S: S\subseteq S\wedge \emptyset \subseteq S$

($\implies$)Let us assume now, $$x\subseteq \{a\}\wedge x\ne \emptyset\tag{*}$$If there is $t\in\{a\}: t\notin x$ by the uniqueness of the empty set we know $x=\emptyset$, a contradiction to $(*)$ So it must be that $\forall t:\big(t\in \{a\}\implies t\in x\big)$. Furthermore, we know $\forall t:\big(t\in \{a\}\iff t\in x\big)$ also because of $(*)$Then,\begin{align*}\Big((*)\implies x=\{a\}\Big)&\iff \Big(x\subseteq \{a\}\implies \big(x\notin \emptyset\implies x=\{a\}\big)\Big)\\
&\iff \Big(x\subseteq \{a\}\implies x=\emptyset \vee x=\{a\}\Big)\end{align*}
as we intended to prove.
Comment: What's the question?
Comment: What's the conjunction of two sets?
Comment: Ok, I figured out how your statements meant to be read now. I implore you to use brackets. Also, though more minor, I recommend not using $\colon$ to mean "such that" in plain text. Anyway, I believe you should add more detail to the argument "by uniqueness of the empty set". It is not very transparent as currently written at which point in the argument you take advantage of the defining property of $\{a\}$.
Comment: What is $\land$ here? Certainly not intersection.
Comment: @Thorgott Conjunction.
Answer: $
\newcommand{\ps}{\mathcal{P}}
\newcommand{\eqv}{\Leftrightarrow}
\newcommand{\emt}{\varnothing}
$
By the definition of the power set,
$$
\forall x: (x \in \ps(\{a\}) \eqv x \subseteq \{a\})
$$
Let $P = \{\emt, \{a\}\}$. Then, we have to show that
$$
\forall x: (x \subseteq \{a\} \eqv x \in P)
$$
to show $P = \ps(\{a\})$.
Since you showed the $\Leftarrow$ part, I will show the other direction proof by contraposition:
$$
\forall x: (x \notin P \Rightarrow x \not\subseteq \{a\})
$$
Suppose $x \notin \{\emt, \{a\}\}$. Then, $x \neq \emt \land x \neq \{a\}$. There must be $b$ such that $b \in x \land b \neq a$. Hence, $x$ is not a subset of $\{a\}$.
Answer: Similar to the proof by Hermis14 but more direct,  avoiding contraposition. As already observed, it suffices to prove that $\forall x\,(x\subseteq\{a\} \implies(x=\varnothing \lor x=\{a\}))$. So consider any $x\subseteq \{a\}$. Thus all members of $x$ (if any) are equal to $a$.
Case 1: $a\in x$. Then $a$ is the one and only member of $x$, so $x=\{a\}$.
Case 2: $a\notin x$. Then $x$ has no members at all, so $x=\varnothing$.
In both cases, $x=\varnothing \lor x=\{a\}$ as required.
Comment: I "get" why all members of $x$, if any, are equal to $a$ but, couldn't it be deemed as an heuristic argument? I mean it's plenty rigurous enough for me but I am wondering...
Comment: @Replik Since we assumed $x\subseteq\{a\}$, any element $y$ of $x$ must also be an element of $\{a\}$ (by definition of $\subseteq$) and must therefore be equal to $a$ (by definition of $\{a\}$).


Scarlett Solo Gen 2 Interface Picks up Audio but Windows doesn't receive anything

Question: I'm using an AKG P220 condenser mic, running XLR to the interface and then USB into my computer.
The microphone shows up as "Scarlett Solo USB" which is correct, but when I test the mic, it doesn't output any sound. I've downloaded the requisite drivers for the interface and whenever I speak into it, the gain ring lights up to let me know that it's actually getting signal, so I know the interface is working, it's just not piping anything to the computer from what I can tell.
Things I've tried:

I've tried turning the gain and monitor both up to no avail.
I've toggled the Direct Monitor switch on and off and still nothing.
Phantom power is turned on.
The interface is set as the default recording device in Windows.
Running a test in Audacity gives me the error: "Error while opening sound device. Please check the recording device settings and the project sample rate." (both are set to 44100)

Again, the interface is clearly picking up the microphone, it's just that it's as if it's not being passed along to Windows properly, which is extremely odd.
Any solutions?
Comment: What application is receiving (or not receiving) the audio?
Answer: So from what I just learned with doing some more testing is that "Scarlett Solo USB" is NOT what you want to see if the device is hooked up.
For the device to be properly configured for Windows, you should see it as "Focusrite USB".
If your interface is getting signal, but Windows is not interpreting that input, then that is a Windows driver issue. More than likely Windows recognized the device when you inserted it into the USB port, which caused whatever drivers on the interface itself to be loaded. These are not the correct drivers and will continue to override the proper drivers until they're uninstalled.
If you've already tried installing the drivers, here's what I did to fix the problem.

Keep the interface plugged into the computer.
Uninstall the current drivers by going into the Device Manager > Audio Inputs and Outputs and then uninstalling the drivers to the interface.
With the device plugged in, reinstall the drivers provided by the manufacturer and restart your computer.
At this point, the audio interface should be working properly.


Redirect traffic from an interface to a VPN tun interface with iptables

Question: I'm trying to achieve something easy but apparently I'm missing something.
In my box I have a VPN client running which created a tun0 interface. The box has external traffic coming from the eth0.
I would like to forward the traffic from eth0 to tun0. I run the following commands:
iptables -A FORWARD -i eth0 -o tun0 -s 192.168.100.0/28 -j ACCEPT
iptables -A FORWARD -i tun0 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A POSTROUTING -s 192.168.100.0/28 -o tun0 -j MASQUERADE

Note that I select the source IPs range because I want to forward only certain range.
Running tcpdump on the eth0 interface I can see the traffic coming in from a machine in the range 192.168.100.0/28 but I can't see traffic going into tun0.
IP forwarding is naturally on.
I'm not sure what I'm really missing here.
IP configuration of eth0 is 192.168.10.93/24 while tun0 is 10.8.8.15/24
➜  ~ ip r
default via 192.168.10.1 dev eth0  metric 100
10.8.8.0/24 dev tun0 scope link  src 10.8.8.15
172.17.0.0/16 dev docker0 scope link  src 172.17.0.1
172.30.32.0/23 dev hassio scope link  src 172.30.32.1
192.168.10.0/24 dev eth0 scope link  src 192.168.10.93  metric 100

Comment: The traffic that get into the box does not have destination `192.168.100.0/28` but it has source `192.168.100.0/28`. the destination is the Internet.
Comment: IP configuration of `eth0` is `192.168.10.93/24` while `tun0` is `10.8.8.15/24`.
Comment: `➜  ~ ip r
default via 192.168.10.1 dev eth0  metric 100
10.8.8.0/24 dev tun0 scope link  src 10.8.8.15
172.17.0.0/16 dev docker0 scope link  src 172.17.0.1
172.30.32.0/23 dev hassio scope link  src 172.30.32.1
192.168.10.0/24 dev eth0 scope link  src 192.168.10.93  metric 100
`
Comment: sure. added the required changes
Comment: the destination of the traffic is the Internet generic external IPs. basically a machine generates Internet traffic that is forwarded to the `eth0` interface of this box and from `eth0` must be forwarded to `tun0` and then finally to the Internet. the most important thing is that the traffic leaves from `tun0` because it's a VPN.
Comment: You talk about forwarding from `eth0` (internet) to `tun0` I can not figure out what you actually want to go where. Can you maybe give a better example of a packet that does not work.
A packet that should reach the internet should be forwarded to `eth0` since that is your internet.
Comment: Basically being the `tun0` interface of a VPN, the traffic should reach the Internet via `tun0` so it will appear masqued by the VPN connection.

Basically in plain English what I'm trying to do is:

all incoming traffic to the interface `eth0` with a specific source IP must be forwarded to the Internet via the interface `tun0` so it will appear behind a VPN connection.
Comment: Can you reach internet over `tun0` as well?
I think your understanding of what forwarding is is wrong.
Could you please verify that you are sure what the source, and destination is in the scenarios you are thinking about.

If you have traffic with a destination of "internet" coming in over `tun0` and want that forwarded to the internet, then it is `eth0` that should do MASQUERADE, but that does not work with your explanation of source range.
Comment: Ok I will review all my assumptions and I will let you know.
Comment: Also I will review this https://serverfault.com/questions/571801/tunneling-traffic-from-eth0-to-tun0-openvpn-ububtu-12-04 because it is exactly what I'm trying to achieve. thanks anyway
Comment: but just to explain you the thing because I think I got what you did not understand, the machine with interfaces `eth0` and `tun0` will have to work as a forwarder. take traffic coming in to the interface `eth0` and shot it to the Internet via the `tun0` intertface.
Comment: So tun0 is now internet and not eth0
What is the IP of the gateway on tun0?
Answer: Since this in the end might be about having traffic from 192.168.100.0/28 go out over tun0
This could be resolved by something like:
ip rule add from 192.168.100.0/28 lookup 10000
ip route add default via ${tun0gwip} table 10000

Also keep the iptables MASQUERADE which is needed unless the tun0 gw can route back to your other network.
Comment: `iptables` is not responsible for where traffic is routed, that is the job of the `routing table`
Comment: I'm going to upvote your answer @NiKiZe but it's not fully correct in my case. In fact w/o `iptables` won't work.
Comment: Thanks I'll try and see if it works. But my question is packets from eth0 should be forwarded to tun0. Why my forward command does not work?
Comment: I'm not really familiar with `ip rule add` command so I need to explore it but this is what I get
`ip rule add from 192.168.100.0/28 lookup 10000 ip: invalid argument '10000' to 'table ID'
`
Comment: I had to install `iproute2` tool. also I have found exactly all the commands needed and `iptables` is necessary at the end of the day otherwise there is no NATing. https://unix.stackexchange.com/questions/490662/how-to-route-traffic-from-br0-to-tun0-when-tun0-is-not-the-default-route-of-the
Comment: You already had MASQURADE part correct so did not include that. Will update to mention that as well.
Answer: This is the exact combination of commands that solved the issue:
Create a new route table named vpn under
➜  ~ cat /etc/iproute2/rt_tables
#
# reserved values
#
255 local
254 main
253 default
0   unspec
#
# local
#
#1  inr.ruhep
1 vpn

and then run:
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

iptables -A FORWARD -i eth0 -o tun0 -s 192.168.100.0/28 -j ACCEPT
iptables -A FORWARD -i tun0 -o eth0 -j ACCEPT

iptables -A INPUT -i tun0 -m state --state RELATED,ESTABLISHED -j ACCEPT

ip route add default dev tun0 table vpn
ip route add 192.168.100.0/28 dev eth0 table vpn

ip rule add from 192.168.100.0/28 table vpn


Access product field from variation field

Question: There are a bunch of product images that are named same as SKU, so I'm just using field--commerce-product-variation--sku.html.twig to show them. All is fine.
I'd like to use the parent product image as fallback image for when the SKU image doesn't exist.
How do I access a parent product field from the product variation field template?
Answer: You'll get the variation object in element['#object']
{% set variation_object = element['#object'] %}
{% set product_object = variation_object.product_id.entity %}

then from product_object you can access the image field
Comment: That worked! Thanks. Then you can access image URI as `product_object.field_product_img.0.entity.uri.0.value`


Como configurar a segurança para servidores dedicados e VPS?

Question: Estou tendo problemas com as configurações de segurança de servidores virtualizados (VPS) e dedicados.
O que preciso fazer para proteger meu servidor Linux, com Apache, contra as principais ameaças de segurança, como rootkits, exploração de portas comuns abertas, logging de ações de root, etc? O que precisa ser instalado e configurado?
Comment: @Tiago abri uma questão no meta para discutirmos essa pergunta. http://meta.pt.stackoverflow.com/questions/4048/essa-pergunta-pode-ser-reaberta
Comment: @williamhk2 boa, vou mudar.
Comment: Caso a sua intenção seja compartilhar algo que possa ajudar o pessoal, sugiro coloque a parte da explicação como resposta. E a parte da pergunta vc coloca como se fosse alguem perguntando: ex.: 'quais as praticas comuns de segurança em VPS/Dedicados?'
Comment: Sim a intenção é compartilhar conhecimento. Tive problemas de segurança, e isso me ajudou muito. Então quero ajudar outros tambem.
Comment: Editei meu comentário @Tiago
Comment: Beleza, ai também outras pessoas com outras dicas, podem responder como complementação à sua resposta! ;)
Comment: @gmsantos, RicardoHenrique, Rray, BrunoAugusto, JorgeB, Seria interessante vocês lerem com atenção antes. Quiz contribuir com conhecimento e não estava fazendo uma pergunta, basta ler a mensagem logo abaixo. Chato isso...
Answer: Via SSH - acesso Shell
Instale o ELS
wget --output-document=installer.sh http://servermonkeys.com/projects/els/installer.sh; chmod +x installer.sh; sh installer.sh; els --update; els --chkrootkit; els --rkhunter; els --chmodfiles; els --disabletelnet; els --hardensysctl; els --libsafe; els --mytop; els ---securepartitions

O ELS "Easy Linux Security" é um instalador de módulos e pequenos scripts de segurança atualizados. Existem muitos módulos disponíveis, vc pode lista-los executando simplesmente o comando els em seu shell. O que instalo acima são os que fazem mais diferença em termos de segurança do servidor: chkrootkit (rootkit), rkhunter (outro rootkit melhor ainda), chmodfiles (ele muda as permissões de acesso e execução de alguns scripts/comandos no servidor para apenas o root executa-los), disabletelnet (desabilita/desliga o telnet, deixando apenas o SSH), hardensysctl (faz um tunnig de sua interface de rede), instala o libsafe (apenas para sistemas 32 bits), mytop (instala um visualizador de processos mysql como o comando TOP faz com o sistema).
Instale o logview
wget http://www.logview.org/logview-install

Instale o CMM
wget http://www.configserver.com/free/cmm.tgz; tar -xzf cmm.tgz; cd cmm; ./install.sh

É um visualizador de logs via navegador, vc não precisa abrir o SSH para ver os logs intrincados do sistema, com este addon do WHM vc os vê via seu painel WHM.
Instale o CMQ
wget http://www.configserver.com/free/cmq.tgz; tar -xzf cmq.tgz; cd cmq; ./install.sh

Instale o CMC
wget http://www.configserver.com/free/cmc.tgz; tar -xzf cmc.tgz; cd cmc; ./install.sh

Configurando a porta do SSH
pico -w /etc/ssh/sshd_config

E mude a linha "Port 22" para a porta que vc deseja (lembre-se de adicionar a porta em seu firewall ANTES ou vc não conseguirá acessar mais o servidor).
Aviso de acesso ROOT
Edite ".bash_profile" o com o comando:
cd root; pico -w /root/.bash_profile

Adicione o código abaixo no final do ultimo comando:
#
# GRAVA LOG E HISTORICO DE ACESSOS ROOT
#
echo `who` >> .access
#
# EMAIL DE AVISO ACESSO ROOT
#
rootalert() {
  echo 'ALERTA - Acesso ROOT SHELL'
  echo
  echo 'Servidor: '`hostname`
  echo 'Data: '`date`
  echo 'Usuario: '`who | awk '{ print $1 }'`
  echo 'TTY: '`who | awk '{ print $2 }'`
  echo 'Origem: '`who | awk '{ print $6 }' | /bin/cut -d '(' -f 2 | /bin/cut -d ')' -f 1`
  echo
  echo 'ACESSO ROOT EXECUTADO.'
  echo
  echo 'Estes usuários estão ativos neste instante como root:'
  echo `who | awk '{print $6}'`
  echo
  echo 'Últimos 10 acessos efetuados:'
  echo `last -n 10`
  echo
  echo 'Informações: Horário deste acesso, Uptime e Load Averange atual'
  echo `uptime`
  echo
}
rootalert | mail -s "Alerta: Acesso ROOT [`hostname`]" SEUEMAILAQUICARAMBA

Instale o CSF Firewall
wget http://www.configserver.com/free/csf.tgz; tar -xzf csf.tgz; cd csf; sh install.sh

Remova o Lynx
Primeiro identifique o pacote que vc tem instalado:
rpm -qa | grep lynx

Depois execute:
rpm -e lynx NOMEDOPACOTE

Instalando e configurado corretamente o Maldetec
wget http://www.rfxn.com/downloads/maldetect-current.tar.gz ; tar -xzf maldetect-current.tar.gz ; cd maldetect-* ; sh ./install.sh ; maldet --update-ver ; maldet --update

Agora configurando, edite o arquivo "conf.maldet" em /usr/local/maldetect, editando a linha "email_alert=0" para "email_alert=1" e a linha "email_addr=" colocando o seu email que receberá o relatório.
Você pode executar ele na linha de comando especifica, por exemplo:

maldet -a /home/USUARIO/
maldet -a /home?/?/public_html

Aqui vai uma dica um tanto que radical: Vc pode configurar o maldetec para ele tentar limpar possíveis trojans ou códigos maliciosos que "colam" em códigos PHP intregos, e caso não consiga ele move o script/arquivo todo para o diretório /usr/local/maldetect/quarantine/. Para isso edite a linha "quar_hits=0" para 'quar_hits=1" e "quar_clean=0" para "quar_clean=1".
Usando o KSPLICE
wget -N https://www.ksplice.com/uptrack/install-uptrack; sh install-uptrack 8c7fea7e7e4e244d9ad4abacd55caf67fbed1d7f46ad31d1f3edea0eb61d8b7b --autoinstall

Distribuições que funciona http://ksplice.oracle.com/legacy#installing-uptrack?wi=1
Creditos: Alexandre Duran.


What's this w-shaped ebony item from my grandma's violin case?

Question: What's this w-shaped ebony item from my grandma's violin case?
Possible it's not violin-related.
Comment: Wait a minute - intensely curious now.  IS there a reason why we shouldn't be photographing violins?
Comment: @Lazy - can't see what harm it could do.
Comment: You are not using the top of the violin as surface for photographing stuff, are you?
Comment: @nuggethead possibly just an abuse of the violin to use it as a table I guess. But I thought it made a nice backdrop, and added some violin context to the post.
Comment: Yeah, what is the photography concern @Lazy?
Comment: Can't believe this hasn't come up previously.
Answer: It's a mute.   It clips onto the bridge. Damps the sound.

This is the traditional type.  There are others:
https://nolaschoolofmusic.com/blog/a-guide-to-violin-mutes
Comment: Wow, that's brilliant, thanks. My daughter DEFINITELY needs to start using this when practising
Comment: @samerivertwice There are also "practice mutes" that are intended for practicing. There are reasons not to use them all the time, though not necessarily what user90393 outlined
Comment: @samerivertwice That type of mute changes the sound rather than greatly diminishing it.  There are other types, made of soft materials, that muffle the sound for practice.
Answer: As others have said, it's a mute, designed to be clamped on the bridge with its fingers between the strings.  I warn against extended use of it for practice reasons: the violin takes considerable time to recover from longer use and redevelop its full tone.
Also it changes the response of the strings to the bowing and makes tone and intonation problems harder to hear.  So (sadly for neighbors and relatives) it is a particularly bad idea for beginners still working out their intonation and tone control.
This goes doubly for the much more thorough "tone wolf", basically a rubber(?)-filled metal barrel with similar clamp-on fingers which is only intended as practice mute.
The mute depicted here is a stronger variant of a mute you'd use in concert for "con sordino" passages.  A mute that looks like a rubber disk and sits on the middle strings on the tailpiece side of the bridge when unused tends to be more practical in use (though not as strong in effect) and does not squeeze the bridge to the point where it takes significant time to recover.  But since it changes sound more than volume, it just serves as a concert mute, not a practice mute.  And when you change the sound of a violin (by adding mutes or using different strings), that does change the body's response as well, so even here you get bounceback effects when using the mute for prolonged times.
Comment: "The violin takes considerable time to recover from longer use and redevelop its full tone"—Sorry, I take exception to this claim. As a lifelong professional violinist, this seems like pseudoscience. However, the next paragraph is so important I'd amplify it: it's not a great idea to do most of your practicing using a practice mute, because the instrument "behaves differently" and you get used to the wrong thing. Practice mutes should pretty much just be for the occasional hotel room. Also: a wooden mute does not *necessarily* mute more strongly than a rubber one; it just has a different tone
Comment: It is simply not completely clear who recovers - it may be the violin (I can think about some residual bridge deformation between the mute fingers). But it is most probably the violinist who needs to recover from the different handling of the muted instrument.
Comment: I can't believe it 'changes the response of the strings to bowing', and 'violin takes considerable time to recover'. You're not supposed to hammer it onto the bridge, are you?
Comment: It's too bad about the 'recover from use' issue, because your detail about practice versus concert, con sordino mutes is informative.
Comment: @user90393 Perhaps you have misunderstood something you have read about how quickly different types of mute can be removed.
Comment: @MichaelCurtis: If Alex Baker only uses one violin, and he's the only person who uses that violin, then after the mute has been used excessively, it might take awhile before the violin would be able to produce rich full sound again (because it couldn't do so until Alex Baler rediscovered his technique).
Answer: This is called a "mute". This can be put onto the bridge (the teeth go between the strings) to get a soft, dampened sound.
Comment: Not 'so called', it actually IS a mute!   'Sticked' is misleading.  There's no glue involved.
Comment: @Laurence Fair point, although "stick" does not only mean _gluing_, but also pressing something into a different thing.
Comment: @Laurence "So-called" isn't entirely inappropriate because "mute" is more likely to mean silenced rather than quietened down, and adding "so-called" indicates that it doesn't fully mute the sound.
Comment: @samerivertwice In fairness, *no* instrument mute *fully* mutes the sound, what would be the point of that?  "Mute" only implies complete silence when talking about electronics, e.g. your TV, or a perhaps a person who cannot talk for whatever reason.  In the context of musical instruments, it always just dampens the sound.


JAVA Guava cache refresh existing elements

Question: I am using Guava to handle caching in my web application; I want to auto refresh the existing elements in my cache every 10 minutes.
this is my snippet code:
private Cache<String, Integer> cache = CacheBuilder.newBuilder.build();

//my main method
public Integer load(String key){
    Integer value = cache.getIfPresent(key)
    if(value == null){
        value = getKeyFromServer(key);
        //insert in my cache
        cache.put(key, value);
    }
    return value;
}

I want to enhance the above code in order to refresh the elements gathered in my cache map as bellow:
 //1. iterate over cache map
 for(e in cache){
    //2. get new element value from the server
    value = getKeyFromServer(e.getKey());
    //3. update the cache
    cache.put(key, value);
 }

Answer: You have to use Guava Cache a bit more. There is no need to call getIfPresent or put as the mechanism is handled automatically.
LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .build(
           new CacheLoader<String, Integer>() {
             @Override
             public Integer load(Key key) throws Exception {
               return getKeyFromServer(key);
             }
           });

Source: https://github.com/google/guava/wiki/CachesExplained
Please note that Guava Cache is deprecated in Spring 5: https://stackoverflow.com/a/44218055/8230378 (you labeled the question with spring-boot).
Comment: Just take a look at ehcache and Caffeine too.  https://www.baeldung.com/spring-boot-ehcache https://www.baeldung.com/spring-boot-caffeine-cache


PostgreSQL - Remover tupla referenciada por outra tabela

Question: Estou com um problema que não encontrei nada no Google (talvez eu não soube perguntar à ele)
Imaginem o seguinte:

Tenho 11 tabelas, uma chamada tbl_pai e outras 10 chamadas tbl_filha1, tbl_filha2, tbl_filha{n}.
Nas tabelas filhas possui um campo chamado id_pai e uma constraint (CONSTRAINT fk_filha_com_pai FOREIGN KEY (id_pai) REFERENCES tbl_pai(id))

Ou seja, 10 tabelas que possuem chaves estrangeiras referenciadas para a tabela principal
A dúvida é: Como posso testar de modo elegante para saber se posso ou não remover uma tupla da tabela principal? Só consegui pensar em duas opções: Tentar excluir o registro da 'pai' e tratar o erro caso o registro esteja referenciado em outra tabela, ou, fazer um COUNT em todas as tabelas filhas para saber se há dependência.
Eu preciso dessa informação para decidir se disponibilizo ou não um botão de DELETE na minha aplicação. Se o registro não possuir referência, eu exibo o botão, se não eu oculto o botão. O problema é que esse botão fica em uma listagem (de registros da 'pai') e essa verificação precisa ser feita para cada registro. Eu fiz usando o COUNT mas ficou extremamente lento visto que a tabela 'pai' possui mais de um milhão de registros.
Existe um método menos custoso?
Obrigado pessoal.
Comment: como você fez o seu count?? poste a Query que você havia feito
Comment: Tudo bem mas preciso deixar de usar o count. No exemplo acima eu falei de tabelas imaginárias, a query que vou postar é a real:
Comment: `SELECT
    (SELECT COUNT(t.id) FROM telemetria t WHERE t.id_sistema = s.id) +
    (SELECT COUNT(a.id) FROM alerta a WHERE a.id_sistema = s.id) +
    (SELECT COUNT(c.id) FROM controle c WHERE c.id_sistema = s.id) +
    (SELECT COUNT(cs.id) FROM cliente_sistema cs WHERE s.id_sistema = s.id) AS qtde
    FROM sistema s
    WHERE s.id = 1;`

A tabela 'telemetria' é muito volumosa. A listagem na aplicação é de sistemas e preciso verificar se disponibilizo ou não o botão para excluir o sistema.
Comment: Gustavo de uma olhada nessa pergunta:
http://dba.stackexchange.com/questions/23041/is-there-a-way-to-test-whether-delete-will-fail-due-to-constraints
Answer: Monteu uma função para isso :
CREATE LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION checkDependence(VARCHAR, VARCHAR, INTEGER) RETURNS BOOLEAN AS $$
DECLARE
    tableName   ALIAS FOR $1;
    columnName  ALIAS FOR $2;
    id          ALIAS FOR $3;

    sqlExecute  RECORD;
    sqlExecute2 RECORD;
    sqlQuery    VARCHAR;
    sqlQuery2   VARCHAR;
    primaryKey  VARCHAR;
BEGIN

    sqlQuery := 'SELECT table_name';
    sqlQuery := sqlQuery || ' FROM information_schema.columns';
    sqlQuery := sqlQuery || ' WHERE table_name != '''||tableName||'''';
    sqlQuery := sqlQuery || ' AND column_name = '''||columnName||'''';

    FOR sqlExecute IN EXECUTE(sqlQuery) LOOP

        RAISE NOTICE '%', sqlExecute.table_name;
        RAISE NOTICE '%', columnName;
        RAISE NOTICE '%', id;

        sqlQuery2 := 'SELECT CASE WHEN count(1) > 0 THEN TRUE ELSE FALSE END AS has';
        sqlQuery2 := sqlQuery2 || ' FROM '||sqlExecute.table_name;
        sqlQuery2 := sqlQuery2 || ' WHERE '||columnName||' = '||id;

        FOR sqlExecute2 IN EXECUTE(sqlQuery2) LOOP
            RAISE NOTICE '%', sqlExecute2;
            IF sqlExecute2.has THEN
                RETURN TRUE;
            END IF;
        END LOOP;
    END LOOP;

    RETURN FALSE;
END;
$$ LANGUAGE plpgsql;

Agora so sera necessário chamá-la no seu select :
SELECT
    checkDependence('table_pai', 'id', id);

Comment: Cara, perfeito! Funcionou maravilhosamente bem e o raciocínio ficou muito inteligente. A query levou 180ms na minha base de dados. Obrigado pela contribuição, dessa forma ficou extremamente modular sendo possível usar para qualquer tabela desde que siga o padrão correto de dar sempre o mesmo nome para as chaves estrangeiras da tabela, como no meu caso. Ótimo, parabéns! Abraços!
Comment: De nada @Gustavo, que bom que ajudou :D
Answer: Fazer count pode ser lento. Solução com o exists:
select *,
    not (
        exists (
            select 1
            from telemetria
            where id_sistema = s.id
        ) or
        exists (
            select 1
            from alerta
            where id_sistema = s.id
        ) or
        exists (
            select 1
            from controle
            where id_sistema = s.id
        ) or
        exists (
            select 1
            from cliente_sistema
            where id_sistema = s.id
        )
    ) as pode_deletar
from sistema s

Se ficar com bom desempenho pode também ser transformado em função
Answer: Se as linhas das tabelas filhas que você está verificando não forem importantes, digo, se você precisa apenas consultar a existência de filhas que referenciem o pai que está tentando excluir, pode usar algo como:
SELECT 1 FROM tbl_filha1 WHERE id_pai = <id do pai>;

[...]
SELECT 1 FROM tbl_filhaN WHERE id_pai = <id do pai>;

Perceba que você terá que fazer isso para as N tabelas filhas (pelo menos até achar um resultado) o que seria um pouco oneroso. Considerando isso, no seu lugar eu faria a rotina para exclusão da tabela pai e trataria o erro na aplicação caso o SGBD barrasse a exclusão, sem fazer verificação prévia de tabelas filhas.
Comment: A sua proposta de utilizar o Count() pode ser uma opção, mas você terá que trabalhar com todas as tabelas filhas, sendo oneroso também.
Comment: Sim, não deixa de ser uma opção porém eu terei que disponibilizar o botão de "Excluir" para todos os registros na aplicação. O que seria perfeito é não exibir o botão para registros que não podem ser excluídos. Como a aplicação é web, eu já trato o erro do SGBD ao tentar excluir pois no meio tempo entre exibir os dados na aplicação e o usuário clicar em excluir, outro usuário online pode ter gerado dependência para o registro.
Answer: Tenta o seguinte:
SELECT s.*,

CASE WHEN
    t.id_sistema IS NOT NULL OR
    c.id_sistema IS NOT NULL OR
    cs.id_sistema IS NOT NULL
    THEN 'disabled'

END as desabilitar

FROM sistema s
    LEFT JOIN telemetria t ON s.id = t.id_sistema
    LEFT JOIN controle c ON s.id = c.id_sistema
    LEFT JOIN cliente_sistema cs ON s.id = cs.id_sistema

O código acima vai listar todos os seus sistemas fazendo um left join com as demais tabelas. Isso vai fazer com que seja listado todos os sistemas independente se existe id_sistema nas outras tabelas.
O CASE WHEN está verificando se id_sistema nas outras tabelas está diferente de nulo. Se não estiver nulo, ele cria a coluna desabilitar = 'disabled'.
Agora no seu HTML, na listagem de sistema, utilize o campo desabilitar para atribuir o disabled ao botão.
<button <?= $rs['desabilitar'] ?>>DELETAR</button>

Se estiver utilizando tag de link, mude o valor da coluna desabilitar para 'none', e ai vc esconde o link com um css inline:
<a style="display:<?=$rs['desabilitar']?>">

Isso para poder evitar o IF. Mas você pode retornar true e fazer um if verificando se desabilitar = true, esconde o botão.
Porém como você disse que são milhões de registros, talvez a melhor opção seja tratar a exceção do banco quando você tentar excluir.
Porém vale tentar essa solução =)
Espero ter ajudado!
Comment: Cara, obrigado pelo esforço e pela contribuição. O raciocínio está correto mas os join deram problema de performance. A query levou 210 segundos em um Linux com i7 e 8GB de ram =) Mas valeu pelo esforço. Abraços!
Comment: A solução do Guilherme ficou realmente muito boa, e pelo que você comentou, bem rápida tbm. Maravilha!
Answer: Eu faria tudo em uma só tabela, utilizando um campo chamado filhode com uma chave estrangeira para o id da própria tabela. Uso isso até para fazer menus. Veja um exemplo:

CREATE TABLE menu
(
  idmenu serial NOT NULL,
  menu character varying(50),
  filhode integer,
  CONSTRAINT pk_idmenu PRIMARY KEY (idmenu),
  CONSTRAINT fk_filhode FOREIGN KEY (filhode)
      REFERENCES menu(idmenu) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
)

Com isso não preciso deste monte tabelas filhas como tbl_filha1, tbl_filha2 ... tbl_filhax. Tudo acontece em uma única tabela.


Getting blank page when error in Laravel Valet WSL

Question: I'm getting a blank page when an error occurs while using Valet WSL.
I can read the error on the "title" of the browser tab but it shows no page content.
I'm on Laravel 7 and valet-wsl 1.0.6 and WSL 1.
Answer: Check the following

.env file is present in the project root with proper values
Check whether proper permissions are set on files and folders especially bootstrap\cache and storage
Whether the web-server user has the appropriate permissions on bootstrap\cache and storage

To set proper permissions on all files and folders in the project
# replace /var/www/myproject with path to your project on webserver root

find /var/www/myproject -type f -exec chmod 664 {} \;
find /var/www/myproject -type d -exec chmod 755 {} \;

To ensure proper permissions on bootstrap\cache and storage`
# replace <non-root-sudo-user> with your username

setfacl -Rdm u:www-data:rwx,u:<non-root-sudo-user>:rwx storage
setfacl -Rdm u:www-data:rwx,u:<non-root-sudo-user>:rwx bootstrap/cache
setfacl -Rm u:www-data:rwx,u:<non-root-sudo-user>:rwx storage
setfacl -Rm u:www-data:rwx,u:<non-root-sudo-user>:rwx bootstrap/cache

These are the common pitfalls for getting a blank page


fontawesome com vuetify

Question: estou inciando um projeto VUEJ+vuetify.
Implementei o pacote do fontawesome para utilizar dos icones free que disponibilizaram.
entretanto, todos os componentes renderizados no navegador que utilizam algum icone, estou tendo o seguinte erro no console.

A configuração foi feita da seguinte maneira.
Critei um arquivo.js denominado 'fontawesome.js' onde importo os icones que irei utilizar.
import Vue from 'vue';
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { faHome, faUser, faIdCard, faSignOutAlt, faSignInAlt, faSync, faBan, faLayerGroup, faServer, faUsers, faChartLine } from '@fortawesome/free-solid-svg-icons';

Vue.component('font-awesome-icon', FontAwesomeIcon);

library.add(faHome, faUser, faIdCard, faSignOutAlt, faSignInAlt, faSync, faBan, faLayerGroup, faServer, faUsers, faChartLine);

export default {
    home: { component: FontAwesomeIcon, props: { icon: ['fas', 'home'] } },
    user: { component: FontAwesomeIcon, props: { icon: ['fas', 'user'] } },
    idCard: { component: FontAwesomeIcon, props: { icon: ['fas', 'id-card'] } },
    signOutAlt: { component: FontAwesomeIcon, props: { icon: ['fas', 'sign-out-alt'] } },
    signInAlt: { component: FontAwesomeIcon, props: { icon: ['fas', 'sign-in-alt'] } },
    sync: { component: FontAwesomeIcon, props: { icon: ['fas', 'sync'] } },
    ban: { component: FontAwesomeIcon, props: { icon: ['fas', 'ban'] } },
    layerGroup: { component: FontAwesomeIcon, props: { icon: ['fas', 'layer-group'] } },
    server: { component: FontAwesomeIcon, props: { icon: ['fas', 'server'] } },
    users: { component: FontAwesomeIcon, props: { icon: ['fas', 'users'] } },
    chartLine: { component: FontAwesomeIcon, props: { icon: ['fas', 'chart-line'] } },
};

Dentro do meu vuetify.js importo o fontawesome, junto com algumas configurações de temas.
import Vue from 'vue';
import Vuetify from 'vuetify/lib';
import colors from 'vuetify/lib/util/colors';
import icons from './fontawesome';

Vue.use(Vuetify);

export default new Vuetify({
    theme: {
        themes: {
            light: {
                primary: colors.purple.darken1, // #E53935
                secondary: colors.blue.lighten1, // #FFCDD2
                accent: colors.indigo.base, // #3F51B5
                error: colors.red.darken1,
                sucess: colors.green.lighten2,
            },
        },
    },
    icons: {
        iconfont: 'faSvg',
        values: icons,
    },
});

E para a utilização do incone faço da seguinte maneira.
             <v-btn
                small
                dark
                text
                @click="logout"
            >
                <v-icon v-text="'$vuetify.icons.signInAlt'" />
                Sair
            </v-btn>

Os icones aparecem normalmente nas páginas, porem a quantidade de erros no console é enorme. Alguem sabe me dizer como resolver esse problema ? Tentei algumas coisas que vi na net a respeito, porem nada surtiu efeito...
att.
Answer: Bom, consegui resolver da seguinte maneira.
Isso ocorre porque existe um problema de compatibilidade com as ultimas versoes do vue e vuetify.
Então fiz o downgrade do vue e vue-template-compiler para a versão 2.6.10, pois estava utilizando a '11'
npm install firstname.lastname@example.com email@example.com

Caso alguem passe pelo mesmo problema...

fontawesome com vuetify


How store a JSON in a QR code using Angular

Question: I'm generating QR codes from my Angular web app. I'm using the npm package ngx-qrcode2 to generate the QR code.
Is there a way with this npm package or another npm package to store a JSON object in the QR. Then read QR,and extract the JSON using the qr reader zxing/ngx-scanner.
Currently, I'm able to achieve this if I convert the JSON to a string, store that string in the QR and then when I read it, a parse it back to a JSON.
This is what I have done so far.
TO GENERATE THE QR CODE
https://stackblitz.com/edit/angular-ja13vl
TO READ THE QR CODE
https://stackblitz.com/edit/angular-qr-reader
Comment: "I'm able to achieve this if I convert the JSON to a string". Does that not solve your question?
Comment: @molamk yes, you are right my friend. I just felt it was a little hackie. This is my first time working with QRs and I didn't know If what I did was the correct or best way to do it
Answer: You seem to have found the solution and it seems totally right I think.

Currently I'm able to achieve this if I convert the JSON to a string

As you say, if you want to store raw JSON in the QR code, you have to stringify it first using JSON.stringify(json).
When reading the QR code, you have no choice but to parse the string to get the raw JSON back, using JSON.parse(str).
But, you could also compress the JSON and store a string representing this compressed JSON instead. This will allow you to store more information in the QR code.
You can use a library like jsonpack for this, which compresses up to 55% of the original size. You can use it like this:
const qrcode = jsonpack.pack(json);
const json = jsonpack.unpack(qrcode);

You can find more compression ideas for QR codes on this page.
Comment: Thanks so much for you answer. It was my first time working with QRs so I didn't know if what I did was correct. Very useful information know that I can even compress a JSON!!! that's awesome. Thanks so much
Comment: @Patricio Vargas, I am happy it helped! Please consider marking the answer accepted if you think it is appropriate!


Identify a group $G$ that has subgroups isomorphic to $\mathbb{Z}_n$ for all positive integer $n$

Question:
Identify a group $G$ that has subgroups isomorphic to $\mathbb{Z}_n$ for all positive integer $n$.

Source: Gallian Contemporary Algebra, Isomorphism Chapter
I am stuck at the very premise of this question. It seems that the question is asking for a single group $G$ which would be isomorphic to every $\mathbb{Z}_n$ ever possible. However, how would I define a bijective mapping from $G$ to $\mathbb{Z}_n$ if their cardinality differs?
According to me, the question itself is flawed. Am I right? If not, what is the mistake in my understanding?
Answer: The question is not asking for the parent group to be isomorphic to all $\mathbb Z_n$, only that for each $n$ it has a subgroup isomorphic to $\mathbb Z_n$. Accordingly, the circle group under addition $\mathbb R/\mathbb Z$ fits the requirements with $\mathbb Z_n\cong\{k/n:k\in\mathbb Z,0\le k<n\}$.
Answer: Two easy examples:

$\displaystyle G = \prod_{n \in \mathbb N} \mathbb{Z}_n$
$G = \mathbb C^\times$


Difference between rbind() and bind_rows() in R

Question: On the web, I found that rbind() is used to combine two data frames by rows, and the same task is performed by bind_rows() function from dplyr.
What's the difference between these two functions, and which one is more efficient?
Comment: It has additional arguments like `.id` etc in `bind_rows`.   `bind_rows` can bind multiple datasets in a `list` whereas `rbind` does only 2 datasets unless you do `do.call`.  Regarding the efficiency, it is easier to check with `system.time` or `microbenchmark` on a large dataset when you get some time
Answer: Apart from few more differences, one of the main reasons for using bind_rows over rbind is to combine two data frames having different number of columns. rbind throws an error in such a case whereas bind_rows assigns "NA" to those rows of columns missing in one of the data frames where the value is not provided by the data frames.
Try out the following code to see the difference:
a <- data.frame(a = 1:2, b = 3:4, c = 5:6)
b <- data.frame(a = 7:8, b = 2:3, c = 3:4, d = 8:9)

Results for the two calls are as follows:
rbind(a, b)
> rbind(a, b)
Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match

library(dplyr)
bind_rows(a, b)
> bind_rows(a, b)
  a b c  d
1 1 3 5 NA
2 2 4 6 NA
3 7 2 3  8
4 8 3 4  9

Answer: Since none of the answers here offers a systematic review of the differences between base::rbind and dplyr::bind_rows, and the answer from @bob regarding performance is incorrect, I decided to add the following.
Let's have some testing data frame:
df_1 = data.frame(
  v1_dbl = 1:1000,
  v2_lst = I(as.list(1:1000)),
  v3_fct = factor(sample(letters[1:10], 1000, replace = TRUE)),
  v4_raw = raw(1000),
  v5_dtm = as.POSIXct(paste0("2019-12-0", sample(1:9, 1000, replace = TRUE)))
)

df_1$v2_lst = unclass(df_1$v2_lst) #remove the AsIs class introduced by `I()`

1. base::rbind handles list inputs differently
rbind(list(df_1, df_1))
     [,1]   [,2]
[1,] List,5 List,5

# You have to combine it with `do.call()` to achieve the same result:
head(do.call(rbind, list(df_1, df_1)), 3)
  v1_dbl v2_lst v3_fct v4_raw     v5_dtm
1      1      1      b     00 2019-12-02
2      2      2      h     00 2019-12-08
3      3      3      c     00 2019-12-09

head(dplyr::bind_rows(list(df_1, df_1)), 3)
  v1_dbl v2_lst v3_fct v4_raw     v5_dtm
1      1      1      b     00 2019-12-02
2      2      2      h     00 2019-12-08
3      3      3      c     00 2019-12-09

2. base::rbind can cope with (some) mixed types
While both base::rbind and dplyr::bind_rows fail when trying to bind eg. raw or datetime column to a column of some other type, base::rbind can cope with some degree of discrepancy.
Combining a list and a non-list column produces a list column. Combining a factor and something else produces a warning but not an error:
df_2 = data.frame(
  v1_dbl = 1,
  v2_lst = 1,
  v3_fct = 1,
  v4_raw = raw(1),
  v5_dtm = as.POSIXct("2019-12-01")
)

head(rbind(df_1, df_2), 3)
  v1_dbl v2_lst v3_fct v4_raw     v5_dtm
1      1      1      b     00 2019-12-02
2      2      2      h     00 2019-12-08
3      3      3      c     00 2019-12-09
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 1) : invalid factor level, NA generated

# Fails on the lst, num combination:
head(dplyr::bind_rows(df_1, df_2), 3)
Error: Column `v2_lst` can't be converted from list to numeric

# Fails on the fct, num combination:
head(dplyr::bind_rows(df_1[-2], df_2), 3)
Error: Column `v3_fct` can't be converted from factor to numeric

3. base::rbind keeps rownames
Tidyverse advocates making rownames into a dedicated column, so its functions drop them.
rbind(mtcars[1:2, 1:4], mtcars[3:4, 1:4])
                mpg cyl disp  hp
Mazda RX4      21.0   6  160 110
Mazda RX4 Wag  21.0   6  160 110
Datsun 710     22.8   4  108  93
Hornet 4 Drive 21.4   6  258 110

dplyr::bind_rows(mtcars[1:2, 1:4], mtcars[3:4, 1:4])
   mpg cyl disp  hp
1 21.0   6  160 110
2 21.0   6  160 110
3 22.8   4  108  93
4 21.4   6  258 110

4. base::rbind cannot cope with missing columns
Just for completeness, since Abhilash Kandwal already said so in their answer.
5. base::rbind handles named arguments differently
While base::rbind prepends argument names to rownames, dplyr::bind_rows has the option to add a dedicated ID column:
rbind(hi = mtcars[1:2, 1:4], bye = mtcars[3:4, 1:4])
                    mpg cyl disp  hp
hi.Mazda RX4       21.0   6  160 110
hi.Mazda RX4 Wag   21.0   6  160 110
bye.Datsun 710     22.8   4  108  93
bye.Hornet 4 Drive 21.4   6  258 110

dplyr::bind_rows(hi = mtcars[1:2, 1:4], bye = mtcars[3:4, 1:4], .id = "my_id")
  my_id  mpg cyl disp  hp
1    hi 21.0   6  160 110
2    hi 21.0   6  160 110
3   bye 22.8   4  108  93
4   bye 21.4   6  258 110

6. base::rbind makes vector arguments into rows (and recycles them)
In contrast, dplyr::bind_rows adds columns (and therefore requires the elements of x to be named):
rbind(mtcars[1:2, 1:4], x = 1:2))
              mpg cyl disp  hp
Mazda RX4      21   6  160 110
Mazda RX4 Wag  21   6  160 110
x               1   2    1   2

dplyr::bind_rows(mtcars[1:2, 1:4], x = c(a = 1, b = 2))
  mpg cyl disp  hp  a  b
1  21   6  160 110 NA NA
2  21   6  160 110 NA NA
3  NA  NA   NA  NA  1  2

7. base::rbind is slower and requires more RAM
To bind a hundred medium-sized data frames (1k rows), base::rbind requires fifty times more RAM and is more than 15 times slower:
dfs = rep(list(df_1), 100)
bench::mark(
  "base::rbind" = do.call(rbind, dfs),
  "dplyr::bind_rows" = dplyr::bind_rows(dfs)
)[, 1:5]

# A tibble: 2 x 5
  expression            min   median `itr/sec` mem_alloc
  <bch:expr>       <bch:tm> <bch:tm>     <dbl> <bch:byt>
1 base::rbind       47.23ms  48.05ms      20.0  104.48MB
2 dplyr::bind_rows   3.69ms   3.75ms     261.     2.39MB

Since I needed to bind lots of small data frames, here is a benchmark for that too. Both speed but especially RAM difference is quite striking:
dfs = rep(list(df_1[1:2, ]), 10^4)
bench::mark(
  "base::rbind" = do.call(rbind, dfs),
  "dplyr::bind_rows" = dplyr::bind_rows(dfs)
)[, 1:5]

# A tibble: 2 x 5
  expression            min   median `itr/sec` mem_alloc
  <bch:expr>       <bch:tm> <bch:tm>     <dbl> <bch:byt>
1 base::rbind         1.65s    1.65s     0.605    1.56GB
2 dplyr::bind_rows  19.31ms  20.21ms    43.7    566.69KB

Finally, help("rbind") and help("bind_rows") are interesting to read, too.
Comment: I'd suggest adding that `bind_rows()` can combine data frames which contain same column names but in different order . For example `bind_rows()` can merge and append DF1: [`Column1`,`Column2`, `Column3`] and DF2: [`Column3`,`Column1`, `Column2`], while `rbind()` would require to resort them to have the same column sequence
Comment: Wait, that's not right. You can totally do e.g. `rbind(mtcars[, 1:3], mtcars[, 3:1])` and it works just fine, despite the fact the columns come in different order.


After singing, how long do you remain warmed up for?

Question: If you are singing on and off during the day, and begin with a decent warm up in the morning, how frequently do you need to sing/do exercises to remain warmed up? Doing a warm-up over and over again during the day would be a little irritating but maybe it's what's required?
Or looking another way, how might you remain 'warm' all day, what is the minimum you need to do to achieve this?
Comment: I get tired out after an hour or so (on a good day, if I'm being honest with myself), and at that point being tired cancels out being warm - at least for me. On guitar, my peak performance for a day is literally a peak - a moment in time. Before the peak, I'm warming up. After the peak, I'm getting more tired. For a gig I try to enter the good zone before the gig starts with a proper warm up, then one song is magically awesome, and then I hope the end of the gig comes before getting tired takes me out of the good zone again. "Warming up" again would just make me more tired.
Answer: The primary purpose of warming up is indicated by the term "warm" up.  Whether warming up for sports activity or singing - it literally means raising the core temperature of the muscles you plan to use in order to increase the efficiency of the muscles and reduce the likelihood of injury.
As it relates to singing, a warm up routine will also serve to loosen up (like stretching) your vocal folds.  Asking tight vocal folds to respond to sudden high intensity singing is a recipe for injury.
Muscles are warmed by increasing the blood flow by increasing the movement of the muscle.  As the neurons fire to tell the muscles to contract, heat is produced in the muscle tissue.  Once the exercise (such as singing) has ceased, the muscles begin to cool.  After 30 minutes of inactivity, a new warm up would be indicated.
Excessive talking after warming up the muscles involved in singing, might delay the time needed for those muscles to completely cool down.  So the amount of time elapsed before a new warm up is indicated may vary to some extent depending on how much talking you do between singing sets.
But it is probably a good idea to do some warm up prior to singing again if more than 30 minutes has gone by since you last sang - just to be on the safe side.
Comment: @WheatWilliams  All excellent advice Wheat.  When I am performing I drink room temperature water.  At the end of the night before packing up my gear - I will have a cold beer.
Comment: A tip -- don't drink ice water or cold water or cold beer while singing or before singing. Drink water or any other drink at room temperature or hotter. Drinking something cold causes constriction in your throat and interferes with singing freely. Also avoid milk, ice cream, yogurt. Some people find that too much tannic acid or caffeine (tea and coffee) dry out the throat. You can have fatigue if you sing when your throat is dry. All of these things may reverse the effects of warming up your voice.