Fauxbourdon in minor - examples from actual compositions

Question: Dimitri Tymoczko has a very nice overview of fauxbourdon harmony in this syllabus. While he gives several example for fauxbourdon in major, he doesn't give examples for minor. I don't know of any examples.
Can anyone cite some examples of fauxbourdon in minor - especially from the time period of Haydn/Mozart?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/35615/discussion-on-question-by-michael-curtis-fauxbourdon-in-minor-examples-from-ac).
Answer: I contacted Dr. Tymoczko and asked for an example. His response was Mozart, piano sonata K310 in A minor, 3rd movement, starting at m.211.
Answer: First - you should be aware that Tymoczko's usage here is not standard.  The term fauxbourdon is usually only used to refer to the late Medieval/early Renaissance technique of almost pervasively harmonizing in this manner.  This is all before tonal harmony, and fauxbourdon can be employed in any mode, though care needs to be taken to use B-flat or B as necessary (or musica ficta in the earliest appearances) to avoid tritones.  That said, I could guess correctly what he meant before reading the link.
The example that comes to my mind - a little later than what you're looking for - is the minor variation in the 2nd movement of Beethoven's Kreutzer Sonata.  It begins with parallel 1st inversion triads as 16th notes over a C pedal.  This first looks like a series of passing tones over a V7 chord, but in measure 4 we get a #iiidim65 - iv6 progression, followed by i6 - flatii6 - V7 - i in measures 5-8.  The last four measures have a completely different harmonization in all the major variations.
Comment: Gjerdingen uses the term fauxbourdon in his book Music in the Galant Style. Why do you say it is not standard use if two published music scholars use the term for styles other than medieval/Renaissance? Regardless, thanks for the Beethoven example. I will look at it tonight.
Comment: Maybe "not widespread" is a better rephrasing?
Comment: Two published scholars does not a standard usage make. Faux bourdon was a form of polyphony that used _primarily_ parallel fourths and sixths beneath the cantus, but it should be noted that the bass was quite a bit freer than just sixths dropped down from the cantus. It derives from the English practice of _faburden_, which set a _tenor_ cantus with a very similar texture. It should be noted that early Tudor English organists used faburden to describe a bass _punctus_ that was derived by faburden rules, again more than just sixths dropped beneath the (unstated) cantus. (_more_)
Comment: If you look at Dufay's _Ave maris stella_, you'll note that the bass tends to use fifths by contrary motion as well as parallel sixths while the tenor runs in parallel fourths with the cantus, and Dufay _specifically_ marks the tenor as "faux bourdon". (Dufay is the first composer we know of to use the term to describe his methods.) The important thing to note is that the perfectly consonant chord in music that uses faux bourdon or faburden is the octave-and-fifth sonority, and it is _not_ just used at cadences. (_more_)
Comment: Now note how parallel first inversions tend to be used in functional tonality: primarily as approaches to strong progressions, or as harmonic sequences (as in Michael's prof's example) _which function as extended approaches to strong progressions_.
Comment: Sorry, I should state that the bass in faux bourdon can move by contrary movement to the _octave_ below the cantus to form an octave-and-fifth sonority. (Hopefully that's clearer.)
Comment: I appreciate you guys making this point about the historical usage, because I assumed other writers used "fauxbourdon" in the way Gjerdingen and Tymoczko did. After doing some searches I can see they are unique in this regard.


Let $p(x)$ be odd degree polynomial ,$g$ be a bounded real valued continuous function

Question: Let $p(x)$ be  odd degree polynomial in one variable with real co-efficient, $g$ be a bounded real valued continuous function,  we need to show $\exists x_0\in\mathbb{R}$ such that $p(x_0)=g(x_0)$
what I did: take $h(x)=p(x)-g(x)$ it is also an odd degree polynomial hence must have a real root, so we are done. am i right? thank you.
Comment: $h(x)$ in fact, cannot be a polynomial unless $g(x)$ is a constant polynomial. As an example, consider $g(x)=\arctan(x)$. It's continuous, real-valued, and bounded. But $h(x)$ is not a polynomial.
Answer: HINT: You have the right general idea, but your $h(x)$ is not necessarily a polynomial. What you can show, however, is that either
$$\lim_{x\to\infty}h(x)=\infty\quad\text{and}\quad\lim_{x\to-\infty}h(x)=-\infty$$
or
$$\lim_{x\to\infty}h(x)=-\infty\quad\text{and}\quad\lim_{x\to-\infty}h(x)=\infty\;,$$
depending on the sign of the leading coefficient of $f$. Now apply the intermediate value theorem to $h$.
Comment: @Panu: Continuity is need to make $h$ continuous, so that you can use the intermediate value theorem. Boundedness is needed to make $h$ unbounded in both directions in the same way that $p$ is unbounded.
Comment: where we are using the fact that $g$ is bounded real valued continuos function?
Answer: Invoking brians Hint: $lim_{x\rightarrow\infty}h(x)=+\infty$ as $g$ is bounded and for the same reason $\lim_{x\rightarrow -\infty}h(x)=-\infty$ as $p$ is of odd degree, now by IVT, there exist $x_0$ $h(x_0)=0$


How to change field values in a view programatically?

Question: I'm working in a custom module that displays date fields. I want to be able to change the date's timezone programmatically.
I've tried implementing hook_views_pre_render(), but that doesn't allow me to format the field value. I'd really like to do the theming inside my module code since that's where the logic is regarding my timezone.
As a total hack, I could use hook_views_post_render(), but then I'd be doing search/replace on the text and that seems like a poor solution.
What other hooks inside my module are available?
Answer: Okay, so after a little more googling I found my own answer on a thread on d.o that address this issue with sample code (which I'm condensing a bit):
<?php
/**
 * Implements HOOK_preprocess_views_view_fields().
 */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  //Replace 'VIEW_NAME' with the machine_name of your view.
  if($view->name == 'VIEW_NAME') {

    //This for loop iterates over all fields in this view.
    foreach ($vars['fields'] as $id => $field) {

      //Custom formatting logic goes here....

      //Set the field value (not the surrounding tags) here.
      $vars['fields'][$id]->content = 'my new value';
    }
  }
}
?>

NOTE Make sure you replace "MYTHEME" with the name of your theme or module in order for this work.


Extracting Multiple Numerical Values from String in R

Question: I have a dataset where I would like to extract only the numerical values from the following string:
{  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}

Specifically, I would like to extract this as two separate columns (043 and 681). Is there a way to do this with these symbols in the string?
Comment: Is this JSON content, and, if so, why do you have such key names?
Comment: I don't think so and the format is from Microsoft Bookings - You can ask "customers" extra questions on there and, for whatever reason, it doesn't create separate columns for these extra questions... just lumps it all into one cell with this odd formating.
Answer: We can use str_extract_all
library(stringr)
str_extract_all(str1, "\\d+")[[1]]
#[1] "043" "681"

If there are more than one element, we can do
library(dplyr)
library(tidyr)
tibble(col1 = str2) %>%
    mutate(col1 = str_extract_all(str2, "\\d+")) %>%
    unnest_wider(c(col1)) %>%
    set_names(str_c('col', seq_along(.)))

-output
# A tibble: 2 x 2
#  col1  col2
#  <chr> <chr>
#1 043   681
#2 313   681

data
str1 <- "{ \"What are the last three digits of your zip code?\": \"043\", \"What are the last three digits of your phone number?\": \"681\"}"

str2 <- c('{  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}', '{  "What are the last three digits of your zip code?": "313",  "What are the last three digits of your phone number?": "681"}')

Comment: Thanks for this! I think this is a good start as it extracts the numbers into characters and I can just convert it into a data frame, however, it doesn't seem to work if I have multiple rows like below

`{  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}
{  "What are the last three digits of your zip code?": "313",  "What are the last three digits of your phone number?": "681"}`

It only extracts the first one. Is there a workaround for this?
Comment: That makes a 2 obs 4 variables like the following:
043 | 681 | 313 | 681
043 | 681 | 313 | 681
@akrun
Comment: @ChrisWiese Can you show the dput of the string.  I assume these are of length 2 and not of 1
Comment: @ChrisWiese Please check the updated exxample in my data and the output I am getting
Comment: The output? [Here](https://imgur.com/HrGnn15) is a screenshot
Comment: @ChrisWiese I can't copy from the image.  Please check the data I showed in my post
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231041/discussion-between-chris-wiese-and-akrun).
Answer: Here is a base R option using strsplit
> Map(function(x) x[nchar(x) > 0], strsplit(str1, "\\D+"))
[[1]]
[1] "043" "681"

> Map(function(x) x[nchar(x) > 0], strsplit(str2, "\\D+"))
[[1]]
[1] "043" "681"

[[2]]
[1] "313" "681"

Answer: Base R Solution:
# Split numeric values into separate columns: df => data.frame
df <- data.frame(
  do.call(rbind, do.call(c, lapply(list(str1, str2), strsplit, "\\D+")))
)

# Subset data.frame to exclude blanks; correctly name vectors: res => data.frame
res <- setNames(df, paste0("col", seq_along(df)))[, colSums(df == "") < nrow(df)]


Show closed form as read only form

Question: I'm working on a Drupal 8 project where I need to show closed webforms as read-only form (without submit button and possibility to answer them), but Webform behaviour doesn't fit my need, as it only display a message "Sorry...This form is closed to new submissions." without displaying the webform.
Is their any way/hook that will allow me to display these closed webform?
Answer: You would need to not close the form but use hook_webform_submission_form_alter() to change all elemnts to be readonly and hide the submit buttons.
Comment: Thanks for you answer but how can I set the status of my form to close / open if I need to set the status of the form to always open ?

Is their any way to handle status of the form and show a readonly form ?
Comment: The existing closed form logic can't be altered. You will have to write custom close form logic. For example, you would have to override the form status when it is loaded, determine if it is closed, override this state to reopen the form and then set rendered form to be readonly

Show closed form as read only form


RVs that are uncorrelated but not independent

Question: Given that $X\sim N(0,1)$, $Z\sim Unif(\{\pm 1\})$, and $Y=XZ$.
$Z$ is independent of $X$. After calculation we found that $Y\sim N(0,1)$.
Show that X and Y are uncorrelated but not independent.
I can only assume that since $Y=XZ$ then, $Y$ must be dependent of $X$.
Comment: I made a mistake of not writing Unif at Z
Comment: https://math.stackexchange.com/q/1064541/321264
Answer: If $X$ and $Y$ are indepedent then  so are $X^{2}$ and  $Y^{2}$. But $Y^{2}=X^{2}$ since $Z^{2}=1$. This makes $X^{2}$ independent of itself which is possible only when it is a constant. This contradicts the fact that $X \sim N(0,1)$.
By independence $EXY=EX^{2}Z=EX^{2}EZ=(1)(0)=0$ and $EXE(XY)=(0)E(XY)=0$ so cavariance of $X$ and $Y$ is $0$.
Comment: @SharonZh I have now proved that the covariance is $0$. $Z^{2}=1$ because $(-1)^{2}=1$ and $(1)^{2}=1$. $Z$ takes only the values $\pm 1$.
Comment: How is $Z^2=1$? Also how do I prove their uncorrelation?


How come there are different UUIDs for multiple environments?

Question: We have D8 site where we use Configuration Management to export and deploy to multiple environments. We recently created a new content type, Blogs where we added a few fields (field_url, field_country). When we export this in our local development environment it all exports to yml files.
When we push these configurations to our Dev and Test environment we are seeing that they are out of sync even after running drush @env cim. Doing further analysis we found that the UUID is different and causing the issue.
However even if we were to export the configuration from Dev environment into our local ones, we still see that the UUID is different.
The settings.php already contains $config_directories['sync'] = 'path/to/config-folder';
How can we get the UUIDs to be in sync? We don't have this issue with other content types nor fields.
Comment: Which version of drupal do you use? I thought uuid was considered in config files (it is present) but maybe it's only since a certain version of the core.
Comment: @ClaireD I tagged the question with 8 since we use Drupal8
Comment: Yes, I understand, but which version of Drupal 8? Many change are added between minor versions. :-)
Comment: @ClaireD Drupal 8.5.1
Comment: What UUID? The site's UUID? The UUID of one config object?
Comment: @leymannx `UUID` of the config object.
Answer: The right way to do it is to create a config_sync folder, you can set it like this in the settings.php file.
$config_directories['sync'] = 'path/to/config-folder';

Then you can run drush cex to export current configuration, and run drush cim to import. I am doing this on all my drupal sites and have never ran into any issues.
You shall commit the config files if you are using git so you can import them on production.
UPDATE: As it is described on drupal.org the full export, on the config page is only to use if you move from one copy of a site to another.

Or the full site configuration can also be dumped as yml files to a tar.gz file. This only works if you're moving configuration between two copies of the same site (e.g. development and production) and for that reason the sites UUIDs must match.

Try to use the drush cex command instead.
Comment: maybe i should've added that information but we are already doing that with the settings.php. We run Configuration Export from the `admin/config/development/configuration/full/export` page through the UI. Basically everything you have highlighted is what we do already.
Comment: running the `drush cex` command to export the active configurations and importing using `drush cim` did the trick.


Do tensor products support cancellation?

Question: If $A\otimes B\simeq A\otimes C$, is it true that $B\simeq C$? If not, under what conditions might this be true?
EDIT:
More specifically, I'm working on a problem where I have a field $K$ and an ideal $I\subseteq A$, where $A$ is an algebra over $K$. I also have that $I\otimes_K K\simeq A\otimes_K K$. I would like to conclude that $I=A$. Can I do this? (This seems like it has to be true.)
Comment: Wouldn't, say, $\mathbb{Z}_2 \otimes \mathbb{Z} \simeq \mathbb{Z}_2 \otimes \mathbb{Z}_4$?
Comment: OK, so I'm pretty bad with tensor products. What would the isomorphism be between those two? The specific case I'm looking at is where A and C are rings and B is an ideal in C. Can I say B = C now?
Comment: In general, given a divisible group $D$ and and a finite group $G$ one has that $D\otimes_\mathbb{Z}G=0$. So, for example $\mathbb{Q}\otimes_\mathbb{Z}S_5=0$. That said, neither of these are the zero group.
Comment: I don't really know, I just remember a bit about it from topology.  I think I got it mixed up with something else there.  I think $\mathbb{Z}_7 \otimes \mathbb{Z}_4 \simeq \mathbb{Z}_7 \otimes \mathbb{Z}_2$ might be a better example.  In that case, you can multiply the generator in the right group by 4 and divide the left by 4 to get $\mathbb{Z}_7\otimes 0$ right?
Comment: See my edit to the post for the specific question. Based on your answers, "cancellation" doesn't apply always, so I've added more information specific to the problem I'm working on.
Comment: Which ring is your tensor product over? K or A?
Comment: @Jack: It's over K
Answer: Let $K$ be the field of rational numbers, $A=K[x]$ be the ring of polynomials with coefficients from $K$, and $I=(x)$ be the ideal of polynomials $f$ with $f(0)=0$.
As $A$-modules, $I \cong A \cong I \otimes_K K \cong A \otimes_K K$, but $I \neq A$.
One of course has cancellation up to isomorphism: if $M$ is an $A$-module, then $M \otimes_K K \cong M$ as $A$-modules, so if $I \otimes_K K \cong A \otimes_K K$, then $I \cong I \otimes_K K \cong A \otimes_K K \cong A$.
If $A$ is a finite dimensional algebra, then things are better:  if $I \otimes_K K \cong A \otimes_K K$ then both $I$ and $A$ have the same dimension as $K$-vector spaces, and since $I \leq A$ and $A$ is finite dimensional, one must actually have equality: $I=A$.
If $A$ is actually an algebra over a subfield of $L$, and you want to change fields to $K$, then look for "separable algebra" to see cases where things behave reasonably.
Comment: What about when $A$, $B$ and $C$ are just three finite dimensional central simple algebras over $k$. Does it follow $A \otimes B \approx A\otimes C$ $\rightarrow$ $B\approx C$?
Answer: Consider $\mathbb{Q} \otimes_\mathbb{Z} \mathbb{Z}_n$. Since we have
$$\frac{a}{b} \otimes k = \frac{a}{nb} \otimes nk = 0,$$
all the pure tensors vanish, so the tensor product does too. Comparing this with $\mathbb{Q} \otimes_\mathbb{Z} \mathbb{Z}$ shows that cancelation need not hold.
Comment: This is not an example, for $\mathbb Q\otimes_{\mathbb Z}\mathbb Z\not\cong\mathbb Q\otimes_{\mathbb Z}\mathbb Z_n$.
Answer: I think I should point out the following in an answer.
As I said in the comment above, if you take a divisible group $D$ and a finite abelian group $G$ then $D\otimes_\mathbb{Z} G=0$ for basically the same reason why the above user pointed out $\mathbb{Q}\otimes_\mathbb{Z}\mathbb{Z}_n=0$--of course neither of the factors is zero.
Moreover, it's clear that there are problems even with "nice" modules. For example, if you take something really nice, say some field $k$, then $k^m\otimes_k k^n\cong k^\ell\otimes_k k^j$ whenever $mn=\ell j$. That said, it's clear that since fields have the IBN property if we choose $m\ne \ell$ that $k^m\not\cong k^\ell$.
Comment: In your comment you had $G=S_5$ which doesn't make any sense. G needs to be abelian (or else it's not a $Z$-module!)
Comment: Wait, I thought dimensions multiplied with tensor products. Wouldn't it be whenever $mn=\ell j$?
Comment: Of course, I've editied it.


Semi-conjugate inverse Wishart posterior, can we obtain the marginal?

Question: In Hoff's text (A First Course in Bayesian Statistical Methods), he uses a semi-conjugate inverse-Wishart prior for the covariance matrix of a multivariate normal process. In equation 7.9, he has the following posterior for the covariance matrix $\Sigma$:
$\{\Sigma\vert \mathbf{y}_1, ..., \mathbf{y}_n, \mathbf{\theta}\}\sim \text{inverse-Wishart}\Big(\nu_0+n, [\mathbf{S}_0+\mathbf{S}_\theta]^{-1}\big)$,
where $\mathbf{S}_0$ is the prior scale matrix and $\mathbf{S}_\theta=\sum_{i=1}^n (\mathbf{y}_i-\theta)(\mathbf{y}_i-\theta)'$. If I'm not wrong, this posterior can also be viewed as the posterior for $\Sigma$ given a diffuse prior for $\theta$ and an inverse Wishart prior for $\Sigma$.
My question is this: Since the posterior here depends on $\theta$, is it possible to remove this conditioning by integrating out $\theta$ from the posterior inverse-Wishart distribution? This would yield some expression for $\{\Sigma\vert \mathbf{y}_1, ..., \mathbf{y}_n\}$, or the marginal posterior for $\Sigma$ if we assume a diffuse prior for $\theta$.
I don't think this yields a closed form solution, is this the case?
Answer: Simple answer
No, you cannot. Since in your problem setting, $\Sigma | \vec{\mathbf{y}}$ and $\theta | \vec{\mathbf{y}}$ are by no means independent. Thus we cannot simply marginalize it.

Your try
Here the problem setting is follows:
$$
\begin{aligned}
\mathbf{y}_1, \cdots, \mathbf{y}_n | \Sigma &\sim \mathcal{N}\left( \theta, \Sigma  \right) \\[10pt]
\Sigma &\sim \mathcal{W}^{-1} \left( \nu_0, \mathbf{S}_0 \right)
\end{aligned}
$$
where $\mathcal{W}^{-1}(\nu, \mathcal{\Psi})$ denotes the inverse-Wishart distribution, which is a generalization of inverse gamma$(\alpha, \beta)$ distribution when dimension $p=1$, with $\nu = 2\alpha, \mathcal{\Psi} = 2\beta$.
Note that we have assumed a given (nonrandom) $\theta$. This is why we can write
$$
\mathbf{y}_1, \cdots, \mathbf{y}_n | \Sigma \sim \mathcal{N}\left( \theta, \Sigma  \right)
$$
in the first place, rather than $\mathbf{y}_1, \cdots, \mathbf{y}_n | \Sigma, \theta \sim \mathcal{N}\left( \theta, \Sigma  \right)$.

Posterior when both $\theta, \Sigma$ : unknown
Alternatively, let us suppose $\theta$ is random, so that we can assume a prior on $\theta$. This is exactly where your idea may kick in. Note that when we start assuming
$$
\begin{aligned}
\mathbf{y}_1, \cdots, \mathbf{y}_n | \Sigma, \theta &\sim \mathcal{N}\left( \theta, \Sigma  \right) \\[10pt]
\Sigma &\sim \mathcal{W}^{-1} (\nu_0, \mathbf{S}_0)
\end{aligned}
$$
we also simply get the posterior of $\Sigma | \vec{\mathbf{y}}, \theta$ , since by the Bayes rule,
$$
\begin{aligned}
p(\Sigma | \vec{\mathbf{y}}, \theta) &= \frac{p(\vec{\mathbf{y}}|\Sigma, \theta) p(\Sigma | \theta)}{\int_{\tilde{\Sigma}} p(\vec{\mathbf{y}}|\tilde{\Sigma}, \theta) p(\tilde{\Sigma}| \theta)} \\[8pt]
&\propto \mathcal{N} \left( \nu_0 + n, [\mathbf{S} + \mathbf{S}_\theta]^{-1}  \right)
\end{aligned}
$$
as in the equation (7.9). Note that unlike the above, we cannot say $\Sigma|\theta \equiv \Sigma$. This is exactly why your idea might need caveats. Rather, if we allow an additional information to be
$$
\theta | \Sigma \sim \mathcal{N} (\theta_0, \Sigma/m)
$$
for a nonrandom hyperparameters $\theta_0$,$m$, things get simpler, i.e. we can get a closed-form solution.

Posterior when $\theta | \Sigma$ : normal
The joint density of $\theta$, $\Sigma$ is commonly referred to as Normal-inverse-Wishart distribution, which is simply formulated as
$$
\theta, \Sigma \sim \mathcal{N} (\theta_0, \Sigma/m) \mathcal{W}^{-1} (\nu_0, \mathbf{S}_0) \equiv NIW(\theta, m, \mathbf{S}_0, \nu_0)
$$
It can be shown that the posterior distribution is also the Normal-inverse-Wishart, as
$$
\begin{aligned}
\theta | \Sigma , \vec{\mathbf{y}} &\sim \mathcal{N} (\theta_n, \Sigma/m_n) \\[8pt]
\Sigma | \vec{\mathbf{y}} &\sim \mathcal{W}^{-1} (\nu_n, \mathbf{S}_n)
\end{aligned}
$$
where
$$
\begin{aligned}
\theta_n &= \frac{m \theta_0 n + \bar{\mathbf{y}} }{ m_n } \\
m_n &= m + n\\
\nu_n &= \nu_0 + n \\
\mathbf{S}_n &= \mathbf{S}_0 + \mathcal{S} + \frac{mn}{m+n} (\bar{\mathbf{y}} - \theta_0) (\bar{\mathbf{y}} - \theta_0)^T
\end{aligned}
$$
where $\mathcal{S} := (\vec{\mathbf{y}}-\bar{\mathbf{y}}\mathbb{1})(\vec{\mathbf{y}}-\bar{\mathbf{y}}\mathbb{1})^T$.

On your comment
So you are now assuming the model
$$
\begin{aligned}
\mathbf{y}_1, \cdots, \mathbf{y}_n | \Sigma, \theta &\sim \mathcal{N}\left( \theta, \Sigma  \right) \\[10pt]
\Sigma &\sim \mathcal{W}^{-1} (\nu_0, \mathbf{S}_0) \\[10pt]
\theta  &\propto 1 \\[10pt]
\end{aligned}
$$
where definitely the improper prior $\theta$ on $p$-dimensional real space $\mathbb{R}^p$  assumed. Most Bayesians accept improper priors if the resulting posterior is proper(see here).
So let us see if this setting leads to the proper posterior. We have
$$
\begin{aligned}
p(\theta, \Sigma) &\propto \mathcal{W}^{-1} (\nu_0, \mathbf{S}_0) \prod_{i=1}^n \mathcal{N}_\mathbf{y}\left( \theta, \Sigma  \right)  \\[10pt]
\end{aligned}
$$
thus we have
$$
\Sigma , \theta | \vec{\mathbf{y}} \sim \mathcal{W}^{-1} (\nu_0 + n, [\mathbf{S}_0 + \mathbf{S}_\theta]^{-1})
$$
Note that the difference between here and in (7.9) is the LHS in (7.9) is $\Sigma | \theta, \vec{\mathbf{y}}$, whereas we have joint here. Thus, we can integrate out $\theta$, (kind of) as what you said,
$$
\begin{aligned}
p(\Sigma | \vec{\mathbf{y}}) &= \int_\Theta \mathcal{W}^{-1} (\nu_0 + n, [\mathbf{S}_0 + \mathbf{S}_\theta]^{-1}) d\theta \\[10pt]
&= \int_{\mathbb{R}^p} \frac{\left|\mathbf{S}_0 + \mathbf{S}_\theta \right|^{-(\nu_0 + n)/2}}{2^{(\nu_0 + n) p/2}\Gamma_p(\frac{\nu_0 + n}{2})} \left|  \Sigma \right|^{-(\nu_0 + n+p+1)/2} e^{-\frac{1}{2}\operatorname{tr}( [\mathbf{S}_0 + \mathbf{S}_\theta]^{-1} \Sigma^{-1})} d\theta \\[10pt]
&= \frac{\left|  \Sigma \right|^{-(\nu_0 + n+p+1)/2}}{2^{(\nu_0 + n) p/2}\Gamma_p(\frac{\nu_0 + n}{2})} \int_{\mathbb{R}^p} \left|\mathbf{S}_0 + \mathbf{S}_\theta \right|^{-(\nu_0 + n)/2} e^{-\frac{1}{2}\operatorname{tr}( [\mathbf{S}_0 + \mathbf{S}_\theta]^{-1} \Sigma^{-1})} d\theta
\end{aligned}
$$
This integral does not converge, which means it is an improper posterior. Thus, most Bayesians may not accept this as the posterior.
To see why the integral does not converge in a little bit heuristic way, say for the one dimensional case($p=1$), the integral is the form
$$
p(\sigma^2 | \vec{\mathbf{y}}) = C \cdot \int_\mathbf{R} \theta^{-(\nu_0 + n)} exp(-\theta^2) d\theta
$$
for some constant $C$. It is known that the above integral converges iff
$$
\nu_0 + n < 1
$$
which is not attainable for $n \ge 1$ cases.

PS. Interestingly, we can show that the marginal prior density of the $\theta$ is multivariate $t$ distribution (reference: Bernardo and Smith[1]), where
$$
\theta \sim T(\theta_0, \kappa, q)
$$
where $\kappa=\nu_0 \mathbf{S}_0/m, q=2\nu_0 - p + 1$.
Reference
[1] Bernardo and Smith, Bayesian theory(1994), p435
Comment: Thanks for the detailed response! I have some clarifications regarding your section "Posterior when both are unknown". If we allow the additional information on theta to be improper diffuse so that p(theta)=1 instead of the standard multivariate normal, we yield the same posterior as equation 7.9.

Conceptually, this is acceptable right? In this case, it would also be conceptually acceptable to think about integrating out theta to yield a marginal, and the only problem is that there is no closed form solutions?
Comment: @bayes No, the real problem is, that does not yield a proper posterior. Please check the latest edit.


Customizing main_menu so that it shows nested elements with styling in Drupal 7

Question: I have the following menu structure which i like to implement in Drupal 7 :

Home

About

About Us

Team

So far i have the base elements displaying correctly using :
<?php
print theme('links__system_main_menu',
array('links' => $main_menu, 'attributes' => array('id' => 'dropdown-menu',
'class' => array('fixed'))));
?>

Problems :

It doesn't display nested elements
I can only control the styling of the first level but in my code i have to apply a subclass of 'sub-menu' according to my theme.

Can someone point me to a starting point ? Thanks
Comment: Exactly in the same boat as you. Starting to annoy me, real bad. Unfortunately your question didnt get an answer.
Answer: As far as I know, it's not possible to make theme('links__system_main_menu' [...]) display the nested elements. That suprised me, too...
One way to fix this: set up a region in the theme for the menu and put a menu block in there. This will display the nested elements, however styling the menu itself won't be much easier than before. theme_menu_tree() and theme_menu_link() hooks could be useful.
Also, check out the Menu block module.
p.s. I'm currently doing something similar that you do and it seems to be quite complicated for me, too, so I just summarized what I've already found.


Find the highest weight and highest weight vector for adjoint representation of $\mathfrak{sl}(n)$

Question: By definition, the highest weight vector for $\mathfrak{sl}(n)$ is an eigenvector for the action of a Cartan subalgebra which is killed by the adjoint action of $E_{ij}$ with $i < j$ (which correspond to the eigenspaces of positive roots). Let us choose, as a Cartan subalgebra, the subalgebra of all diagonal matrices of $\mathfrak{sl}(n)$. Now, the highest weight vector must be of type $E_{kh}$ with $k \neq h$ because all eigenvectors of non zero eigenvalue are elementary matrices of this type. What I find most difficult now is to find an elementary matrix $E_{kh}$ such that $[E_{ij}, E_{kh}] = 0$ for every $i < j$, because this happens everytime $j \neq k$ and $h \neq i$. What am I missing here? Is this even the right way to go about this problem?
Answer: Take $E_{1n}$. Then, whenever $i<j$, $[E_{ij},E_{1n}]=0$.
Comment: Right, thank you. So, if $\epsilon_i(h)= h_i$ where $h_i$ is the $i$-th entry of a diagonal matrix $h$, the highest weight is $\epsilon_1 - \epsilon_n$, is that right?
Comment: Yes, that is correct.


Docker image only work on my machine, but not on AKS

Question: I am new to Kubernetes.
So I have this .NET Core console application Docker image that I built:
FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build
WORKDIR /src
COPY ["DataSync.Entry/DataSync.Entry.csproj", "DataSync.Entry/"]
RUN dotnet restore "DataSync.Entry/DataSync.Entry.csproj"
COPY . .
WORKDIR "/src/DataSync.Entry"
RUN dotnet build "DataSync.Entry.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "DataSync.Entry.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DataSync.Entry.dll"]

This image works perfectly on my machine. However when I try to deploy it as a CronJob in Kubernetes it fails.
Here's the YAML:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: netcore-cronjob
  namespace: aim-ns
  labels:
    app: netcore-cronjob
spec:
  schedule: "*/2 * * * *"
  jobTemplate:
    spec: #JOB
      backoffLimit: 1
      template:
        spec: #POD
          containers:
            - name: netcore-job
              image: <ACR>.azurecr.io/aim/test-data-sync-netcore:v1 #my docker image above pushed to ACR
              command: ["dotnet", "DataSync.Entry.dll"]
              args: []
              resources:
                requests:
                  memory: "64Mi"
                  cpu: "100m"
                limits:
                  memory: "128Mi"
                  cpu: "150m"
          restartPolicy: Never

And the error message I got from viewing the logs on the Pod:
NAME                                        READY   STATUS    RESTARTS   AGE
netcore-cronjob-1582854120-scwfb            0/1     Error     0          19s

And when I run kubectl logs -n aim-ns netcore-cronjob-1582854120-scwfb I get:
  It was not possible to find any installed .NET Core SDKs
  Did you mean to run .NET Core SDK commands? Install a .NET Core SDK from:
      https://aka.ms/dotnet-download

What am I missing here?
Comment: One gotcha with Docker is that `v1` is not unique. What you host uses as `v1` is not necessarily what another host (i.e. a remote Kubernetes node) thinks it `v1`.
Comment: I'd have preferred to see the same error that Kubernetes reported (`It was not possible to find any installed .NET Core SDKs`). Now we have a third problem :-(
Comment: It seems that the image you think you're running on AWS is not the image that you were running locally. Are you able to `docker run  .azurecr.io/aim/test-data-sync-netcore:v1 -- dotnet DataSync.Entry.dll`? This should prove that, what Kubernetes is running on AWS is what you're running locally.
Comment: @DazWilkin thanks for your suggestion. I tried running that command and got a `C:\Program Files\Docker\Docker\resources\bin\docker.exe: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"--\": executable file not found in $PATH": unknown.` error. Maybe we're on to something here.
Comment: do a force docker pull and do a `ls` on the container, I think you are running on the wrong path

`docker pull .azurecr.io/aim/test-data-sync-netcore:v1`

`docker run --entrypoint /bin/bash .azurecr.io/aim/test-data-sync-netcore:v1`
Answer: I had the same problem and I needed to change the "FROM mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim AS base"
(which is used for run the application) change to "FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS base". I thought the runtime has to be enough but...
bye
Markus


.substring() throws a nullPointerException

Question: I am creating a Chess program on NetBeans using jButtons as squares, and my java knowledge is limited to what I have learnt at school.
So this line
int verticalValue = Integer.parseInt(newButton.substring(1,1));

returns a nullPointerException and I can't figure it out whatsoever. Here is the relevant code:
static void pawnMovement(JButton but){
    String buttonName = but.getName();
    String newButton = buttonName;
    int verticalValue = Integer.parseInt(newButton.substring(1,1));

The names of all buttons are in the format letterNumber, so I don't see why this shouldn't work.
Thanks!
Comment: simply print the value of `newButton` and see it yourself though substring is innocent in this case
Comment: Seems to be a classical NullPointerException... What does `but.getName();` return? Certainly, it returns *null* and thats your problem... Chech this before using the variable `newButton` or `buttonName`
Answer: This code should produce a NumberFormatException as the string from substring(1, 1) will always be empty, unless newButton is null because it hasn't been set.
I would check in your debugger that is has been set. I would also ensure you are trying to parse at least 1 character.
Comment: It's really amazing to see that your answer appears more valuable to people even though you _technically didn't_ answer the question. Reputation, indeed, has a huge role to play, I guess. No offence.
Comment: @PankajSinghal maybe you know something I don't but often new developers don't read the error message and don't realise they are not all the same. I made the point that if the OP believes the value can't be null perhaps they misread the exception.
Comment: Totally agree with you, and it is the reality what you have said. But I was making a different point. :)
Comment: @PankajSinghal my impression is that upvoting had an element of randomness.
Comment: Hmm. Maybe. But, I seriously didn't need a sympathetic upvote (if you did it).
Comment: @PankajSinghal I upvoted because you might be correct (there is not enough information in the question IMHO)
Comment: Yeah, I sure did a dangerous thing, in the computing world, of making an _assumption_
Answer: When you do a new JButton("name") - it sets the variable JButton.text as name. Hence, but.getText() should work for you.
In your case, but.getName() returns NULL because you have NOT done but.setName() first. but.setName() is required for but.getName() to work.
Hence, buttonName & newButton are NULL.
Hence, when you do newButton.substring(1,1) - it causes NPE because newButton is NULL


Checagem de tipos em tempo de compilação ADVPL

Question: Estou usando a linguagem ADVPL no meu estágio e tendo muitos problemas com erros de tipo, escopo de variável, etc. Coisas em geral que, ao meu ver, deveriam ser verificadas em tempo de compilação, porém eu só consigo ver o erro em tempo de execução e para tal é necessário logar no sistema, acessar o módulo, etc, etc...
Gostaria de saber se alguém sabe alguma forma de fazer a checagem de tipos em tempo de compilação usando ADVPL ou se existe alguma versão mais nova da linguagem que faz isso.
Tentei procurar sobre checagem de tipos em tempo de execução usando ADVPL mas tudo que encontro são artigos relacionados apenas à compiladores e não à linguagem em si.
Comment: Para evitar longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/93117/discussion-on-question-by-gabriel-belini-checagem-de-tipos-em-tempo-de-compilaca)
Answer: Gabriel,
   Desconheço alguma forma de testar tipos na hora da compilação em Advpl, os tipos são checados no runtime do programa mesmo! Com o Totvs Developer Studio Baseado no Eclipse tem-se uma analise sintática e semântica melhor!
Se for usar pode verificar qual é o que mais se aqueda a você segue os links:

Versão 12 http://ds.totvs.com/tds11_2/
Versão 13 http://ds.totvs.com/tds11_3/

Prefiro a 12 ele e mais leve e syntax hilight e melhor que a do 13, pode usar o VS code também tem o plugin https://marketplace.visualstudio.com/items?itemName=KillerAll.advpl-vscode.
Ele o debug e compilação estão funcionando bem com o Protheus V12, na 11 esta dando alguns problemas.
Testar sem ter que abrir o ERP manualmente
Para testar seu programa sem ter que abrir o ERP manualmente existe essa possibilidade?
Sim ela existe você deve usar o seguinte trecho de código no programa:
PREPARE ENVIRONMENT EMPRESA("02") FILIAL("01") MODULO "COM"
RESET ENVIRONMENT

Exemplo abaixo usando o trecho de código:
User Fuction NomeFucao()
 Local variável
 Local outravar
 Private varival
 PREPARE ENVIRONMENT EMPRESA("02") FILIAL("01") MODULO "COM"
   PROCESSAMENTO DO SEU PROGRAMA AQUI
   .....
   .....
   ....
 RESET ENVIRONMENT
Return Variável ou Nil
Após isso você manda executar o smartclient e no programa inicial U_NomeFucao ao invés de SIGAMDI ou SIGAADV. A sim poupa tempo de abrir o ERP, isso se seu programa for somente background e não envolver componentes visuais!
Para testar os tipos Variáveis pode usar as funções

ClearVarSetGet
ContType   (Retorna um array com o tipo da variável. Diferente do ValType, retorna o tipo original da variável)
Type   (Retorna o tipo de dado de uma expressão ou variável)
VarRef  (Cria referência entre duas variáveis)
ValType   (Retorna um caractere que identifica o tipo de dado da variável informada através do parâmetro)
VarSetGet   (Permite associar um bloco de código a uma variável de programa do Advpl, onde o bloco de código será chamado quando a variável for acessada)
Link da Documentação: http://tdn.totvs.com/pages/viewpage.action?pageId=6063952

Agora que você sabe com testar as variaves ai vamos para os Cast no Advpl e muito livre e tem função converter tudo vou colocar apenas algumas e deixar o link da documentação oficial da TOTVS.

Val( < cString > )   Converte uma sequência de caracteres que contêm dígitos em um valor numérico.
CtoD( < cData > )   Converte uma string formatada para o tipo data
cValToChar( < xParametro > )   Converte uma informação do tipo caractere, data, lógico ou numérico para string, sem adição de espaços na informação.

Assim você pode ver o restante de acordo com sua necessidade na documentação link http://tdn.totvs.com/pages/viewpage.action?pageId=6063599
Esse outro link traz uma lista com todas as funções o SDK documentadas veja de acordo com sua necessidade link http://tdn.totvs.com/pages/viewpage.action?pageId=6063359
O que fazer com os erros e exceções
Pode usar a biblioteca tryexception
#include "tryexception.ch"
Static Function TrySample2()
  Local bError := { |oError| MyError( oError ) }
  Local oError
  ..
  TRYEXCEPTION USING bError
   //Forçando um erro para avalia-lo.
   __EXCEPTION__->ERROR := "__EXCEPTION__"
  CATCHEXCEPTION USING oError
     //"Se ocorreu erro, após o BREAK, venho para cá"
     MsgInfo( oError:Description , "Peguei o Desvio do BREAK" )
  ENDEXCEPTION
  MsgInfo( "Continuo após o tratamento de erro" )
Return( NIL )

Ela esta no GitHub link https://github.com/NaldoDj/BlackTDN/blob/master/include/tryexception.ch
Desenvolvida pelo Marinaldo do Black TDN http://www.blacktdn.com.br/
Espero ter ajudado!
Answer: A linguagem ADVPL possui tipagem dinâmica, ou seja o tipo é definido conforme você o atribui.
o que no caso :
valor := 1
valor := "Um"

Não seria reportado como um erro em tempo de compilação.
Para ajudar nesse quesito utilizamos um manual de boas prática e nele
contém dicas de convenções e de como organizar o seu código.
http://tdn.totvs.com/pages/viewpage.action?pageId=22480357
Para Desenvolvimento sugerimos a utilização da IDE TOTVS Develop Studio
http://tdn.totvs.com/pages/viewpage.action?pageId=107939969
Você tbm pode utilizar o Visual Studio Code com essa extensão:
pesquise no github killerall/advpl-vscode
Comment: Caso queira utilizar o vscode o link é:https://marketplace.visualstudio.com/items?itemName=KillerAll.advpl-vscode
Answer: O ADVPL é uma linguagem que tem sua origem no Clipper. Para você iniciar nela você pode utilizar qualquer manual de Clipper como base, porem recomendo fortemente a leitura do material disponível em:
http://tdn.totvs.com/display/framework/SDK+Microsiga+Protheus
Trabalhar com ela é super simples se você tiver conhecimento em programação estruturada.
Sobre a tipagem, o advpl é muito mais parecido com javascript do que com java. Não sendo fortemente tipado. O que facilita muito no desenvolvimento de regras de negocio ( que é o foco dela).
Caso tenha algo mais especifico com o código fonte, abra uma pergunta com o mesmo para que possamos ajudar.
Answer: Com o lançamento da nova versão do TOTVS Application Server 64 bits, batizado de "Lobo Guará", será possível programar usando um novo código AdvPL, diferenciado pela extensão do arquivo, com pontos fortes na orientação a objetos e tipagem de variávels -- linguagem TL++.
Para maiores informações, acesse o Link da documentação oficial do TL++ no TDN -- http://tdn.totvs.com/display/tec/Tipagem+Forte


equivalence relations questions

Question: Question $1$: Let $S = \{1,2,3,4,...,9\}$. Let $R$ be the relation on the power set of $S$ defined by:
for every $X,Y$ in the power set of $S$, $XRY$ iff $\{1,2,3\}$ is a subset of $X$ or $Y$.
Is the following true?
$1$: for every $X$ in the power set, there exists a set $Y$ in the power set such that $XRY$. I think this one is true because we can choose $Y$ to be $\{1,2,3\}$.
$2$: There exists a set $X$ in the power set such that for every $Y$ in the power set, $XRY$. I think this one is also true because $X$ can be $\{1,2,3\}$ and the relation will hold.
$3$: how many sets $X$ in the power set are there such that $XR\{1\}$ are there?
I think the answer is $2^7$ because $X$ has to have $\{1,2\}$ in this case but for the rest of the elements we can either put them or not, it doesn't matter.
Question 2: let $A = \{1,2,3,....,250\}$. Define $R$ on $A$ cross $A$ by
for any $(a,b)$ , $(c,d)$ in $A$ cross $A$, $(a,b)R(c,d)$ iff $a+b = c+d$.
1: How many equivalence classes does R have? Explain
I'm not sure about this one but I think it is (250 choose 2) ? if that is true how can I explain it?
Thanks!
Answer: Agree with 1 and 2. 3 is on the right track. If by "is a subset of $X$ or $Y$" you mean "is a subset of $X\cup Y$" then the answer is right, though you meant $X$ has to have $2$ and $3$ (not $1$ and $2$). If it means "is a subset of $X$ or a subset of $Y$", then it's wrong. You need to have $\{1,2,3\}\subseteq X$ since its not a subset of $\{1\},$ so there are $2^6$ possibilities.
For the second one there are as many equivalence classes as unique sums of two elements. You can make any number from $2$ to $500.$
Comment: Thanks! for 2, How can I count the unique sums? I still don't get it.
Comment: @Justagirl it's just every number  you can write as the sum of two elements of the set {1,2,3, ... 250}. So 1+ 1 =2, 1+2 =3, 1+3 =4 .... 2+2=4, 2+3  = 5... etc. There will be a lot of repeats if you count this way but it's pretty easy to figure out what set of numbers come out. Each of these will represent an equivalence class, so for instance (1,3) and (2,2) are both in the equivalence class of pairs that sum to 4. (250,250) is the only element of the equivalence class of pairs that sum to 500, etc. Are there pairs that sum to 501? 499? What are the possibilities?
Comment: Oh ok, I get the question now but I still don't know how to count them :(
Comment: @Justagirl You can make any number from 2 to 500 as the sum of two elements of {1,2,3,..250}. You can count the numbers between 2 and 500.
Comment: Alright. Thank you! I understand

equivalence relations questions


Converting microservice to Knative

Question: Knative is currently in alpha. I need to develop a service, so that when knative is released the conversion is straightforward.
What type of kubernetes deployed service would most easily be converted to knative? I also will be leveraging Istio. So just want to make this as simple as possible.  (Also any estimates on when knative will be released or where I should check for that information).
Answer: The latest release of Knative, v0.7, is v1beta1 not alpha and as far as I'm aware the API's are now very close to how they will be in v1.0.
We currently use Knative v0.7 and I would suggest developing the apps using that until v1.0 is released.
R.E. Knative v1.0 release, I would keep an eye on these two github milestones: https://github.com/knative/serving/milestone/18 & https://github.com/knative/serving/milestone/24 . The latter milestone is due on August 06 2019 & currently "The ambition of 0.8 [this milestone] is to be a release candidate for a "v1" of serving."

Converting microservice to Knative


Is there any C++ style guide that talks about numeric literal suffixes?

Question: In all of the C++ style guides I have read, I never have seen any information about numerical literal suffixes (i.e. 3.14f,  0L, etc.).
Questions

Is there any style guide out there that talks about there usage, or is there a general convention?
I occasionally encounter the f suffix in graphics programming. Is there any trend on there usage in the type of programming domain?
Comment: You use them when you need to use them.  Do you need a `float` constant?  Use an `f` suffix.  Do you need an `unsigned` constant?  Use a `u` constant.  And so on.
Comment: I'm not quite sure what your questions are. Are you asking about the *meaning* of the numeric literal suffixes, or are you asking about whether people have established some conventions around their use?
Comment: @GregHewgill: I'm asking about whether people have established conventions on their use.
Answer: The only established convention (somewhat established, anyway) of which I'm aware is to always use L rather than l, to avoid its being mistaken for a 1. Beyond that, it's pretty much a matter of using what you need when you need it.
Also note that C++ 11 allows user-defined literals with user-defined suffixes.
Comment: Good answer, I was looking for a rationale to prefer the uppercase version.
Comment: Well, I have been using the lower case version for years, and never had one confusion about this, or heard of anyone being confused by this.. maybe depends on the font used.. My counter argument to use lowercase would be: it is less typing (holding shift). I know that reading code is more important, but if it doesn't seem to matter for reading in my (limited) experience, then this is a valid argument. I'm also a long time RSI patient so things like holding shift matter to me.
Answer: There is no general style guide that I've found.  I use capital letters and I'm picky about using F for float literals and L for long double.  I also use the appropriate suffixes for integral literals.
I assume you know what these suffixes mean: 3.14F is a float literal, 12.345 is a double literal, 6.6666L is a long double literal.
For integers: U is unsigned, L is long, LL is long long.  Order between U and the Ls doesn't matter but I  always put UL because I declare such variables unsigned long for example.
If you assign a variable of one type a literal of another type, or supply a numeric literal of one type for  function argument of another type a cast must happen.  Using the proper suffix avoids this and is useful along the same lines as static_cast is useful for calling out casts.  Consistent usage of numeric literal suffixes is good style and avoids numeric surprises.
People differ on whether lower or upper case is best.  Pick a style that looks good to you and be consistent.
Comment: @bobobobo I think so...  Either that or 0ull.  I tend to prefer upper case because 'l' looks like '1'.  Using suffixes is especially important with C++11 auto.
Answer: The CERT C Coding Standard
recommends to use uppercase letters:

DCL16-C. Use "L," not "l," to indicate a long value
Lowercase letter l (ell) can easily be confused with the digit 1 (one). This can be particularly confusing when indicating that an integer literal constant is a long value. This recommendation is similar to DCL02-C. Use visually distinct identifiers.
Likewise, you should use uppercase LL rather than lowercase ll when indicating that an integer literal constant is a long long value.
Answer: MISRA C++ 2008 for the C++03 language states in rule M2-13-3 (at least, as cited by this Autosar document) that

A "U" suffix shall
  be applied to all octal or hexadecimal
  integer literals of unsigned type.

The linked document also compares to JSF-AV 2005 and HIC++v4.0, all these four standards require the suffixes to be uppercase.
Nevertheless I can't find a rule (but I don't have a hardcopy of MISRA C++ at hand) that states that the suffixes shall be used whenever needed. However, IIRC there is one in MISRA C++ (or maybe was it just my former company coding guidelines…)
Answer: Web search for "c++ numeric suffixes" returns:
http://cpp.comsci.us/etymology/literals.html
http://www.cplusplus.com/forum/general/27226/
http://bytes.com/topic/c/answers/758563-numeric-constants
Are these what you're looking for?
Comment: I was looking for an authoritative source, such as the Google C++ style guide, etc. that has an established convention for their use. You can Google all you want, but you won't find anything because it seems that such a thing doesn't exist.


Display only properties with values in TimeSpan Display Template

Question: I need to create a display template in ASP.NET MVC 3 that will display a Timespan, showing only the properties with values set. Here are some examples to show what I mean:
Timespan: 1 day, 2 hours, 3 minutes
Required display: "1 day, 2 hours, 3 minutes"

Timespan: 0 days, 2 hours, 1 minute
Required display: "2 hours, 1 minute"

Timespan: 0 days, 5 hours, 0 minutes
Required display: "5 hours"

So as you can see, I need to show only the non-zero values; but I don't know how... apart from an inelegant solution with many if statements. I want to find a better way.
Here is my current code:
@model TimeSpan

@if (Model.Days > 0)
{
    @Model.Days if (Model.Days > 1)
                {<text>days</text>}
                else
                { <text>day</text>}
}

@if (Model.Hours > 0)
{
    if (Model.Days > 0)
    {
        @:,
    }
    @Model.Hours if (Model.Hours > 1)
                 {<text>hours</text>}
                 else
                 { <text>hour</text>}
}

@if (Model.Minutes > 0)
{
    if (Model.Days > 0 || Model.Hours > 0)
    {
        @:,
    }
    @Model.Minutes if (Model.Minutes > 1)
                   {<text>minutes</text>}
                   else
                   { <text>minute</text>}
}

Comment: I think Peter has an answer similiar to your problem at his question: http://stackoverflow.com/questions/842057/how-do-i-convert-a-timespan-to-a-formatted-string
Comment: Why not extract it out into a utility or helper method which you can then just call?
Comment: Yes I can also extract it as an extension method, but what am asking for is help with the logic / code structure.
Answer: You might refactor a bit (untested, not sure if @functions will work in a template file, but... why wouldn't it ?)
@model TimeSpan

@functions{
    public string FormatElement(int value, string text){
        if (value == 0) return string.Empty;
        if (value > 1) text +="s";
        return string.Format("{0} {1}", value, text);
    }
}

@string.Join(", ",  new[]{
                        FormatElement(Model.Days, "day"),
                        FormatElement(Model.Hours, "hour"),
                        FormatElement(Model.Minutes, "minute")
                    }
                   .Where(m => m != string.Empty));

Answer: As @Serv commented this was answered at How do I convert a TimeSpan to a formatted string? by Peter.
Please go there to see his solution.


Drupal Commerce - Update profile on order without cloning?

Question: I understand the reasoning behind preserving integrity of data for existing orders tied to profiles, however...
I have a page where the user can edit the order contents and change their billing or delivery information. Instead of create a new profile, I would like to save the data directly to the order being viewed. I don't want it to affect new orders created later, either.
How can I do this? It would seem that every time commerce_customer_profile_save is called, a brand new profile is created.
This isn't a standard commerce workflow, but most of the fundamentals are there. A customer can have many open orders at any given time, and I want the flexibility for them to change the delivery address ON a specific order and save it for that order only. Someone out there has to have done this I would believe.
Answer: How about something like this leveraging Drupal's Entity API:
<code>//assume we retrieved the $order_id via a page callback argument or something similar
$my_order = entity_load('commerce_order', array($order_id));

$billing_profile_id = $my_order[$order_id]->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'];
$billing_profile = entity_load('commerce_customer_profile', array($billing_profile_id));

// **replace this comment with PHP logic to update the profile values**

//save our customer profile object using the updated values from logic above
$success = entity_save('commerce_customer_profile', $billing_profile[$billing_profile_id]);
</code>
This allows us to directly edit the customer profile object associated with a particular order, and leaves the rest of the profiles unaffected.
Comment: I had the same idea however this still causes a new profile to be created every time :(


How to set Arial Unicode Ms Font for Crystal Report Chart (Pie)?

Question: Can Any one know how to Change Font of Chart in Crystal Report When I Generate Report Using C# .NET it Display Fine in my Application  but When Export as PDF Or Print this Pie Chart it does not Show my Native Language But instead it show  ' ?????? ' I want to set Arial Unicode MS Font but I can't  find any option in Chart Expert to set Arial Unicode MS Font Please Anyone  Have any Solution For  this  Problem   …..
Comment: Any feedback to the answerers? I'd like to know which answer helped you and, if not, why they didn't work.
Answer: It's in the Chart Expert under Text. Open Chart Expert, click on Text tab, click on Font. Please see the screenshot.
Answer: in visual studio find CrystalReport menubar and go to Design after that go to defualt setting select Font tab and change your font in chart,Fields,TextObjects,...etc
CrystalReport > Design > DefualtSetting... > Font > Chart


Synth pads summed to mono get quieter. How to fix?

Question: I use pads in almost all of my tracks and they sound good in stereo mode but when I check in mono, suddenly a large part of the pad sound disappears.
Anybody know a trick in arrangment or mixing to prevent that?
Comment: What are you using to create the pads?
Comment: If i want to create them myself , i usually use serum, otherwise i use nexus, synthmaster, analog lab and ...
Answer: If you have wide-sounding pads with poor mono compatibility, the chances are that it is using some kind of phase-inversion to achieve this apparent width.
When you add two phase-inverted signals together they cancel each other out & if perfectly out of phase, you get silence.
One trick to avoid this is to put a slight delay on one side of the signal only.
This will of course change the original stereo sound somewhat, but will prevent that simple phase-cancellation when summed to mono.
Experiment with the delay until you get a result that is satisfactory for both situations - this is best done on a rig you can quickly flip from mono to stereo.
Comment: Thanks. I also tried to decreas the stereo signal of my pad, using imagers, that helped a little too. Just a quick question, how do i add delay to one side of my signals?
Comment: Depends on your mix environment. At worst, split the track into two mono tracks.
Answer: I assume when you say "a large part of the pad sound" you are refering specifically to the dynamics and stereo width (tone) of the synth. As stereo instruments are positioned within the stereo field, their overall volume will differ if summed to mono, increasing or sometimes decreasing the volume slightly. The reason for this is to do with the phase relationship of your sound in stereo. https://larryjordan.com/articles/audio-mono-vs-stereo-levels/
https://en.m.wikipedia.org/wiki/Pan_law
Secondly, stereo width adds a tonal quality that in itself can only be described as being stereo... or wide(r) or however else you want to put it. Again depending on the phase of your synth, the wideness may be affected a lot or a little when summed to mono. (You can check it's phase relationship with a correlation meter, +1 is good, -1 is bad, the closer to +1 your correlation is, the less problems you'll have with phase and therefore stereo/mono summing).
Whether any of this is useful depends on why you want to sum to mono? Usually Bass frequencies are kept in mono, if you have phase problems with different sounds then you can EQ Mid/side the bass/lower mid frequencies to get rid of most problems. If you have a synth with bass/treble frequencies, consider splitting the sound into two tracks, one for bass below 120Hz (For example) and one for treble above (120Hz). This way you should be able to keep your synths stereo as long as your bass frequencies are mono.


Problem with setting proxy and sending header - selenium and java

Question: I am using selenium and java with my automation tests. I am forced to send authorization token in my tests so I used BrowserMobProxy library. Here is my setUp in @BeforeClass:
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.addHeader("Authorization",tokenIDdev2);
proxy.start();

Next, this that I need to do is opening my browser by special proxy address, I've found this kind of setting up proxy address:
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
DesiredCapabilities capabilities = new  DesiredCapabilities();
seleniumProxy.setHttpProxy(PROXY_ADDRESS);
seleniumProxy.setSslProxy(PROXY_ADDRESS);
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);

// Setting up Proxy for chrome
ChromeOptions opts = new ChromeOptions();
opts.merge(capabilities);
driver = new ChromeDriver(opts);

Problem is that when I am connecting by proxy which was set up in the method above, requests are not sending with the header that I specified in the first part.
Do you have any ideas that I am doing wrong, or maybe there is another way to handle this situation?
Thanks!
Answer: For some reason, I think I never managed to make .addHeader(); method work either.
But I did it in another way:
    String authorizationKey = "Authorization";
    browserMobProxyServer.addRequestFilter((request, content, messageInfo)->{
        if (request.headers().contains(authorizationKey)) {
            request.headers().remove(authorizationKey);
        }
        request.headers().add(authorizationKey, tokenIDdev2);
        return null;
    });

You may remove the if part if you are 100% sure that the "Authorization" header is never present.


Show that $\lim_{j\to\infty}\int_{\mathbb{R}^n}f_jd\mathcal{L}^n=\int_{\mathbb{R}^n}f\mathcal{L}^n$

Question: Let $g_j\le f_j\le h_j$ be three sequences of Lebesgue-integrable functions with $g_j\to g, f_j\to f, h_j\to h$ such that $g,h\in L^1(\mathbb{R}^n)$ and $\lim_{j\to\infty}\int_{\mathbb{R}^n}h_jd\mathcal{L}^n=\int_{\mathbb{R}^n}hd\mathcal{L}^n,\;\lim_{j\to\infty}\int_{\mathbb{R}^n}g_jd\mathcal{L}^n=\int_{\mathbb{R}^n}gd\mathcal{L}^n $.

Show that $f\in L^1(\mathbb{R}^n)$ and $\lim_{j\to\infty}\int_{\mathbb{R}^n}f_jd\mathcal{L}^n=\int_{\mathbb{R}^n}fd\mathcal{L}^n$.

My work so far: $f$ is integrable by the definition of the Lebesgue integral since both the negative (which I will denote by $f_{\_}$) and positive part of $f$ (which I will denote by $f_{+}$) are bounded by $g_{\_}$ and $h_{+}$.
My problem is the second part: I want to obtain something like $f_j\ge h_j+\epsilon$ and $f_j\le g_j-\delta$ for some $\epsilon,\delta> 0$ in order to be able to use the fact that we can switch integral and limit for $g$ and $h$. I have already tried to make the convergence uniform by using Egorov locally and then gluing the result together but I don't know how to continue from here.
Comment: This has appeared here: https://math.stackexchange.com/questions/1163497/sandwich-lemma-for-functions-show-that-the-integrals-converge?rq=1
Answer: I don't think you should have uniform convergence. Here is my idea:
Let $f_{n-}$ denote the negative part of $f_n$ for every $n$. $f_{n-}$ is always a positive function. Thus, by Fatou's Lemma $$\int_{\mathbb{R}^n}f_-\;d\mathcal{L}^n\leq\liminf_{n\to\infty}\int_{\mathbb{R}^n}f_{n-}\;d\mathcal{L}^n\leq\limsup_{n\to\infty}\int_{\mathbb{R}^n}f_{n-}\;d\mathcal{L}^n\leq\int_{\mathbb{R}^n}f_-\;d\mathcal{L}^n.$$ The same follows analogously for $f_+$. The proof follows from the definition of the Lebesgue Integral.
Comment: Thanks but that last inequality is actually not true..
Comment: Oh yeah, you're right. My apologies.


Complex mean value theorem

Question: Complex mean value theorem: Let $g$ be a holomorphic function defined on an open convex subset $D_{g}$ of $ℂ$. Let $v$ and $u$ be two distinct points in $D_{g}$. Then there exist $z₁,z₂∈(u,v)$ such that
$Re(g′(z₁))=Re(((g(u)-g(v))/(u-v)))$,
$Im(g′(z₂))=Im(((g(u)-g(v))/(u-v)))$, i.e.,
$g(u)=g(v)+(u-v)(Re(g′(z₁))+iIm(g′(z₂)))$.
In fact, we have $z₁=v+t₁(u-v),t₁∈(0,1)$ and $z₂=v+t₂(u-v),t₂∈(0,1)$ from the proof of this Theorem.
My question is about the uniqueness of $t₁,t₂∈(0,1)$ . The proof of the result indicate only their existence.
Answer: Let's consider $g(z) := z$ for $z \in \mathbb{C}$. We are looking for $z_1,z_2 \in (u,v)$ such that
$$\begin{align*} \text{Re} \, g'(z_1)=1 \stackrel{!}{=} \text{Re} \left(\frac{g(u)-g(v)}{u-v}\right) = 1 \tag{1}\\
\text{Im} \, g'(z_2)=0 \stackrel{!}{=}  \text{Im} \left(\frac{g(u)-g(v)}{u-v}\right) = 0 \tag{2}\end{align*} $$
This shows that all $z_1, z_2 \in (u,v)$ fulfill the given equations.
Comment: Thank you. But I am asking on the unicity of $t₁,t₂∈(0,1)$. No matter with $z₁,z₂∈(v,u)$.
Comment: But you defined $t_1$ by $z_1=v + t_1 \cdot (u-v)$. Since the equality (1) holds for all $z_1 \in (u,v)$ you can choose $t_1 \in (0,1)$ arbritary. Same for $t_2$.
Comment: Yes. thank you very much.

Complex mean value theorem


How to build Docker image from Bitbucket Pipeline with private repo dependency

Question: I'm trying to deploy a Docker image to AWS ECR using Bitbucket Pipeline. In the requirements.txt file, I have a Python package that originates from a private Bitbucket repo within my project.
Unfortunately, my Bitbucket pipeline builds keep failing. I think I'm missing some essential steps in authentication or pip install but I can't seem to find the correct documentation for this use case.
Following this Bitbucket community post, I generated a SSH key in my pipeline project and added it to Access Keys in the package repo. Then I followed this post and structured my files as such:

Dockerfile

# syntax = docker/dockerfile:1.2
FROM python:3.9-slim
WORKDIR /src
# Install git to download private repo
RUN apt-get update && apt-get install -y git
# Add Bitbucket SSH key to install private repo
ARG SSH_PRIVATE_KEY
RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~.ssh/id_rsa
RUN chmod 600  ~/.ssh/id_rsa
RUN touch ~/.ssh/known_hosts
RUN ssh-keyscan bitbucket.org >> ~/.ssh/known_hosts
RUN eval $(ssh-agent -s)
RUN ssh-add ~/.ssh/id_rsa
# Install Python dependencies
RUN pip install --upgrade pip setuptools
COPY requirements.txt requirements.txt
# requirements.txt also includes private repo package
RUN pip install --no-cache-dir -r requirements.txt
# Copy code into `src` folder
COPY src/ /src
# Set up environment variables & secrets
RUN --mount=type=secret,id=keys cat /run/secrets/keys \
  && python -m configs.parser
ENTRYPOINT ["python", "main.py"]

bitbucket-pipelines.yml

image: atlassian/default-image:2

pipelines:
  branches:
    master:
      - step:
          name: Build and AWS Setup
          services:
            - docker
          script:
            # Export repo variables to .env file
            - export ENV_PATH=src/configs/.env
            - echo AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID >> $ENV_PATH
            - echo AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY >> $ENV_PATH
            - export SSH_PRIVATE_KEY=`cat /opt/atlassian/pipelines/agent/data/id_rsa`
            - export TIMESTAMP="$(date +%Y%m%d%H%M%S)"
            # Build docker image with secrets mounted
            - export DOCKER_BUILDKIT=1
            - docker build --build-arg SSH_PRIVATE_KEY --secret id=keys,src=$ENV_PATH -t $AWS_ECR_REPO .
            # use pipe to push the image to AWS ECR
            - pipe: atlassian/aws-ecr-push-image:1.3.0
              variables:
                AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
                AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
                AWS_DEFAULT_REGION: us-east-1
                IMAGE_NAME: $AWS_ECR_REPO
                TAGS: "latest $TIMESTAMP $BITBUCKET_BUILD_NUMBER"

My pipeline run fails at Step 5 of docker build with the error: executor failed running [/bin/sh -c echo "${SSH_PRIVATE_KEY}" > ~.ssh/id_rsa]: exit code: 2
Any help with this would be greatly appreciated!
Comment: Related https://stackoverflow.com/a/66301568/11715259 and https://stackoverflow.com/q/69798493/11715259
Answer: You should NOT pass private RSA keys as arguments nor dump them in files inside the docker image you are building. This way that private key would end exposed in your image layers.
You should mount the build agent ssh key with
RUN --mount=type=ssh \
  pip install -r requirements.txt

docker build --ssh default=$BITBUCKET_SSH_KEY_FILE .

(See https://support.atlassian.com/bitbucket-cloud/docs/run-docker-commands-in-bitbucket-pipelines/#Docker-BuildKit-restrictions)
As for the known_hosts content: to protect the image builder from being spoofed I'd recommend NOT accepting whatever key can be scanned in build time.
Either vendor (and keep under the VCS) the necessary ssh sever fingerprints in the docker building context or mount (not necessarily as a secret) an externally managed known_hosts. E.g. the one managed by Bitbucket Pipelines will already feature a maintained bitbucket.org ssh fingerprint: https://support.atlassian.com/bitbucket-cloud/docs/set-up-pipelines-ssh-keys-on-linux/#Update-the-known-hosts
RUN \
  --mount=type=ssh \
  --mount=type=bind,target=~/.ssh/known_hosts,source=known_hosts \
  pip install -r requirements.txt

cp ~/.ssh/known_hosts .
docker build --ssh default=$BITBUCKET_SSH_KEY_FILE .

Comment: Thank you for the detailed explanation! I've updated my Dockerfile and bitbucket-pipelines.yml accordingly. I've also changed my `requirements.txt` file to this:
` @ git+ssh://firstname.lastname@example.com/.git`

I'm still getting an error within the docker build command:

`Host key verification failed. Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.`

Is it due to the known_hosts content? Do I need to add something to the private package's repo settings?
Comment: I've already added the public SSH key from the building repo to the package repo under Repository Settings > Access Keys
Comment: That is due to `known_hosts`. Did you use the `--mount=type=bind,target=~/.ssh/known_hosts,source=known_hosts` in the Dockerfile and the `cp ~/.ssh/known_hosts .` in the building script? I thought that should be enough. Maybe make sure the file is not excluded from the building context by a `.dockerignore` rule.
Comment: Oh this was a super useful tip! Made the mistake of not updating my Dockerfile command to `ssh-keyscan bitbucket.org`, left it as github.com initially. It works perfectly now, thank you!!


How to setState from within a callback?

Question: I am trying to use Twilio's Chat Client SDK, which is under-documented, with React Hooks/FC. And am having an issue finding the correct way to update my state from the context of the on callback.
http://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/docs/
If I register it on every render, then naturally I get a memory leak and duplicate responses handling.
const MessageList = ({channel}) => {
  const [messageGroups, setMessageGroups] = React.useState([]);

  ...

    channel.on("messageAdded", (message) => {
    if(messageGroups.length == 0) {
      setMessageGroups([[message]])
      return
    }

    let messageChucks = [...messageGroups]

    ...

    setMessageGroups(messageChucks)
  })

If I register it in a useEffect than the messageGroups value is statically defined to the value it had when the useEffect was last triggered meaning that messageGroups get resets to empty. I could then update my useEffect to reregister on MessageGroups change, but that would just be a slower memory leak.
const MessageList = ({channel}) => {
  const [messageGroups, setMessageGroups] = React.useState([]);

  ...

  React.useEffect(() => {
    channel.on("messageAdded", (message) => {
      if(messageGroups.length == 0) {
        setMessageGroups([[message]])
        return
      }

      let messageChucks = [...messageGroups]

      ...

      setMessageGroups(messageChucks)
    })
  }, [channel])

Is there a way to have my callback as registered use the latest state, or another way to work around this?
Comment: subscription to the events should happen only once. but here, the `useEffect` is getting called every time the `channel` is updated. can you try replacing `[channel]` with `[]` ?
Comment: It needs to be reregistered anytime the channel is changed, which right now is zero. The issue is after it's registered the context of messageGroups doesn't update on rerenders after even though its been populated with history
Answer: Okay, so the answer is to pass the function into the setState which gives you the previous state, this then allows you to update the state and return it.
  const handleMessageAdded = (message) => {
    setMessageGroups(prevMessageGroups => {
      if(prevMessageGroups.length == 0) {
        return [[message]]
      }

      let messageChucks = [...prevMessageGroups]

      ...

      return messageChucks
    })
  }

  React.useEffect(() => {
    channel.on("messageAdded", handleMessageAdded)
  }, [channel])

How to setState from within a callback?


Definition of the derivative: difference between two limiting processes

Question: Say I have $f(x) = 2x^2 + x - 1$.
Is there a difference between using the following two limit processes?

$\lim_{x\to c} \frac{f(x) - f(c)}{x-c}$

$\lim_{\Delta x \to 0} \frac{f(x+\Delta x) - f(x)}{\Delta x}$

I've applied both processes to get the derivative in terms of $c$ for #1 and in terms of $x$ for #2.
It seems like both work fine. Are there any pros or cons for either? I've tried to look up information online on this but had no luck.
Thank you.
Comment: They're both equivalent ways of expressing the concept of a derivative. One just might be easier to use than the other in different cases or scenarios.
Answer: Those two definitions for the derviative of a function $f$ are equivalent, which I am going to prove right now:
$$\frac{d f}{d x}(c) = \lim_{x\to c}\frac{f(x) - f(c)}{x - c}$$
By substitution of variable $x = x' + c \implies x' = x - c$ we have that:
$$\frac{d f}{d x}(c) = \lim_{x\to c}\frac{f(x) - f(c)}{x - c} = \lim_{x'\to 0}\frac{f(c + x') - f(c)}{x'} $$
By further changing the variable $x'$ as $x' \rightarrow \Delta x $ we get
$$\frac{d f}{d x}(c) = \lim_{x\to c}\frac{f(x) - f(c)}{x - c} = \lim_{\Delta x\to 0}\frac{f(c + \Delta x) - f(c)}{\Delta x} $$
Because of their equivalency, whenever you try to find the derivative of one function with the one limit process or the other, the result is going to be the same.
As far as which is better, there is no answer to that. Every time you use the representation that seems to lead you to the solution more easily and its straightforward.
Answer: There is no difference, they are equivalent. The second method is most commonly used because with it the point in which the function is differentiated is not used in the limit opperation.
Let $f$ be a real function differentiable at a point $x$. We can write:
$$f^\prime(x) = lim_{\Delta x \to 0} \frac{f(x+\Delta x) - f(\mathbf{x})}{\Delta x}$$
Whereas using the first limit, we would have to write $x$ as the limit point:
$$f^\prime(x) = lim_{u \to x} \frac{f(u) - f(x)}{u - x}$$
In the same way, this method is usually more helpful when working with multiple variables and partial derivatives:
$$\frac{\partial f}{\partial x_i}= lim_{\Delta x \to 0} \frac{f(x+\Delta x . e_i) - f(\mathbf{x})}{\Delta x}$$


Multiple instances of Openvpn with different server IP numbers

Question: Is it possible to assign different ip numbers to different openvpn interfaces on server (Like in PPTPD):
Server PC i-face-s:
tun0: inet 10.8.1.1 peer 10.8.2.1
tun1: inet 10.8.1.2 peer 10.8.2.2

Client 1 PC i-face-s:
tun_client1 inet 10.8.2.1 peer 10.8.1.1

Client 2 PC i-face-s:
tun_client2 inet 10.8.2.2 peer 10.8.1.2

I tried this:
/etc/openvpn/server.conf:
dev tun
topology p2p
server 10.8.0.0 255.255.255.0
route 10.8.1.0 255.255.255.0
route 10.8.2.0 255.255.255.0
ifconfig-pool-persist ipp.txt 0
client-config-dir ccd

/etc/openvpn/ccd/client1
ifconfig-push 10.8.2.1 10.8.1.1

And on client all works:
19: tun_client1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1300 qdisc fq_codel state UNKNOWN group default qlen 100
    link/none
    inet 10.8.2.1 peer 10.8.1.1/32 scope global tun_client1
       valid_lft forever preferred_lft forever

But on server ip addresses not valid and ping to 10.8.2.1 dont works:
1150: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 100
    link/[65534]
    inet 10.8.0.1 peer 10.8.0.2/32 scope global tun0

Comment: I guess the only solution would be to run multiple OpenVPN instances on the server. But maybe you should explain what problem you are trying to solve.
Comment: the problem is in that there are no ping from server to 10.8.2.1, and can't ping 10.8.1.1 from client, I guess the reason is uncorrect ip's on servers tun0 interface, it should corespond to client ip's.
Comment: Yes, but what's the reason you want multiple tun interfaces on the server? OpenVPN is not PPTP.
Comment: I want to allow 2 connections from one client to one server in general, if use subnet topology , there is issue when 2 routes with same network exists via different i-face-s
Answer: Solved using 2 instances of openvpn and subnet topology.
It was enough copy server.conf to server1.conf, change port and server's ip range and also rename some files which clashes with server.conf (logs etc). When service restarts it automatically creates instance of openvpn for each config.


The Origins of $Re \lbrace x \rbrace$

Question: I am just starting to take a differentential equations course. We do not use the notation $Re \lbrace x \rbrace$ to describe the real part of a complex number, but I have come accross it in other reading. I am a mathematics major and I was wondering what the proper notation and meaning of $Re \lbrace x \rbrace$ is.
I see it written as $Re(x)$, or $Re \lbrace x \rbrace$. I am wondering if it is a set operation, or a function, or what it is?  If it is a set operation, could we write $Re \lbrace \mathbb{C} \rbrace=\mathbb{R}$? Also, is it common to see such a thing in mathematics courses, or is it a "physics thing"?
Also, could we use $Re \lbrace x \rbrace$ for any $x$ in a field which contains $\mathbb{R}$?
Comment: Sure you can think of it as projection onto the first coordinate thinking of $\Bbb C$ as $\Bbb R^2$.
Comment: "the real part of an imaginary number": you'd better say a "complex number", as imaginary numbers are understood as those without a real part !
Comment: $\text{Re}(x)$, sometimes denoted $\Re x$ is indeed a function from $\mathbb C$ to $\mathbb R$, sister of $\text{Im}(x)=\Im x$. It might make sense to generalize it to other fields, provided a "real part", as opposed to "imaginary" or "non-real", has a meaning there.
Comment: @YvesDaoust edit has been made.
Comment: It also makes sense to use it in the frame of quaternions, a generalization of the complex numbers, in competition with a "Scalar" function. http://en.wikipedia.org/wiki/Quaternion#Scalar_and_vector_parts
Answer: I've never seen $\mathrm{Re}\{x\}$ but $\mathrm{Re}(x)$ or $\frak{Re}$$(x)$. It's a function but you can see it as a set operation if there is no ambiguity, though I don't remember having used this for sets.

The Origins of $Re \lbrace x \rbrace$


OpenVPN enable compression lz4-v2 instead of comp-lzo

Question: I want to enable OpenVPN compression lz4-v2
in server configuration file(server.ovpn) I have:
;comp-lzo
compress lz4-v2
push "compress lz4-v2"

in client.ovpn,instead of
comp-lzo i put push "compress lz4-v2"
is that the correct configuration?
thanks
Comment: seems that for v2.4+ clients no compression specific config required at the client end as long the above config is 'pushable'
but on client side I got
WARNING: 'comp-lzo' is present in remote config but missing in local config, remote='comp-lzo'

In server config I have one line commented:
# comp-lzo
Answer: Put
compress lz4-v2

in client.conf as well.
Answer: Allowing compression in OpenVPN is discouraged for common usage. Compression has been used in the past to break encryption. Allowing compression allows attacks that break encryption. See WARNING: Compression for receiving enabled. Avoid using "--allow-compression yes".
Please note that if you add allow-compression yes to your client config file, you will instead get a warning message that it is strongly discouraged to use the compression in this context.
You can resolve both problems (Used Inconsistently and Missing in local config) for a particular compress command if present as per the following example.
WARNING:'link-mtu' is used inconsistently, local='link-mtu1633',remote='link-mtu 1634'
WARNING:'comp-lzo' is present in remote config but missing in local config,remote='comp-lzo'

First, make sure the client-side .ovpn config file enables selective compression by having at least one --comp-lzo directive, such as --comp-lzo no. This will turn off compression by default, but allows a future directive push from the server to dynamically change the on/off/adaptive setting.
In other word, just add and save the following line in your client.conf file .ovpn:
comp-lzo no

Comment: In case it helps someone, I came here because I was unable to connect to ProtonVPN via OpenVPN. I was getting: "OPTIONS ERROR: server pushed compression settings that are not allowed and will result in a non-working connection. See also allow-compression in the manual." After adding `comp-lzo no`, it worked.


Installing PHP 5.4 on Samsung Chromebook 3 which runs chroot Ubuntu Crouton

Question: I am trying to install PHP 5.4 on a Samsung chromebook 3 running crouton.c (Crouton link:  https://github.com/dnschneid/crouton)
I am following the instructions for the upgrade from http://www.barryodonovan.com/index.php/2012/05/22/ubuntu-12-04-precise-pangolin-and-php-5-4-again
But face some dependency issues when I try to install PHP after adding the repository in the above link.
Pasted below is the message I get when I run the sudo apt-get dist-upgrade. I have also removed PHP completely from my system and try to install it after adding the ondrej/php5 repository but get the same message as the one below.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 php5 : Depends: libapache2-mod-php5 (>= 5.4.14-1~precise+1) but it is not going to be installed or
                 libapache2-mod-php5filter (>= 5.4.14-1~precise+1) but it is not going to be installed or
                 php5-cgi (>= 5.4.14-1~precise+1) but it is not going to be installed or
                 php5-fpm (>= 5.4.14-1~precise+1) but it is not going to be installed
        Depends: php5-common (>= 5.4.14-1~precise+1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I prefer not installing from source. Could some please provide some suggestions to fix this issue or any alternate methods?
Thank you.
Answer: Did you forget to run:
apt-get update

and
apt-get install -f


Interpreting a set of predicate formulas as a model

Question: Consider the set $\phi$ consisting of the following formulas.
$$ \exists x \exists y \exists z \neg (x = y  ~ \lor x = z ~  \lor y = z) $$
$$ \forall x \exists y ~ gimble(x, y)  ~ \land \exists x ~ \neg gimble(x, x)  $$
$$ \forall x \forall y \forall z ~ (gimble(x, z) ~ \land ~gimble(y, z) \implies x =y)   $$
1) How can I describe a model for $\phi?$
Should I use a table? How would I do that?
2) How can I describe an interpretation that is not a model for $\phi?$
3) Is the set $\phi$: (i) valid, (ii) satisfiable but not valid or (iii) unsatisfiable?
I think that $\phi$ is probably satisfiable but not valid (ii) because it holds under some interpretation e.g. the interpretation for 1) but it is not valid because it does not holds under every interpretation i.e the interpretation for 2)
Answer: For a model:
The first sentence says that there are at least three different objects
The second sentence says that everything stands in a 'gimble' relation to something, and there is something not in a 'gimble' relation to itself
the third sentence says that you cannot have two different objects that stand in a 'gimble' relation to the same object.
1) OK, so here is a possible model: take exactly three objects, $a,b$ and $c$, and with the following 'gimble' pairs: $(a,b),(b,c),(c,a)$
If you want something more meaningful: We have 3 persons: Alice, Bob, and Carroll. $gimble(x,y)$ means '$x$ likes $y$. Say that  Alice likes Bob, Bob likes Carroll, and Carroll likes Alice, and otherwise there are no more like relations. Note how we indeed have at least three different objects, how everyone likes someone, how there is someone who does not like themselves, and how there are not two different people liking the same person.
2) An interpretation that is not a model: say there is only 1 object $a$ and say that $a$ dos not stand in the 'gimble' relation to itself.
More meaningful: We just have Alice, and Alice does not like herself.
3) Yes, you are right: it is satisfiable (because there is a model) but not valid (because not every interpretation is a model)


Is it appropriate to use SE in place of SD in rnorm()?

Question: I have  wood density data for a number of tree species given a tree's state of decay.  I am presented with mean density and standard errors (SE).  I am NOT provided with sample sizes.
For example, a decay class 1 fir tree has a mean density of 0.305 with a standard error of 0.024.
I am using R.  I would like to generate a density value for a given decay class 1 fir tree similarly to using rnorm(n, mean, standard deviation) when pulling from a normal distribution.
In this case, is it appropriate to substitute the SE for SD, such as density<-rnorm(1, mean=0.305, sd=0.024)?
Comment: Hi @mafbarth! If you use the standard error for generating the random values, you are generating new **mean** values and not original measurements. Without knowing the sample size, it is impossible to derive the standard deviation of the measurements. So: wether it is appropriate to use the SE instead of the SD is a matter of your question.
Answer: No! They're not really interchangeable like that. Standard deviation is a measure of central tendency or or dispersion: i.e., how close your values are to one another. A high standard deviation indicates that the values are pretty spread out, while a low standard deviation indicates that they're all fairly close to one another (and the mean). The standard error (which is the shortened form of standard error of the mean), however, represents the (im)precision in your estimate of the mean.
If you draw from a distribution with the same mean and standard deviation, you will effectively simulate a dataset similar to the original (assuming they're both normally distributed, etc). However, if you draw from a distribution with the same mean and standard error, you'll be drawing other plausible estimates for the mean of that distribution.
If you knew the sample size, you can easily recover the standard deviation from the standard error, since
$$\textrm{SE} = \frac{s}{\sqrt{n}}$$
but it sounds like you don't have that information available. Can you estimate the sample size from the text (e.g., "we collected 1-2 dozen samples of each type") or the nature of the experiment? The square-root buys you some flexibility here--if you're off by a factor of 10 (e.g., you think they used 100 samples, but they only used 10), you'll only be off by about three-fold. If this is from an academic paper or something, you might try emailing them. People are often surprisingly helpful about things like this, especially if the paper is fairly recent.


How does a model relate to another model via Foreignkey?

Question: So I've been browing around the web a  bit and I can't quite find what I'm looking for. First off Say I have
class Contact(models.Model):
    nickname = models.CharField(max_length=25)
    number = models.CharField(max_length=25)
    note = models.TextField()

class Telephone(models.Model):
    contact = models.ForeignKey('Contact')

So how would i go about saving a nickname/number/not and then be able to find all of these based on some label that I could give them all?
Say I wanted to have it be that when I used Telephone.objects.filter(contact=jill) all of the information based on the instance of jill would be provided? what if i wanted to be able to edit jill and give her more than one number via different saves is this possible? (but jill isn't her nickname its the label that I put on there.) Sort of a bad example but say I just want to find all of the information in Contact via some named instance that is filterable via Telephone is that possible? or is Foreignkey not what I'm looking for?
Comment: Have you worked through the [Django Tutorial](https://docs.djangoproject.com/en/dev/intro/tutorial01/)? It is rather well done and will give you a good sense for how ForeignKeys (and other things) work.
Comment: I have'ish' I mean I did initially but back when I did it I didn't have any immeadite need to use foriegn keys so I more or less just browsed those sections. I'll have to go back and re read them.
Comment: yeah just looked it over and it didn't say much. However, I'm beginning to think that Foreignkeys aren't what I need to use but that doesn't really solve my problems as it just gives me a new one
Answer: Telephone.objects.filter(contact__nickname='jill')

See the documentation on making queries
 what if i wanted to be able to edit jill and give her more than one number via
 different saves is this possible?

Yes it is. To give one thing in contact objects multiple telephone numbers, there are two ways - a One-To-One relationship via a ForeignKey, or a many-to-many relationship. I suggest you read through the models topic in the documentation.
Edit
You can give Jill more than one phone number on each save in the model layout that you have.
Suppose Jill has a new line, so you want to add a new phone number. The way you have it structured now, you would first have to go and find 'Jill' in Contacts, and then give her a new phone number:
jill = Contact.objects.get(nickname='jill') # assuming you only have one jill
new_num = Telephone.objects.create(contact=jill,number=5551212)

Now if you want all of Jill's contacts, you would do:
call_jill = Telephone.objects.filter(contact=jill) # if you already pulled jill
call_jill = Telephone.objects.filter(contact__nickname='jill')

The other way to do it would be with a ManyToMany:
   class Telephone(models.Model):
      number = models.PhoneNumberField()

   class Contact(models.Model):
      # your normal fields
      phones = models.ManyToMany(Telephone)

Now, you can do:
   jills_phones = Contact.objects.get(nickname='jill').phones.all()

To add a new phone:
   jill = Contact.objects.get(nickname='jill')
   jill.phones.add(Telephone.objects.create(number=5551212))
   jill.save()

You can also do the reverse, find out whose phone this is:
   phone = Telephone.objects.get(number=5551212)
   whose_is_it = phone.contact_set.all()

So what's the difference?
They both sound similar, but the differences are subtle. A simple analogy is easy. One Manufacturer can have many Cars, but one Car can only have one Manufacturer - this is a one-to-one between Car and Manufacturer.
A Pizza can have many toppings, and each topping can be on multiple pizzas. In this case, Pizza has ManyToMany relationship with Toppings.
You might be thinking that I can do that with a ForeignKey. You are right, but consider this scenario:
Suppose you start off and you have no toppings. So you create olives as a topping and then add it to a pizza. Great.
Now you want the same pizza to have green peppers as well. Now you are stuck, because one pizza can only have one topping (due to ForeignKey).
So you end up creating a third model, which holds a reference to a pizza and a topping. So instead of putting toppings on pizzas, you put them on this other model:
class Pizza(models.Model):
   topping = models.ForeignKey('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

class AssembledPizza(models.Model):
   topping = models.ForeignKey('Topping')
   pizza = models.ForeignKey('Pizza')

However, if you did it the correct way with a ManyToMany, you have:
class Pizza(models.Model):
   toppings = models.ManyToMany('Topping')

class Topping(models.Model):
   name = models.CharField(max_length=100)

Then you would do:
Here I am assuming you are a new restaurant and have no toppings. See the documentation for create for more information.
veggie = Pizza()
veggie.toppings.add(Topping.objects.create(name='Olives'))
veggie.toppings.add(Topping.objects.create(name='Peppers'))
veggie.save()

I hope this clarifies it a bit.
Comment: Okay but how I can I get all of the numbers from jill?
Comment: That's what the first line `Telephone.objects.filter(contact__nickname='jill')` does.
Comment: so I assume that it gets all of the information for 'jill'? so how could I filter that off so that it's just numbers and no notes and no dict keys saying that this is jill? assuming its a dictionary?
Comment: To get information on 'jill', which is in the 'Contact' model, you'd have to first filter on that `jill = Contact.objects.filter(nickname='jill')`. Then you have to get the telephones for that model. See my updated answer.
Comment: I guess i have one quesiton left. Why use a manytomany field that links up with phones what you could just include number = models.PhoneNumberField() in Contact and then call jills_phones = Contact.objects.get(nickname='jill').number.all()? I suppose there are other thing I'm not considering but in this aspect it seems redundant
Comment: `all()` only works on managers, not fields. You need to go through the tutorial and documentation links I provided.


How to merge different datasets with datetime index?

Question: I have two datasets (Lots and Measurements) that both have datetime indexes but different lengths and columns. The first dataset (Lots) is structured as follows:

Datetime Index
Lot Group
Lot No
Booking Level

2013-08-03 10:00:00
1
261291.0
PROB1H

2013-08-03 12:00:00
1
261228.0
PROB1H

The other one (Measurements) is structured as follows:

Datetime Index
MID
Passed?
Measurement1
Measurement2
Measurement3

2013-08-28 10:00:00
12345
True
46.908
3.89
29.056

2013-08-03 12:00:00
78262
True
89.457
6.88
34.918

What I am trying to do is merge the two dataframes on the datetime index and get all the columns in both dataframes and if there is a match on the datetime index it would add the MID, Passed? and measurement columns to the Lots dataframeand would also keep the duplicates if there are any and would also keep missing values as NaNs for example:
Let's say the datetime 2013-08-28 10:00:00 is not present in the Lots dataframe but is present in the Measurement dataframe so that would produce:

Datetime Index
Lot Group
Lot No
Booking Level
MID
Passed?
Measurement1
Measurement2
Measurement3

2013-08-28 10:00:00
NaN
NaN
NaN
12345
True
46.908
3.89
29.056

and if there is a match for example in the datetime  2013-08-03 12:00:00 it would produce:

Datetime Index
Lot Group
Lot No
Booking Level
MID
Passed?
Measurement1
Measurement2
Measurement3

2013-08-03 12:00:00
1
261228.0
PROB1H
78262
True
89.457
6.88
34.918

The Lots dataframe's datetime index has only unique datetime values but the Measurement dataframe there are duplicate entries so if there is a match with a duplicate entry I would like to get duplicate rows for example:
Let's say the datetime 2021-04-15 22:00:00 is present in both dataframes but is found multiple times in the Measurement dataframe so it would produce the following:

Datetime Index
Lot Group
Lot No
Booking Level
MID
Passed?
Measurement1
Measurement2
Measurement3

2021-04-15 22:00:00
2
311000.0
PROB2H
34903
True
39
67
50

2021-04-15 22:00:00
2
311000.0
PROB2H
34904
True
88
40.90
54.38

I have tried different merging but couldn't get the result I wanted I tried:
test = lots.merge(measurement, how = "right",left_index=True, right_index=True)
test2 = lots.merge(measurement, how = "outer",left_index=True, right_index=True)

How would you suggest I go about this, thanks in advance.
Answer: You can use join as well as merge:
# Dataset Lots
>>> dfL
                     Lot Group    Lot No Booking Level
Datetime Index
2013-08-03 10:00:00          1  261291.0        PROB1H
2013-08-03 12:00:00          1  261228.0        PROB1H
2021-04-15 22:00:00          2  311000.0        PROB2H

# Dataset Measurements
>>> dfM
                       MID  Passed?  Measurement1  Measurement2  Measurement3
Datetime Index
2013-08-28 10:00:00  12345     True        46.908          3.89        29.056
2013-08-03 12:00:00  78262     True        89.457          6.88        34.918
2021-04-15 22:00:00  34903     True        39.000         67.00        50.000
2021-04-15 22:00:00  34904     True        88.000         40.90        54.380

# Join version
>>> dfL.join(dfM, how='outer')
                     Datetime Index  Lot Group Lot No Booking Level      MID Passed?  Measurement1  Measurement2  Measurement3
2013-08-03 10:00:00             1.0   261291.0               PROB1H      NaN     NaN           NaN           NaN           NaN
2013-08-03 12:00:00             1.0   261228.0               PROB1H  78262.0    True        89.457          6.88        34.918
2013-08-28 10:00:00             NaN        NaN                  NaN  12345.0    True        46.908          3.89        29.056
2021-04-15 22:00:00             2.0   311000.0               PROB2H  34903.0    True        39.000         67.00        50.000
2021-04-15 22:00:00             2.0   311000.0               PROB2H  34904.0    True        88.000         40.90        54.380

# Merge version
>>> dfL.merge(dfM, how='outer', left_index=True, right_index=True)
                     Datetime Index  Lot Group Lot No Booking Level      MID Passed?  Measurement1  Measurement2  Measurement3
2013-08-03 10:00:00             1.0   261291.0               PROB1H      NaN     NaN           NaN           NaN           NaN
2013-08-03 12:00:00             1.0   261228.0               PROB1H  78262.0    True        89.457          6.88        34.918
2013-08-28 10:00:00             NaN        NaN                  NaN  12345.0    True        46.908          3.89        29.056
2021-04-15 22:00:00             2.0   311000.0               PROB2H  34903.0    True        39.000         67.00        50.000
2021-04-15 22:00:00             2.0   311000.0               PROB2H  34904.0    True        88.000         40.90        54.380

Comment: @MohamedArebi. Can you check if the answer below is the expected outcome, please?
Comment: Yes it is 90% what I expected to output but what I also wanted was to ouput the date '2013-08-03 10:00:00' with all the data from the lots dataframe but NaNs for the other dataframe
Comment: @MohamedArebi. I updated my answer. This is what you expect?
Answer: Your merge attempts are close.
test2 = lots.merge(measurements, how='right', on='Datetime Index')

print(test2)

    Datetime Index  Lot Group    Lot No Booking Level    MID  Passed?  Measurement1  Measurement2  Measurement3
0 2013-08-28 10:00:00        NaN       NaN           NaN  12345     True        46.908          3.89        29.056
1 2013-08-03 12:00:00        1.0  261228.0        PROB1H  78262     True        89.457          6.88        34.918

This example still works if you omit on='Datetime Index', though it's probably better to keep it to show intent. From DataFrame.merge:

If on is None and not merging on indexes then [merge] defaults to the
intersection of the columns in both DataFrames.
Comment: I think '2013-08-03 10:00:00' should not appear in the final outcome?
Comment: But the Datetime Index is not a column it is an index present in both dataframes, would that work as well? Or the on can be an index level name?
Comment: @MohamedArebi apologies, I didn't read the fact that `Datetime Index` (as its name hints) is in fact a `DatetimeIndex` :) Based on your comment in the other answer, it seems that your second attempt, `lots.merge(measurement, how='outer', left_index=True, right_index=True)`, should do exactly what you want. Does that still not produce your expected result?


Google Maps Marker Selection

Question: greetings,
I am loading markers on a google maps dinamically with xml that comes from a php function
Also I use that XML to build a table with all the locations.
the question is how can I link each table entry to a marker so i can click on that location and it appears the marker centered on my map and open the info window?
Answer: When you create the marker object, give it an id:
var alatlng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
    position: alatlng,
    title:"Hello World!",
    icon: image
});

marker.setValues({type: "point", id: counter });
marker.setMap(map);

Then you can use addDomListener to add a listener to a click event on your table object (hyperlink etc)
google.maps.event.addDomListener(document.getElementById("result" + counter), 'click', function() {
    map.setCenter( latlngbounds.getCenter( ) );
});

The bounds of the map are set using:
var latlngbounds = new google.maps.LatLngBounds( );
latlngbounds.extend(alatlng);

Not 100% sure this is what you are after from your post, but it should piece together for you.

Google Maps Marker Selection