How can I have two nodes of different content types update to each other?

Question: I have two different content types(A & B), and I want to be able to have a field in content type A that is a select list of all the nodes from content type B, and then I want to have a field in content type B that is a select list of all the nodes from content type A.
Is there a way that I can have those two fields update each other?
Ex: in node 'Atest' from content type A in the select list field I select the 'Btest' node from content type B, and then if I edit 'Btest' in it's select list field I can see 'Atest' already selected. (showing that 'Atest' has it selected)
Is that possible? if so, what would be the beat way to go about setting that relationship up?
Comment: What do you mean by "update each other"? You want to change options on node edit page? Or you want to change content of actual nodes?
Comment: I want to change the actual content of the nodes. I want to have a node reference select list in each content type that when edited in a node of one type will update the selected nodes' node reference select list in the other content type
Answer: You can try Corresponding node references.
I used this to sync up Events and Venues on one of my sites, and whenever I switch a venue for an event it automatically changes the node reference on the other node, so I only have to change the node reference once, instead of twice. Keeps things tidy, works with multiple.
Comment: As a note [CER](https://www.drupal.org/project/cer) should be used since development has swapped over to there now.
Comment: Although I have yet to be able to get the CER module to with without errors


Drupal 8: Prevent webform from saving IP

Question: About the webform module: It always stores the IP with a submission unless it's set as confidential. Is there a way to not store the IP while leaving it as not confidential?
In webform/src/WebformSubmissionForm.php is the function save where it sets the remote_addr. Is there any way to hook this? I don't think it works with a custom webform handler...
Thanks! Looking forward for your answers!
Answer: You could override the save function of webform/src/WebformSubmissionForm.php, but as you specifically ask for a hook and because this is probably also the easiest solution you can remove the field value set by the form before the entity gets saved:
use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for webform submissions.
 */
function mymodule_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $webform_submission->remote_addr->value = '';
}

Answer: Try to follow this code..
use Drupal\Core\Form\FormStateInterface;

/*
* Implement hook_form_alter()
*/
function my_module_form_alter(&$form,$form_state, $form_id) {
    $form['actions']['submit']['#validate'][] = 'custom_form_validate';
}

function custom_form_validate($form, $form_state) {
  $ip = \Drupal::request()->getClientIp();
  $form_state->setValue('remote_addr', $ip);
}

Comment: I tried it with `$form_state->setValue('remote_addr', '');` since I don't want the IP to be stored but this doesn't work. The IP gets stored anyway. However I have to mention that my custom validate function is called via AJAX (see this [post](https://drupal.stackexchange.com/questions/232909/how-do-i-submit-a-form-via-ajax)). I don't know if it doesn't work because of this and I haven't tested it any other way.


Get pandas df column value distribution

Question: I am trying to create a new column in a pandas dataframe from the values of another column. What I intend to obtain is from the column of goals per team, to distribute the goal count in an array of 10 positions. Where the 0 position of the array shows how many have scored between 0 and 10 goals and so on until the last position (9) that counts how many between 90 and 100.
For example:
From a dataframe like this one:
| player_id | team    | goals  |
|-----------|---------|--------|
| ply_1     | Arsenal | 100    |
| ply_2     | Arsenal | 2      |
| ply_3     | Chelsea | 21     |
| ply_4     | Chelsea | 13     |
| ply_5     | Arsenal | 50     |

Get one like the following:
| player_id | team    | goals | goals_distribution_by_team|
|-----------|---------|-------|---------------------------|
| ply_1     | Arsenal | 100   | [1,0,0,0,0,1,0,0,0,1]     |
| ply_2     | Arsenal | 2     | [1,0,0,0,0,1,0,0,0,1]     |
| ply_3     | Chelsea | 21    | [0,1,1,0,0,0,0,0,0,0]     |
| ply_4     | Chelsea | 13    | [0,1,1,0,0,0,0,0,0,0]     |
| ply_5     | Arsenal | 50    | [1,0,0,0,0,1,0,0,0,1]     |

In this case we can see that for Arsenal team the number of goals are distributed for 0-10 (ply_2), 50-60 (ply_5) and 90-100 (ply_1).
So far I have achieved this by doing a for that goes through the goals column and checks if the number of goals is in which range.

for goal in goals:
 if 0 < goal <=10:
    count()
 if 10 < goal <=20:
    count()
....
 if 90 < goal <=100:
    count()

Is there more pythonic way to achive this?
Thanks!
Answer: One way is to group the dataframe by team, then apply a function to get those ones and zeroes as lists:
out = (df.groupby('team')['goals']
        .apply(lambda x: [int((i==x//10).any()) for i in range(11)])
         )

team
Arsenal    [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
Chelsea    [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Name: goals, dtype: object

Once you have it, you can merge it back to the original dataframe
df.reset_index().merge(out.rename('goals_distribution_by_team'), on='team')

  player_id     team  goals         goals_distribution_by_team
0     ply_1  Arsenal    100  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
1     ply_2  Arsenal      2  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
2     ply_5  Arsenal     50  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
3     ply_3  Chelsea     21  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
4     ply_4  Chelsea     13  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]

Comment: Many thanks @ThePyGuy :) the thing is that if there are 2 goals that are under 0-10 range, instead of one should appear the value of 2
Comment: Hi again, I've found a bug in this solution... this lists has 11 positions and they need to be 10. Also I needed to add .sum() function instead of any() in order to make it sum all the goals under same "bucket".
Comment: the main problem is that if I do the range(0,10), for 100 goals there is not going to be counted.
Answer: Use get_dummies with divide column by integers division by 10, then add 0 by missing range values in DataFrame.reindex, redistibute 1 per groups by GroupBy.transform and last convert to lists:
df1 = pd.get_dummies((df['goals'] // 10))
max1 = range(df1.columns.max() + 1)

df['goals_distribution_by_team'] = (df1.reindex(max1, axis=1, fill_value=0)
                                       .groupby(df['team']).transform('max')
                                       .to_numpy().tolist())
print (df)
  player_id     team  goals         goals_distribution_by_team
0     ply_1  Arsenal    100  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
1     ply_2  Arsenal      2  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
2     ply_3  Chelsea     21  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
3     ply_4  Chelsea     13  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
4     ply_5  Arsenal     50  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

Answer: After some workarounds I finally managed to find the proper solution using Pandas.Cut function.
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

df['binned'] = pd.cut(df['goals'], bins=bins, labels=labels)

out = (df.groupby(['team'])['binned']
       .apply(lambda x: [int((i == x).sum()) for i in range(10)])
       )

df = df.reset_index().merge(out.rename('goals_distribution_by_team'), on=['team'])
df = df.drop(columns=['index', 'binned'])

print(df)

  player_id     team  goals         goals_distribution_by_team
0     ply_1  Arsenal    100  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
1     ply_2  Arsenal      2  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
2     ply_3  Chelsea     21  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
3     ply_4  Chelsea     13  [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
4     ply_5  Arsenal     50  [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

Get pandas df column value distribution


If $w$ is a $1$-form on $S^2$ such that $A^*w = w$ for all $A \in SO(3)$, then $w = 0$.

Question: Assume that $w$ is a $1$-form on the $2$-sphere $S^{2}$ so that $A^{*}w = w$ for all $A \in SO(3)$. Show that $w = 0$.
I have tried to apply the definition of pullback and special orthogonal group, but I don't know how to combine these to get the result. Any hint is appreciated!
Answer: Consider first the following linear algebra proposition:
Let $(V, \left< \cdot, \cdot \right>)$ be a finite dimensional inner product space with $\dim V \geq 2$ and let $\varphi \colon V \rightarrow \mathbb{R}$ be a linear functional. Assume that $\varphi \circ S = \varphi$ for all orientation preserving orthogonal transformations $S \colon V \rightarrow V$. Then $\varphi = 0$. To see this, let $0 \neq w \in \ker(\varphi)$ and let $0 \neq v \in V$. Then there exists an orientation preserving orthogonal transformation $S \colon V \rightarrow V$ with $S \left( \frac{w}{||w||} \right) = \left( \frac{v}{||v||} \right)$. But then
$$ 0 = \varphi \left( \frac{w}{||w||} \right) = \varphi \left( S \left( \frac{w}{||w||} \right) \right) = \varphi \left( \frac{v}{||v||} \right) = \frac{\varphi(v)}{||v||} $$
which implies that $\varphi(v) = 0$.
Now, given a one-form $\omega$ on $S^2$, note that given any point $p \in S^2$ and orientation preserving orthogonal map $S \colon T_p(S^2) \rightarrow T_p(S^2)$, you can construct an element $A \in SO(3)$ such that $A(p) = p$ and $dA|_p = S$. Applying the proposition above, you can conclude that $\omega_p = 0$.

To be even more explicit and precise, consider the rotation matrices
$$ A_\theta = \begin{pmatrix} 1 & 0 & 0 \\ 0 & \cos(\theta) & -\sin(\theta) \\ 0 & \sin(\theta) & \cos(\theta) \end{pmatrix}. $$
Denote by $e_i$ the standard basis vectors of $\mathbb{R}^3$. Note that $A \in SO(3)$, $A(e_1) = e_1$ and after identifying the vectors $(e_2,e_3)$ with tangent vectors in $T_{e_1}(S^2)$, we have
$$ [d(A_\theta)|_{e_1}]_{(e_1,e_2)} = \begin{pmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{pmatrix} $$
so the differential $d(A_\theta)_{e_1}$ acts on $T_{e_1}(S^2)$ by rotation. Since $\omega_{e_1} = A_{\theta}^{*}(\omega)_{e_1} = \omega_{e_1} \circ d(A_\theta)|_{e_1}$ for all $\theta$, we must have $\omega_{e_1} = 0$. Next, given $p \in S^2$, construct a matrix $A \in SO(3)$ satisfying $Ap = e_1$ and conclude that $\omega_p = \omega_{e_1} \circ dA|_{p}$ and so $\omega_p = 0$ for all $p \in S^2$.
Answer: Suppose $w_q = 0$. As $SO(3)$ acts transitively on $S^2$, for any $p \in S^2$ there is $A \in SO(3)$ such that $A(p) = q$. As $(A^*w)_p(X, Y) = w_{A(p)}(A_*X, A_*Y) = w_q(A_*X, A_*Y) = 0$, we see that $w = 0$. That is, if $w$ has a zero, then it is identically zero.
Suppose that $w$ has no zeroes and let $g$ be a Riemmanian metric on $S^2$. As $g$ is non-degenerate, there is a vector field $V$ such that $w(Z) = g(V, Z)$ for all $Z$. As $w$ is nowhere zero, $V$ is nowhere zero. In particular, $V$ has isolated zeroes, so by the Poincaré-Hopf Theorem, $\chi(S^2)$ is the number of zeroes of $V$ counted with sign. This is a contradiction as $Z$ has no zeroes while $\chi(S^2) = 2 \neq 0$.
Therefore $w = 0$.

More generally, suppose $M$ is a closed smooth manifold and there is a smooth transitive group action by $G$ on $M$, i.e. $M$ is a homogeneous space for $G$. If $\chi(M) \neq 0$, then the only $G$-invariant $1$-form on $M$ is $0$.


If $H$ has a normal complement then it has the character restriction property

Question: I am trying to show that if a subgroup $H$ of a group $G$ has a normal complement then $H$ has the character restriction property. That is every irreducible character of $H$ is a restriction of some irreducible character of $G.$
I started with an irreducible character $\theta$ of $H$ and tried to construct $\chi \in Irr(G)$ such that $\chi_H=\theta$ using the definition of induced character. I also tried using the fact that if  $HK=G$ and $\varphi \in \text{cf}(H)$ then $$(\varphi^{G})_K=(\varphi_{H \cap K})^K.$$ But I could not complete it.
Comment: If $H$ has the normal complement $K$, then every $g \in G$ can be written uniquely as $g=hk$, and for an irreducible representation $\sigma$ of $H$, you define a representation $\rho$ of $G$ with the property you want by $\rho(hk)=\sigma(h)$.
Comment: Thank you so much @DerekHolt
Answer: I have found the answer. Here is my proof:
If $\theta$ is an irreducible character of $H$ then define $\chi(g)=\chi(hk)=\theta(h).$ Then
\begin{align}
[\chi, \chi] &= \dfrac{1}{|G|} \sum\limits_{g \in G} \chi(g)
 \overline{\chi(g)} \\
&= \dfrac{1}{|G|} \sum\limits_{hk \in HK} \chi(hk)
 \overline{\chi(hk)} \\
&= \dfrac{|K|}{|G|} \sum\limits_{h \in H} \theta(h)
 \overline{\theta(h)}\\
&= \dfrac{1}{|H|} \sum\limits_{h \in H} \theta(h)
 \overline{\theta(h)} \\
&=[\theta, \theta]
\end{align}
Hence $\chi$ is an irreducible character of $G$ with $\chi_H=\theta.$


Relação dos veículos que estão sem fotos

Question: Eu preciso da relação dos veículos que ainda não possuem fotos cadastradas.
Tenho uma tabela de Veículos, uma tabela ImagenVeiculo e uma outra TipoImagem.
Exemplo:
tbVeiculo (VeiculoId, DataCadastro, Etc...)
tbImagemVeiculo (ImagemVeiculoId, VeiculoId, TipoImagemId, Imagem, Data, Etc...)
tbTipoImagem ( TipoImagemId, Nome, Etc...)

Eu preciso saber também quais os tipos de imagens ele ainda não inseriu.
Answer: Você só precisa a cláusula NOT EXISTS:
SELECT *
  FROM tbVeiculo v
 WHERE NOT EXISTS(SELECT 1
                    FROM tbImagemVeiculo iv
                   WHERE iv.VeiculoId = v.VeiculoId)

E para verificar por tipo de imagem, faça um CROSS JOIN com a tabela tbTipoImagem:
SELECT v.*,
       ti.*
  FROM tbVeiculo v
 CROSS JOIN tbTipoImagem ti
 WHERE NOT EXISTS(SELECT 1
                    FROM tbImagemVeiculo iv
                   WHERE iv.VeiculoId = v.VeiculoId
                     AND iv.TipoImagemId = ti.TipoImagemId)

Subqueries with EXISTS or NOT EXISTS
If a subquery returns any rows at all, EXISTS subquery is TRUE, and NOT EXISTS subquery is FALSE

Ou em tradução livre:

Se a subquery retornar qualquer linha, EXISTS será VERDADEIRO, e NOT EXISTS será FALSO
Comment: +1 Me ajudou muito, eu esqueci de mencionar na pegunta, mas eu precisa saber também quais os tipos de imagens ele ainda não inseriu. Nessa seleção eu só consigo sabe se ele inseriu alguma imagem correto?
Comment: @Jhonas inclui na ultima edição da resposta a resolução para seu questionamento
Answer: Oi,
Sem saber as chaves primária e externa fica dificil mas você pode usar um NOT IN algo parecido com isso
SELECT veiculos.* from tbVeiculo veiculos
where veiculos.id NOT IN (SELECT imagem.id_veiculo from tbImagemVeiculo imagem join tbTipoImagem  tipo on imagem.id = tipo.id_tipo )

Comment: `tbTipoImagem` você usa pra que?
Answer: Acredito que isso resolva seu problema
SELECT
  v.*
FROM tbVeiculo v
WHERE v.id NOT IN (SELECT
  i.id_veiculo
FROM tbImagemVeiculo i
INNER JOIN tbTipoImagem t
  ON i.id = t.id_tipo)

Comment: `tbTipoImagem` você usa pra que?


Understanding the central limit theorem

Question: I am an aspiring probabilist, and I definitely know the central limit theorem. However, I am trying to understand what idea it really embodies.
I am aware that normal distribution arises as the limit even when the averages are taken over non-independent random variables. But in some sense, it seems the correlations among the $X_i$'s are weak. Is this intuition correct? In other words, when can we expect a central limit theorem?
Is there some deeper notion embodied in this limit law? It is so universal, it seems it is quite mysterious...
Comment: "I am aware that normal distribution arises as the limit even when the averages are taken over non-independent random variables." This is true in certain contexts, but not in general. Consider the case where $X_1 = X_2 = \dots$ and $X_1 = \pm 1$ with probability $0.5$. Then the sample average $S_n$ will be $1$ or $-1$, each with probability $0.5$; in no sense is there a normal distribution anywhere. Fundamentally, the $X_i$ terms are too correlated to one another for the CLT to kick in. (Perhaps this is kind of what you're asking about?)
Comment: Yes, so correlations being too high prevents the CLT from kicking in...but why is the limit always normal? Even in weak dependence? What is so special about it?
Answer: Here is an answer to "what's so special about the normal distribution?"
The limiting distribution is normal because the family of normal distributions is closed under addition (and averaging): if $X$ and $Y$ are normal, so are $X+Y$ and $\frac{X+Y}{2}$, with the appropriately modified means and variances.
So if we started with a bunch of i.i.d. normal random variables, their average would stay normal. This tells us that if any sort of central limit theorem holds, it ought to give the normal distribution in the limit.
In general, whenever a limit theorem holds, it gives a distribution in the limit which is closed under the operation we care about.
There are other limit theorems for other cases. For example, the Poisson distribution is a distribution on $\mathbb N$ with a similar property: if $X$ and $Y$ are Poisson, so is $X+Y$. We have Le Cam's theorem and Janson's inequality as two instances of the claim that if we sum many approximately-independent Bernoulli random variables, then in cases where the mean of the sum is constant, it has an approximately Poisson distribution.
(This doesn't contradict the central limit theorem, because the Poisson distribution with mean $\lambda$ is well-approximated by the normal distribution with mean and variance $\lambda$ when $\lambda$ is large.)
For another example, the exponential distribution is closed under minimums and scaling: if $X$ and $Y$ are exponential, so are $k \cdot X$ and $\min\{X,Y\}$. We can prove various forms of a "minimum limit theorem": if $X_1,X_2, \dots, X_n$ are sufficiently independent nonnegative random variables with probability density functions that have nonzero and reasonably similar values at $0$, then then $n \cdot \min\{X_1, X_2, \dots, X_n\}$ should be approximately exponential.
Answer: I consider an i.i.d case., i.e. there is a sequence of i.i.d r.v.s $\{X_n\}$ with distribution $F_X$. It is known that $F_X$ belongs to the domain of attraction of some distribution $F_{\infty}$ is there exists a sequence $\{(m_n,s_n)\}$ s.t.
$$
\frac{\sum_{i\le n} X_i-m_n}{s_n}\xrightarrow{d}F_{\infty}.
$$
We also know that only stable distributions can be domains of attraction. In particular, $F_X$ belongs to the domain of attraction of the normal distribution if and only if
$$
U(x)=\mathsf{E}X_1^2 1\{|X_1|\le x\}
$$
is a slowly varying function. For more results you may look at Chapter 9 in Probability: A Graduate Course by Allan Gut.

Understanding the central limit theorem


How to drop my Foreign key in database?

Question: I am using Hibernate to generate my schema. Hibernate create the following sql instruction
alter table Person add index FKA126572FF5D5DSE (job_id), add constraint FKA126572FF5D5DSE foreign key (job_id) references Job(id)

This sql was executed in my database and the index exists.I would like just to remove the index and its associated constraint.
Is it the following sufficient ?
alter table Person drop foreign key FKA126572FF5D5DSE ;

Thanks.
Comment: Out of curiosity, why's the index called FKA126572FF5D5DSE?
Comment: The name of the index is generated using Hibernate default Rules. I don't need to have a specific name
Comment: If you want to drop the index as well you need to do it explicitly. Only if you drop the table then the index will be also dropped implicitly.
Comment: @zaratustra what is missing in my drop instruction ?
Comment: @Pracede Did you try it and it doesn't work, or are you asking just from curiosity? ^^
Comment: Yes i've tried it. It does not work. It just delete the foreign key but the index remains. So to delete Index and Foreign Key, I have to do 2 instruction drop foreign key first then drop index.
Answer: To drop the foreign key and its index you need to execute:
alter table t1 drop FOREIGN KEY FKA126572FF5D5DSE;
ALTER TABLE t1 DROP INDEX FKA126572FF5D5DSE;

SQLFiddle

How to drop my Foreign key in database?


String validation not working for custom form

Question: Please help me with Drupal 8 validation for string.
<code>   $form['field_text'] = array(

  '#type'  => 'textfield',

  '#title' => $this->t('Name'),

  '#attributes' => array(' type' => 'alpha' ),

   );

  $form['field_phone'] = array(

  '#type' => 'textfield',

  '#title' => $this->t('Phone'),

  '#attributes' => array(' type' => 'number' ),

  );
</code>
I am able to validate Phone no but not string .
Please suggest what i am doing wrong.
Answer: You can add validate form function for same.
public function validateForm(array &$form, FormStateInterface $form_state) {
<code>if(!preg_match("/^[a-zA-Z ]*$/",$field_text))

{

  drupal_set_message("MESSAGE_TO_ENTER_STRING_CHARACTERS");

}
</code>


Unable to pass a list as an argument to a function? How can I pass the list without getting an error?

Question: I have the following function
my_func <- function(sport,
                eventId = eventids,
                apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx",
                regions = "us",
                markets = "alternate_spreads",
                odds_format = "american",
                date_format = "iso"){

    base_url = glue::glue("https://xxx.xxx-xxx-
xxx.xxx/xx/xxxxxx/{sport}/xxxxxx/{eventId}/odds")

    query_params <- list(apiKey = apiKey,
                         sport = sport,
                         eventId = eventId,
                         regions = regions,
                         markets = markets,
                         oddsFormat = odds_format,
                         dateFormat = date_format)

    endpoint <- httr::modify_url(base_url, query = query_params)

    resp <- fromJSON(endpoint) %>%
            as_tibble(validate = F) %>%
            unnest(cols = bookmakers) %>%
            rename("bookmaker_key" = "key") %>%
            unnest(cols = markets) %>%
            unnest(cols = outcomes)

    return(resp)
}

I am trying pass the following list of eventids as an argument
eventids <- followinglist

A tibble: 2 × 1
   id
   <chr>
 1 xxxxxxxxxxxxxxxxadaf06d2660af34
 2 xxxxxxxxxxxxxxxa67aa5a4bce731a0

When I execute the following syntax
my_func('basketball')

I get the following error:
Error in open.connection(con, "rb") :
cannot open the connection to 'https://xxx.xxx-xxxx-xx/sports/basketball/events/truncated?
In addition: Warning message:
In open.connection(con, "rb") :
cannot open URL 'https://xxx.xxx-xxxx-xx/sports/basketball/events/truncated?

HTTP status was '422 Unknown Error'

I have also tried using the following format of eventids
eventids <- c("xxxxxxxxxxxxxx57adaf06d2660af34", "xxxxxxxxxxx7aa5a4bce731a0")

and get the following error when running running the function
Error in parse_url(url) : length(url) == 1 is not TRUE

I found another post that suggested using
eventids1 = paste(eventids, collapse = ",")

However, I get the same error as above
Error in open.connection(con, "rb") :
cannot open the connection to 'https://xxx.xxx-xxxx - this has been truncated

I have also tried using the following
map(eventids, my_func)

but get the following error
Error in `map()`:
ℹ In index: 1.
Caused by error in `parse_url()`:
! length(url) == 1 is not TRUE
Run `rlang::last_error()` to see where the error occurred.

I know the function works because if I pass a single eventid, I get a response and data
my_func('basketball', 'xxxxxxxxxxxxxxxx4bce731a0')

The API only allows a single eventid to be passed at a time which is my reason for wanting to pass a list of eventids.  How can I query the API by passing a list and having the responses written to a tibble?  Thank you in advance.
I tried running the following
map(eventids, ~my_func(sport = "basketball", eventId = .x))

but got the following error.
Error in `map()`:
ℹ In index: 1.
ℹ With name: id.
Caused by error in `parse_url()`:
! length(url) == 1 is not TRUE
Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/purrr_error_indexed>
Error in `map()`:
ℹ In index: 1.
ℹ With name: id.
Caused by error in `parse_url()`:
! length(url) == 1 is not TRUE
---
Backtrace:
1. purrr::map(eventids, ~my_func(sport = "basketball_nba", eventId =
.x))
2. purrr:::map_("list", .x, .f, ..., .progress = .progress)
6. global .f(.x[[i]], ...)
7. global my_func(sport = "basketball_nba", eventId = .x)
8. httr::modify_url(base_url, query = query_params)
9. httr::parse_url(url)
10. base::stopifnot(length(url) == 1)
11. base::stop(simpleError(msg, call = if (p <- sys.parent(1L))
sys.call(p)))
Run `rlang::last_trace()` to see the full context.
> rlang::last_trace()
<error/purrr_error_indexed>
Error in `map()`:
ℹ In index: 1.
ℹ With name: id.
Caused by error in `parse_url()`:
! length(url) == 1 is not TRUE
---
Backtrace:
 ▆
1. ├─purrr::map(eventids, ~my_func(sport = "basketball_nba", eventId =
.x))
2. │ └─purrr:::map_("list", .x, .f, ..., .progress = .progress)
3. │   ├─purrr:::with_indexed_errors(...)
4. │   │ └─base::withCallingHandlers(...)
5. │   ├─purrr:::call_with_cleanup(...)
6. │   └─global .f(.x[[i]], ...)
7. │     └─global my_func(sport = "basketball_nba", eventId = .x)
8. │       └─httr::modify_url(base_url, query = query_params)
9. │         └─httr::parse_url(url)
10. │           └─base::stopifnot(length(url) == 1)
11. │             └─base::stop(simpleError(msg, call = if (p <-
sys.parent(1L)) sys.call(p)))
12. └─purrr (local) `<fn>`(`<smplErrr>`)
13.   └─cli::cli_abort(...)
14.     └─rlang::abort(...)

Comment: have you checked whether the ids provided in the vector work individually?
Comment: There are currently 13 eventids.  I checked 2 of them and yes they return data.
Answer: it seems like your function can only accept a single scalar eventid as its argument, but you are trying to pass a vector of eventids.
Moreover, you should provide the arguments for which there are no defaults, for every call to my_func. These are sport and eventId.
You may want to loop through the eventids vector like this:
map(eventids, ~my_func(sport = "basketball", eventId = .x))

Comment: Thanks @ GuedesBF.  I am specifying the "sport" manually when executing the command as well as specifying the "eventid" vector.  I tried your suggestion but get the same error.  I will update my original post with the new error as it is too long to fit in this comment.
Comment: Any ideas?  Are you aware of any other forums where I might ask this question?
Answer: After using the following syntax
eventids <- nba_h2h %>%
    distinct(id) %>%
    pull()

and converting from class tibble to class "character" I was able to execute the following
map(event_ids, ~my_func(sport = "basketball_nba", eventId = .x))
%>% bind_rows()

Thanks for the help and guidance!
Comment: Happy you found the way. A tip: if you replace `map` with `map_dfr`, i think you no longer need to call `bind_rows` afterwards


How do I add a view between display fields of a node?

Question: I have a view that displays a table at the bottom of every node. It's part of the content of the node so I want to have the "comments" section below the view.
However, the comments are a display field, which means they have to be in the same block as the node content. Since the view is a separate block I can't place the view between the node content and the comment section.
Is there a workaround for this?
Note that my content is created by the website community, so I can't use any solution that involves changing the contents of the nodes manually.
Comment: See https://drupal.stackexchange.com/questions/193833/need-to-display-views-block-in-between-two-fields-of-a-node
Comment: Is it always the same view and does every node of that particular type need to have the block displayed?
Comment: Did you try Layout Builder?
Comment: @leymannx yes for a given content type it is the same view block that I want to render above the comment section. It's always the same view. Note however that the content is created by the community, so I wouldn't want any proposed solution to affect the UX as far as creating content is concerned. I've added this to the post.
Comment: @PatrickKenny I wasn't aware of Layout builder, thanks for the tip. I'll do some reading!
Answer: This can be done with Drupal 8's Layout Builder.
Layout Builder is a module in Drupal 8 core that does much of what Panels did in Drupal 7 and before-- it allows you to create arbitrary layouts consisting of fields and blocks for content types and even individual pieces of content.
Since its part of core, this should be a safe long-term solution to rely on.
In this case, the rough steps would be:

Enable Layout Builder.
Go to Structure -> Content types -> MY CONTENT TYPE -> Manage Display.
Under Layout options, check Use Layout Builder and save.
Click the new Manage layout button that appears.
Your fields will be arranged as before.  Now, though, you can click Add block to add any block you want, including Views blocks.  You can then put the Views block between your page body and your comments.

This is just scratching the surface of what you can do but it should get you started.


Constructing a generalized linear model when the dependent variable has a Exponentially modified Gaussian distribution

Question: I have some data where I have reason to believe the dependent variable $Y$ follows an Exponentially modified Gaussian distribution, i.e. $Y$ is the sum of one gaussian distributed stochastic variable $A$ and one exponentially distributed stochastic variable $B$,
$$ Y = A+B $$
I would like to construct a generalized linear model with this assumption. How can I do this? For example, in the python statsmodels package, I can do
<code>model = sm.GLM(data.endog, data.exog, family=sm.families.Gaussian())
</code>
But the family argument only accepts Binomial, Poisson, Neg. Binom., Gaussian, Gamma, Inv. Gauss, Tweedie. Is there any trick I can do or how would I go about this? What link function would I use?
Comment: GLM in statsmodels is only for families that are one-parameter linear exponential families (LEF), with fixed extra parameters and auxiliary scale if it is not fixed. Regression for distributions not in this family are implemented as generic maximum likelihood models. The `GenericLikelihoodModel` can be used for user provided likelihood functions. Note, AFAICS from the wikipedia page, the mean of the exponentially modified Gaussian is not of the form `link_inverse(linear_predictor)` as in GLM, so it will not fit into the GLM/LEF framework.
Comment: Have you tried fitting a linear model and looking at the distribution of the residuals? Fitting a distribution to $\mathbf{Y}$ (the dependent variable) is not particularly useful in the presence of explanatory variables. Even if the errors are Gaussian, remember that each $Y_i$ has its own mean ($\mathbf{x}_i' \beta$), so the distribution will be a mixture of Gaussians.
Comment: This is not a standard model, so you would need to write your own likelihood function. You say that this is a GLM, so I presume there are some explanatory variables. Are both $A$ and $B$ functions of these variables?
Comment: This distribution has three parameters: the mean ($\mu$) and variance ($\sigma^2$) of the Gaussian part, and the scale ($\theta$) of the Exponential part. Assuming that $\sigma^2$ is the same for every observation, you could write down a model where $\mu$ and $\log\theta$ are linear combinations of the explanatory variables.
Comment: @DoctorMilt I would assume both of them are. Initially I had a linear regression model $$Y=\beta_0 + \beta_1 x_1 + ... + \beta_i x_i + ... + \beta_p x_p.$$
I have read both that linear regression does and does not need $Y$ to be distributed gaussian. Atleast my residuals are. Since $Y$ is reaction times, usually distributed according to Exponentially modified Gaussian distribution, I thought I could do better by using GLM and assuming exgauss distribution. This is where I am at. I don't know if this is sound at all and would appreciate any help.
Comment: The PDF of the exponentially modified Gaussian involves evaluating a convolution integral, so it includes the error function (see here: https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution). I am not very familiar with Python, but it is implemented efficiently in R.
Comment: @DoctorMilt I'm afraid I don't fully understand how to construct it yet, but I will take a look at generalized linear models in R, thanks. But just for a sanity check: I have confirmed that $Y$ as well as the residuals in a linear regression model better fits exgaussian rather than gaussian. Would it from this point make sense to construct a glm (in whatever way) where I try to set the "family" to exgaussian? What would I set the link function to?
Comment: The big advantage of GLM/LEF is that the mean parameters are consistently estimated if the mean function (link) is correctly specified, but it does not require that variance function and distribution are correctly specified. That means we can treat all GLM/LEF families as quasi-maximum likelihood models. This is not the case for other distributions.
Comment: @Josef So I take it I can't use glm. So I can use scipy.stats.exponnorm.fit()(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.exponnorm.html ) to use maximum likelihood estimation to fit an exgauss distribution to my data and it fits the collected data of the dependent variable almost perfectly. But how can I use this to construct a model based on my data of independent variables? My end goal is to interpret and create confidence intervals for the coefficients of my model, think $\beta$ in $Y=A\beta$
Comment: Should you be open to Bayesian modeling, the brms package has the ex-Gaussian family. See here: [http://paul-buerkner.github.io/brms/reference/ExGaussian.html](http://paul-buerkner.github.io/brms/reference/ExGaussian.html).
Answer: Generalized linear models assume that the response variable follows an exponential dispersion model (EDM) distribution. For fixed dispersion value, an EDM is a linear exponential family (LEF). As already pointed out by @Josef in a comment, the normal+exponential convolution distribution is not a LEF and hence there is no generalized linear model.
The whole point of generalized linear models is that the response distribution is determined by the mean-variance relationship.
The normal+exponential convolution does not have a characteristic mean-variance relationship, so it never could be a candidate for the generalized linear model framework.
The normal+exponential convolution distribution has however been used extensively in the bioinformatics literature for background correction of microarray intensities. I've listed a few references below. So there is existing software for estimating the parameters of the normal+exponential convolution.
If your intention is simply to model your response variable using covariates then the normal+exponential convolution might not be the best way to proceed.
The first step would usually be to fit a normal linear regression model and then plot the residuals vs fitted values to view the mean-variance relationship.
That is more relevant than examining the marginal distribution of the y-values.
Since your $y$ values are reaction times, and are presumably strictly positive, they probably have an increasing mean-variance relationship.
I would try log-transforming and then fit the linear regression again, to see if that removes the mean-variance dependence.
References
Ritchie ME, Silver J, Oshlack A, Holmes M, Diyagama D, Holloway A, Smyth GK (2007). A comparison of background correction methods for two-colour microarrays. Bioinformatics 23, 2700-2707.
Silver JD, Ritchie ME, Smyth GK (2009). Microarray background correction: maximum likelihood estimation for the normal-exponential convolution. Biostatistics 10, 352-363.
Xie Y, Wang X, Story M (2009). Statistical methods of background correction for Illumina beadarray data. Bioinformatics 25, 751–757.
Shi W, Oshlack A, Smyth GK (2010). Optimizing the noise versus bias trade-off for Illumina Whole Genome Expression BeadChips. Nucleic Acids Research 38, e204.


Renaming lots of files in Linux according to a pattern

Question: I'm trying to do three things with the mv command, but not sure it's possible? Probably need a script. not sure how to write it. All files are in same folder.
1) Files ending with v9.zip should just be .zip (the v9 removed)
2) Files containing _ should be -
3) Files with Uppercase letter next to a lowercase letter (or lowercase next to an Uppercase) should have a space between them. So MoveOverNow would be Move Over Now and ruNaway would be ruN away
[A-Z][a-z] or [a-z][A-Z] becomes [A-Z] [a-z] and [a-z] [A-Z]
Comment: Your last point seems underspecified. What's the rule to determine if 'ruNaway' should be 'ruN away' or 'ru Naway'?
Comment: Im not sure that you would use mv to do this... maybe look into a script solution, given the conditional scenarios.
Comment: 1 and 2 ought to be trivial using `rename`. 3 is more involved so will require some scripting. Which shell do you use, bash?
Comment: http://theunixshell.blogspot.com/2013/01/bulk-renaming-of-files-in-unix.html
Answer: There's a rename command provided with most Debian/Ubuntu based distros which was written by Robin Barker based on Larry Wall's original code from around 1998(!).
Here's an excerpt from the documentation:

  "rename" renames the filenames supplied according to the rule specified as the first argument.  The perlexpr argument is a Perl expression which is expected to modify the $_ string in Perl for at least some of the filenames
  specified.  If a given filename is not modified by the expression, it will not be renamed.  If no filenames are given on the command line, filenames will be read via standard input.

  For example, to rename all files matching "*.bak" to strip the extension, you might say

          rename 's/\.bak$//' *.bak

  To translate uppercase names to lower, you'd use

          rename 'y/A-Z/a-z/' *

It uses perl so you can use perl expressions to match the pattern, in fact I believe it works much like tchrist's scripts.
One other really useful set of tools for bulk file renaming is the renameutils collection by Oskar Liljeblad. The source code is hosted by the Free Software Foundation. Additionally many distros (especially Debian/Ubuntu based distros) have a renameutils package with these tools.
On one of those distros you can install it with:
$ sudo apt-get install renameutils

And then to rename files just run this command:
$ qmv

It will pop open a text editor with the list of files, and you can manipulate them with your editor's search and replace function.
Answer: I haven't tested these, so I put echo at the front of the commands so you can try them before removing the echo to run them for real.

for f in *v9.zip; do echo mv "${f}" "${f%v9.zip}.zip"; done

for f in *_*; do echo mv "${f}" "${f//_/-}"; done

As for your third problem I'm sure it can be done too but maybe a more sophisticated approach than raw shell one-liners will help, as @tchrist mentioned.
Comment: +1 because the first line helped me with my simple version of this problem. Thanks.
Comment: This was exactly what I needed. It allowed me to sort out the command until it was perfect then remove the echo and 'fire'!
Answer: My favorite solution is my own rename script. The simplest example that maps to your problems are these:
% rename 's/_/-/g' *
% rename 's/(\p{Lower})(\p{Upper})/$1 $2/g' *

Although I really hate whitespace in my filenames, especially vertical whitespace:
 % rename 's/\s//g' *
 % rename 's/\v//g' *

et cetera.  It's based on a script by The Larry Wall, but extended with options, as in:
usage: /home/tchrist/scripts/rename [-ifqI0vnml] [-F file] perlexpr [files]
    -i          ask about clobbering existent files
    -f          force clobbers without inquiring
    -q          quietly skip clobbers without inquiring
    -I          ask about all changes
    -0          read null-terminated filenames
    -v          verbosely says what its doing
    -V          verbosely says what its doing but with newlines between old and new filenames
    -n          don't really do it
    -m          to always rename
    -l          to always symlink
    -F path     read filelist to change from magic path(s)

As you see, it can change not just the names of files, but where symbolic links are pointing to using the same  pattern.  You don't have to use a s/// pattern, although often one does.
The other tools in that directory are mostly for Unicode work, of which there are some super-useful ones.
Comment: The link to training.perl.com/scripts/rename is broken.
Comment: Uhh wow, I'm not sure I'm properly licensed to have this kind of extreme power. Thank you very much!
Answer: The above answers apply to Debian, Ubuntu etc
For RHEL and co: rename from_pattern to_pattern files
Answer: I think the link is broken and I couldn't find the page in the webarchive to the rename script in tchrist's post, so here is another one in Perl.
#!/usr/bin/perl
# -w switch is off bc HERE docs cause erroneous messages to be displayed under
# Cygwin
#From the Perl Cookbook, Ch. 9.9
# rename - Larry's filename fixer
$help = <<EOF;
Usage: rename expr [files]

This script's first argument is Perl code that alters the filename
(stored in \$_ ) to reflect how you want the file renamed. It can do
this because it uses an eval to do the hard work. It also skips rename
calls when the filename is untouched. This lets you simply use
wildcards like rename EXPR * instead of making long lists of filenames.

Here are five examples of calling the rename program from your shell:

% rename 's/\.orig$//'  *.orig
% rename 'tr/A-Z/a-z/ unless /^Make/'  *
% rename '$_ .= ".bad"'  *.f
% rename 'print "$_: "; s/foo/bar/ if <STDIN> =~ /^y/i'  *
% find /tmp -name '*~' -print | rename 's/^(.+)~$/.#$1/'

The first shell command removes a trailing ".orig" from each filename.

The second converts uppercase to lowercase. Because a translation is
used rather than the lc function, this conversion won't be locale-
aware. To fix that, you'd have to write:

% rename 'use locale; $_ = lc($_) unless /^Make/' *

The third appends ".bad" to each Fortran file ending in ".f", something
a lot of us have wanted to do for a long time.

The fourth prompts the user for the change. Each file's name is printed
to standard output and a response is read from standard input. If the
user types something starting with a "y" or "Y", any "foo" in the
filename is changed to "bar".

The fifth uses find to locate files in /tmp that end with a tilde. It
renames these so that instead of ending with a tilde, they start with
a dot and a pound sign. In effect, this switches between two common
conventions for backup files
EOF

$op = shift or die $help;
chomp(@ARGV = <STDIN>) unless @ARGV;
for (@ARGV) {
    $was = $_;
    eval $op;
    die $@ if $@;
    rename($was,$_) unless $was eq $_;
}


Some questions regarding complex analysis

Question: I recently came across the following problem

Pick out the true statements:

There is a bijective analytic function from $\Bbb C$ to the upper half plane $\Bbb H$

There is a non-constant bounded analytic function on $\Bbb C \setminus \{0\}$

If $\{a_n\}$ and $\{b_n\}$ are two sequences of positive real numbers with $a_n \longrightarrow 0$ and $b_n$ diverging to $\infty$, then the sequence $c_n=a_ne^{ib_n} \longrightarrow 0$

My try
For the first bullet, the statement is false, since if it is true, then the range of such a function is dense in $\Bbb C$ but $\Bbb H$ is not dense in $\Bbb C$.
For the third one, the statement is true. Since $$c_n \longrightarrow 0 \iff (\Re( c_n) \longrightarrow 0) \wedge (\Im(c_n) \longrightarrow 0)$$  The above is true, since $$\vert \Re (c_n) \vert=\vert a_n \cos b_n\vert \leq \vert a_n \vert \to 0$$ and $$\vert \Im (c_n) \vert=\vert a_n \sin b_n\vert \leq \vert a_n \vert \to 0$$
Is this correct?  May I have a hint for the second one?
Answer: The third one is simpler than that. Just use the fact that $\lvert a_ne^{ib_n}\rvert=a_n$.
For the second one, think about the type of singularity that such a function would have at $0$.
Comment: I had no use for it.
Comment: Thanks! How about the first one? Is my reasoning correct?
Comment: Yes, it is correct.
Comment: In the third one, we cannot use the divergence of $b_n$ . Is this divergence assumption, not needed here ?


VS 2017 for Android emulator not working - xamarin

Question: Installed VS 2017 (prof & community) RTM for xamarin development. Getting the below error while running the app. I have verified that installed the Intel Acceleration component. Any insights ?

1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for FormsViewGroup.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for Xamarin.Forms.Platform.Android.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>C:\Users\Sowmyan\documents\visual studio 2017\Projects\App1\App1\App1.Android\App1.Android.csproj : warning XA0105: The $(TargetFrameworkVersion) for Xamarin.Forms.Platform.dll (v7.1) is greater than the $(TargetFrameworkVersion) for your project (v6.0). You need to increase the $(TargetFrameworkVersion) for your project.
1>    Processing: obj\Debug\res\layout\tabbar.xml
1>    Processing: obj\Debug\res\layout\toolbar.xml
1>    Processing: obj\Debug\res\values\styles.xml
1>    Processing: obj\Debug\res\layout\tabbar.xml
1>    Processing: obj\Debug\res\layout\toolbar.xml
1>    Processing: obj\Debug\res\values\styles.xml
2>Starting deploy VisualStudio_android-23_x86_phone ...
2>Starting emulator VisualStudio_android-23_x86_phone ...
2>C:\PROGRA~2\Android\ANDROI~1\tools\emulator.EXE -partition-size 512 -no-boot-anim -avd VisualStudio_android-23_x86_phone -prop monodroid.avdname=VisualStudio_android-23_x86_phone
**2>emulator: ERROR: x86 emulation currently requires hardware acceleration!**
2>Please ensure Intel HAXM is properly installed and usable.
2>CPU acceleration status: HAXM is not installed on this machine
2>Emulator VisualStudio_android-23_x86_phone cannot be started.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========
Comment: Please add in SDK Manager in Extras "HAXM installer" and close the VS and emulator. If the error persists, try using Xamarin Android Player. It is very stable and fast.
Answer: I had a similar problem on my laptop.  It turned out the Virtualization was turned off in my BIOS.  My recommendation is to enter the BIOS setup on reboot   (refer to manual as all machines are different) and see if Intel Virtualization is enabled.  If not, you will need to enable it.


pass cck email value to webform block

Question: I currently have 2 webforms displayed on a page - these are inserted dynamically from a node.tpl.php file.
However, I also have a cck field on the current node for an email address - I would like to be able to pass this email value directly to the "Email To" field of the webform.
This would create a new email recipient depending on which node you were viewing. For example:
The "About Us" page contained the field "email: email@example.com" - therefore the webform loaded in the sidebar would be sent to this address.
The "Location" page contains the field "email: email@example.com" - now this would be the email address that receives any submissions from that page.
The idea is to have 1 webform and dynamically change the email its sent to based on a cck field. Is this possible at all?
Thanks,
Garry.
Answer:
In your webform add an "email field" for the recipient (say email_recipient).
Go to node/123/webform/emails to set the recipient to be your previously created field.
Create a hook_form_alter to put the email address you your webform field.
<?php
function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  //you need to set up a CUSTOM module to store this.
  //use devel with dsm($form); to figure the name of each field
  if ($form['#id'] == 'webform-client-form-123') {
    //load the node from the url
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node_email = node_load(arg(1));
      //set your webform field to your email
      $form['submitted']['con_email_recipient']['#default_value']
           = $node_email->field_email_recipient[0]['value'];
    }
  }
}
?>

Add some CSS to hide the field, and it should work, code untested but I'm pretty confident about the steps, also have a look at Working with Default Values.
Comment: Thanks for the response, I have setup my custom module and added the recipient email field to my form. However, I am receiving an error with your code "Fatal error: Can't use function return value in write context in..." I also don't see where my CCK email field is being inserted into the webform. Do you have anymore instructions? Cheers, Garry.
Comment: @Garry which line cause the error ? Do you see your recipient field being populated with your CCK ?
Answer: I know this is old, but in case anyone else comes up with this problem, the problem is this line:
if (arg(0) = 'node' && is_numeric(arg(1))) {

should be
    if (arg(0) == 'node' && is_numeric(arg(1))) {

Comment: Your post not attempt to answer this question, explain in brief!!
Comment: Yep I fixed it, thanks for the bug report ;) but it should be a comment on my answer as yours isn't a proper answer.

pass cck email value to webform block


Should I try to perfect every song I play at open mic?

Question: I've recently taken to attending open mic nights to try and get some much needed experience playing in front of an audience. I've currently got two performances under by belt and I realize I have a long way to go before I feel comfortable playing my own songs in front of other people. I play guitar and sing.
I was always raised to believe that you should have your performance nailed down before you get on stage. If you're getting up on stage in front of strangers and performing, you should know your piece forwards, backwards, and inside out to make sure that you give a good performance. It will take a ton of time, but it's worth it to avoid making sloppy mistakes in front of others.
I still firmly believe this is a good way to handle performances. However, I'm wondering if this kind of outlook is useful for weekly Open Mic at a local coffee house. On one hand, the amount of time it takes for me to compose, write, research, play, and cement two interesting songs to my personal satisfaction is close to a month and that means I'm missing about four potentially educational performances. On the other hand, performing without the proper practice might lead to generally sloppy output and a lower bar for quality. On yet another hand, I'm so nervous playing around others that my playing suffers as a result anyway, regardless of the hours of practice.
Should I play far fewer nights and try for cemented pieces, or play more frequently with less practice but get more experience in front of others?
Comment: I would say "get the experience." That's the best way to learn to survive "disasters" which the audience might not even notice, unless *you* make it obvious to them that something is wrong. You can always do cover versions if you don't have enough of your own material. "Real pros" are quite capable of sight reading in front of a paying audience, when they need to - you can't learn how to get away with that by locking yourself away and perfecting a performance of something in private.
Comment: Can't you play some covers also or instead? And maybe look at forming a band to help with the nerves (it's easier to share the stress).
Comment: @NeilMeyer - your statement is dependant on the definition of 'perfect'. I don't derive much pleasure listening to a band or any musicians who play something they've perfected by lots of rehearsal in order to regurgitate songs 'perfectly' but learned by rote, thus they're the same every time they get played. Music ought to be living and morphing, and is when played by true musos, rather than trying to 'perfect' pieces.
Comment: @ToddWilcox - and - there's always someone else to take the blame...
Comment: You should perfect any song you play before you play it period, you don't insult your audience by playing music you don't know well.
Comment: @NeilMeyer well, it's certainly not bad to err on the safe side, however there is also such a thing as "practising a song to death". I know plenty of guys who spend hours and hours "perfecting" their stuff and end up sounding completely boring. And I know some lazy bastards who dare showing up to a paid gig after no practise, only ¹⁄₂ hour of rehearsal, and end up making a couple of mistakes but, thanks to being just great musicians, still leave the audience much more satisfied. And to become a good musician, I daresay playing live a lot helps proportionally much more than practising a lot.
Answer: Giving this some thought! Open mics are great for cutting your teeth as a beginning performer, and I think most of the audience is fairly forgiving - it's a free night for them, so their expectations shouldn't be too high. Not that that gives you licence to play/sing poorly. Of course you want to do your best.
But, perfect? What's perfect? Especially considering the songs you're doing are your own. You own them, and can do them any way you like. Provided you don't get lost in the middle of them, or if you do, you keep going, who's to know except you? You need to be able to leave out a verse, put in another middle eight, stick a key change in if you like, so perfect isn't the word.
Know the song inside out - after all, it's your baby. Open mic is a good time to play it differently, and gauge audience reaction.
It's also good for finding others of similar mind. Just get up and do your best, and maybe chat to others about putting 3 or 4 of you together to play those songs. BUT - do try not to reahearse them to death, so they're note perfect, like so many do. That's not music, there needs to be room to change things around in mid flight, which involves what I never see enough of. Listening to each other.
As suggested in the comments, playing covers is a good idea - you will even find that others will get up and play along. Scary at first, but great fun.Or, you might decide to do a cover, but change it about in a very different way - slow it right down, speed it up, segue two songs, the list is endless. I've just done a gig where 5 or 6 of us had played 'All Blues' before. Someone said 'now let's try in 5/4' so we just got on with it. No good saying 'but we need to practise it first', what I'm saying is be prepared to play unprepared.
So, in summation, it's a bit of both. Some stuff you can prepare - although doing it the same every time can render it boring - other stuff, be aware of how the verse/chorus goes, and have a go at winging it. A lot of the time the audience will be blissfuly unaware!
Comment: How do you gauge audience reaction at an open mic? People applaud virtually anything at those things. Where appreciation ends, pity takes over.
Comment: @EdPlunkett - very good question - perhaps you should post it. Done a fair few open mics, and sometimes a number goes perfectly, slickly, cleverly, and the audience seems oblivious. Others have been really rough, as far as I'm concerned, and the audience loves it. Owt as queer as folk... So, no actual criteria as far as I'm concerned.
Answer: I think the benefit of playing with less-than-perfect material might be outweighed for some performers by a sort of "aversion therapy" effect. Some people will react to their own mistakes and subsequent embarrassment by feeling traumatized and increasing their negative self-talk. But I think if you can avoid or overcome that danger, you will get a lot out of these performances! Always follow a shaky piece with a solid one, and practice recovering from mistakes at home by not letting yourself stop and correct on final run-throughs. I also have students rehearse for public performance by recording themselves a lot. Knowing you are being recorded mimics external distraction to some degree.
Answer: You should try to perfect every song you perform anywhere.
But you should recognize that 100% perfection is an unrealistic aim.  It can happen, but even the best performers edit their recordings.
A recording is different.  Repeatedly heard, a small mistake becomes irritating.  In live performance it is tolerated.
But don't take this as permission to be sloppy!
Answer: An audience is going to make you self-conscious... making you perform worse than your typical practice standard.
At some point you'll learn to forget the audience and enter a "zone of concentration" that delivers your best work in front of people.
Open Mic's are useful to help transition from being incapable of concentration on making the music vs listening for the next mistake.
I'd recommend you target tunes that are easier to master to feel better about the "mistakes" and work on developing performance confidence. Performances that you are not proud of only make the Open Mic experience
less helpful in learning to be a confident performer.
As your success with less challenging material starts to pay dividends then target more challenging material or introduce your own creations into the mix. Overtime create a list of songs you can play with a high degree of confidence and keep these tunes in the practice mix and pull your open mic
selections from that list. 20 tunes is a good target for a 6 month or 12 month goal depending upon the amount of time you invest and the difficulty of the tunes selected.
After 2-3 years you'll ve in a good position to expect people to pay for your effort... you can test this assumption by busking to see if people like the results. Busking is like practicing in public with a tip jar out front.


Porque este @Html.DropDownListFor não aceita os htmlAttributes?

Question: Tenho uma View que será somente leitura em alguns casos. E não quero usar javascript, pois pode ser desabilitado no lado do usuário.
Em fim...
Quando faço isso (para testes) funciona perfeitamente.

@Html.LabelFor(model => model.IdStatusRegistro, htmlAttributes: new { @class = "control-label col-md-2" })

    @Html.DropDownListFor(model => model.IdStatusRegistro, new SelectList(ViewBag.ListaSelectList, "Id", "Descricao"), new { @class = "form-control input-sm", @disabled ="disabled" })
    @Html.ValidationMessageFor(model => model.IdStatusRegistro, "", new { @class = "text-danger" })

Mas quando tento passar os atributos HTML por variável, como a seguir, não funciona:
var attribs = new Dictionary<string, object>();
attribs.Add("class", "form-control input-sm");
if (ViewBag.ReadOnly)
{
    attribs.Add("disabled", "disabled");
}

@Html.LabelFor(model => model.IdStatusRegistro, htmlAttributes: new { @class = "control-label col-md-2" })

    @Html.DropDownListFor(model => model.IdStatusRegistro, new SelectList(ViewBag.ListaSelectList, "Id", "Descricao"), new { htmlAttributes = @attribs })
    @Html.ValidationMessageFor(model => model.IdStatusRegistro, "", new { @class = "text-danger" })

Repare que a única coisa que mudo é:
@class = "form-control input-sm", @disabled ="disabled"
por
htmlAttributes = @attribs
E o que me deixa curioso é que isso sempre funcionou para mim. Inclusive na mesma View funciona perfeitamente para os @Html.EditorFor. Só este DropDownListFor que não está recebendo o @attribs.
Answer: Tente da seguinte forma:
@Html.DropDownListFor(model => model.IdStatusRegistro, new SelectList(ViewBag.ListaSelectList, "Id", "Descricao"), htmlAttributes: attribs)

Aparentemente é só um erro na passagem do parâmetro.
Comment: Obrigado! Realmente funcionou. Mas saberia me dizer o porque nos EditorFor não tive problema? Afinal qual a maneira correta... @Html.EditorFor(model => model.DataCadastro, new { htmlAttributes = @attribs })   ou   @Html.EditorFor(model => model.DataCadastro, htmlAttributes: @attribs)?
Comment: A maneira correta é  `htmlAttributes: @attribs`, não sei te dizer porque funcionou da outra forma no EditorFor mas declarando um novo objeto com uma propriedade htmlAttributes (`new { htmlAttributes = ... }`) não é uma sobrecarga válida. O certo é um objeto com os atributos no tipo chave/valor ou um dicionário


The component for route 'Example' must be a react component

Question: So I have a rootstack navigation from react-navigation
I have a folder Markets with index.js like this:
import ExampleOne from './ExampleOne';
import ExampleTwo from './ExampleTwo';
import ExampleThree from './ExampleThree';
import ExampleFour from './ExampleFour';
import ExampleFive from './ExampleFive';

export {
    ExampleOne,
    ExampleTwo,
    ExampleThree,
    ExampleFour,
    ExampleFive
};

with ExampleOne.js to ExampleFive.js like this:
import React, { Component } from 'react';
import { Container, Content, Text } from 'native-base';

export default class ExampleOne extends Component {
  render() {
    return (
      <Container>
        <Content>
          <Text>Example</Text>
        </Content>
      </Container>
    )
  }
};

But when I importing it to RootStack.js, I got an error "The Component for route 'ExampleOne' must be a React Component.'
RoutStack.js like this:
import React from 'react';
import { createStackNavigator } from 'react-navigation';

// Import all MarketsScreen
import { ExampleOne, ExampleTwo, ExampleThree, ExampleFour, ExampleFive } from './Markets';

const RootStack = createStackNavigator({
    ExampleOne: ExampleOne,
    ExampleTwo, ExampleTwo,
    ExampleThree: ExampleThree,
    ExampleFour: ExampleFour,
    ExampleFive: ExampleFive
});

export default RootStack;

Is there anything wrong with my code? I'm following some tutorial but it's not work on me
Comment: Sorry, I wrote it wrong
ExampleTwo: ExampleTwo *
Answer: try to call the resources ExampleOne, ExampleTwo..etc, should not use the object {ExampleTwo} .. is unnecessary ..


union of infinitely many bounded sets is not bounded

Question: Why is a union of infinitely many bounded sets not necessarily bounded, please? In addition, what condition can we add to make this union bounded, please?
Comment: Can you give me an example of a bounded set (say, on the real line)? Can you see why a union of infinitely many of them might not be bounded?
Comment: $$\bigcup_{n=1}^\infty [-n, n] = (-\infty, +\infty).$$
Answer: $\mathbb{R}^n=\bigcup_{n=1}^{\infty} \{x\in\mathbb{R}^n:\left\|x\right|\leq n\}$
A finite union of bounded sets is bounded.
I hope this helps!
Answer: Each subset of a metric space is a union of bounded sets (the singletons) but not every subset is bounded.
Comment: Such a clever argument.
Answer: Since you're asking why it's not necessarily true that such a union is bounded, it suffices to consider a counterexample. Define $A_n = [n, n + 1]$; then
$$\bigcup_{n \in \Bbb{N}} A_n = [0, \infty)$$
is unbounded.
It is necessary and sufficient that there is a common bound on all the $A_n$ for the union of the $A_n$ to be bounded.
Comment: Thank you for your response.


Is there general formula for initial guess of Newton-Raphson method for finding roots

Question: A few days ago, we had quiz and I solved 3/4 of questions, and I realized that the 4th question which was mentioned as wrong. Question was

FIND THE SMALLEST POSITIVE ROOT BY USING NEWTON-RAPHSON METHOD,

I asked what's wrong with my solution, so I had an argument with my calculus teacher, about Newton's method of finding roots, specifically  about the initial guess
Example was this: $$\bf f(x)=\cos(3x) + x^3 -2$$
a root lies between 1 and 2
I said professor, that we can choose any points between them as initial guess $\bf x_0$ and had chosen 1.5, so solved.
But, professor said, that we can pick initial guess as following formula:

if f(a)f''(x) > 0 then x0 = a or
if f(b)f''(x) > 0 then x0 = b,

I don't really know where she got these conditions, but I didn't reply he mail after this.
I searched google about 2 hours and I DIDN'T FIND any result like that. So, I wanted to ask you, who is right here? Me or her? Are we free to choose initial guess as we want, or we have to follow her instructions where it doesn't exist in real life? Or, I wrong, because even in wikipedia, there is no any info's about initial guess.
Comment: This is Darboux theorem  http://www.numdam.org/article/NAM_1869_2_8__17_0.pdf
Comment: Looking at the graph, $1.5$ is a decent guess, and it also falls under this criterion for a "good guess" that your teacher, the above comment and the below answer all give. So while it may not be the initial guess they were after, I personally really wouldn't want to call it _wrong_.
Comment: do you mean `good guess tha*n* your teacher`?
Comment: @MerdanKurbanow No, I mean "that". Syntactically simplified, the phrase says "the criterion that all those people give".
Comment: so, fact is, the criteria was not given. Teacher said that I needed to enter online classes to knew that.
Answer: There is some very common exercise about the Newton method that guarantees convergence in the scalar case.
Consider as base case the one where the function has a sign change and is convex and increasing on the interval $[a,b]$.
Then the tangent $t_a(x)$ at $a$ (function value negative) could be almost horizontal, it could have a root almost anywhere, also outside of the interval. As an example consider $f(x)=x^2+0.1x-0.5$ on the interval $[a,b]=[0,1]$. The tangent in $a=0$ is $t_a(x)=0.1x-0.5$ and has its root $x=5$ well outside the interval. The tangent at $b=1$ is $t_b(x)=2.1(x-1)+0.6$ with its root at $x=\frac57$ inside the interval.
However, the tangent $t_b(x)$ at $b$ (function value positive) is more restricted in its slope and $x$-intercept. It is a supporting line of the convex curve, as is every tangent, thus always below it. Which means that at $a$ the tangent must have a negative value, $t_b(a)\le f(a)<0$, and thus its root $c$ is between $a$ and $b$, inside the interval.
The function value $0=t_b(c)\le f(c)$ at the root of the tangent has to be positive (or $c$ is already the root of $f$), so $b$ can be replaced with this root. The reduced interval $[a,b']=[a,c]$ now satisfies the same conditions. Repeating this observation gives a falling sequence of Newton iterates inside the interval converging to the root.

The other sign combinations of the first and second derivative (concave curve, falling curve) can now be obtained by reflections on the $x$ and $y$ axis, leading to the condition your teacher gave.
Comment: I searched for Darboux theorem on wikipedia, and it doesn't have any conditions for initial guess
Comment: @MerdanKurbanow If these conditions and not satisfied you cannot, in general, guarantee convergence... in fact, you can construct examples for which Newton's method will fail. However, if $|f(a)|/|f'(a)| < b-a $ and $|f(b)|/|f'(b)|  0, then x0 = b. The fact is, this hint was not given in the question, so I started with 1.5, and answer I got on 2nd iteration was different than x0=2 starting point. So, im saying that, doesn't matter which you choose as guess point, and from that depends other iteration answers.
Comment: Yes indeed, in this example the iteration will stay inside the interval for any initial value. However you can construct easily examples where you go outside the interval from the wrong initial point, like $f(x)=x^2+0.1x-0.5$ for $[a,b]=[0,1]$.


Regex extrair substring de texto delimitada por um padrão de fim que se repete no texto (STARTtextoFIM STARTtextoFIM)

Question: Tenho como objetivo realizar a extração da substring delimitada por ENTER e Tempo de viagem total:4h 05m no texto abaixo:
Para isso construi a seguinte expressão regular: ENTER[\S\s]+Tempo de viagem total:.*h .*m (geral pra funcionar em qualquer texto)
Contudo quando efetuada a extração no texto abaixo :
ENTERAZUL Linhas Aereas Brasileiras - 4884
ENTERAerospatiale/Alenia ATR 72
ENTERFev
ENTER1
ENTERBauru, SP, BR
ENTERSao Paulo, SP, BR
ENTER19:50JTC
ENTER20:50VCP
ENTERMoussa Nakhl Tobias Airport
ENTERViracopos International Airport
ENTER1h 00m
ENTEReconômica
ENTERExecutiva
ENTER1h 25m escala · Sao Paulo, SP, BR
ENTERAZUL Linhas Aereas Brasileiras - 4663
ENTERUnknown Aircraft
ENTERFev
ENTER1
ENTERSao Paulo, SP, BR
ENTERBrasilia, DF, BR
ENTER22:15VCP
ENTER23:55BSB
ENTERViracopos International Airport
ENTERBrasilia International Airport
ENTER1h 40m
ENTEReconômica
ENTERExecutiva
ENTEREmissões de CO2:econômica/Econômica "Premium": 154kg
ENTERExecutiva: 195kg
ENTERTempo de viagem total:4h 05m
ENTERAZUL Linhas Aereas Brasileiras - 4399
ENTERUnknown Aircraft
ENTERFev
ENTER5
ENTERBrasilia, DF, BR
ENTERSao Paulo, SP, BR
ENTER05:25BSB
ENTER07:05VCP
ENTERBrasilia International Airport
ENTERViracopos International Airport
ENTER1h 40m
ENTEReconômica
ENTERExecutiva
ENTER2h 25m escala · Sao Paulo, SP, BR
ENTERAZUL Linhas Aereas Brasileiras - 4530
ENTERAerospatiale/Alenia ATR 72
ENTERFev
ENTER5
ENTERSao Paulo, SP, BR
ENTERBauru, SP, BR
ENTER09:30VCP
ENTER10:35JTC
ENTERViracopos International Airport
ENTERMoussa Nakhl Tobias Airport
ENTER1h 05m
ENTEReconômica
ENTERExecutiva
ENTEREmissões de CO2:econômica/Econômica "Premium": 154kg
ENTERExecutiva: 195kg
ENTERTempo de viagem total:5h 10m

O match do delimitador final da substring é feito com Tempo de viagem total:5h 10m ao invés de Tempo de viagem total:4h 05m resultando na não separação do texto, como se a busca do delimitador final estivesse sendo realizada do fim do texto para o começo.
Existe alguma forma de realizar este tipo de busca em texto procurando pela primeira ocorrência do delimitador final ? (neste exemplo primeira ocorrência de Tempo de viagem total:.*h .*m )
Estou utilizando o site https://regexr.com/ para testar
Answer: Primeiro, uma explicação sobre [\S\s]: este é um "truque" conhecido para pegar "qualquer caractere". Geralmente usa-se o ponto para "qualquer caractere", mas por padrão, o ponto não considera quebras de linha, então [\S\s] acaba sendo uma alternativa, pois ele pega \s (um atalho para espaços, TABs, quebras de linha, entre outros caracteres) e \S (tudo que não é \s). Ou seja, [\S\s] pega qualquer caractere, incluindo quebras de linha.
Já o quantificador + significa "uma ou mais ocorrências", mas por padrão, os quantificadores são "gananciosos" e tentam pegar a maior quantidade possível de caracteres. E qual a maior quantidade possível de caracteres que logo depois tem o Tempo de viagem total etc...? A string inteira, por isso ele pega até o 5h 10m.
Uma maneira de resolver é tornar o quantificador + "preguiçoso", colocando um ? na frente: [\S\s]+?. Assim, ele pega a menor quantidade possível de caracteres, neste caso, indo até o 4h 05m.
Outro detalhe é que você está usando .*h .*m, mas .* significa "zero ou mais caracteres", o que significa que ele também pegaria coisas como h m ou abch xyzm. Se quer restringir para apenas números, pode usar \d+h \d+m (d+ significa "um ou mais dígitos"), ou se quiser controlar a quantidade, pode usar \d{1,2}h \d{1,2}m (no caso, \d{1,2} significa "no mínimo 1, no máximo 2 dígitos"). Assim você garante que deve ter pelo menos um dígito.
Pode até ser que "funcione" com .*, mas muitas vezes você não quer "qualquer coisa", e sim algo mais específico (neste caso, me parece que apenas dígitos seriam válidos, então não é "qualquer coisa"), e em regex é melhor ser específico com relação ao que você quer e também ao que não quer.
Resumindo, a regex ficaria ENTER[\S\s]+?Tempo de viagem total:\d+h \d+m.

No caso de sites como o RegExr, você também poderia usar o ponto em vez de [\S\s], e habilitar a flag single line:

Assim, o ponto também considera quebras de linha (veja aqui), substituindo o [\S\s]. Neste caso, a expressão ficaria ENTER.+?Tempo de viagem total:\d+h \d+m.

Para entender melhor sobre quantificadores gananciosos ("greedy") e preguiçosos ("lazy"), leia aqui, aqui e aqui.

Vale lembrar que este problema seria - na minha opinião - mais fácil de resolver sem regex, usando alguma linguagem de programação. Assim você poderia ler linha a linha, ver se ela é o início de um registro ou o final (se ela contém "Tempo de viagem total", por exemplo), e ir concatenando as linhas em um único registro. Regex nem sempre é a melhor solução.
Answer: Nesse caso, faltou apenas inserir o ponto de interrogação logo após o sinal de mais:
ENTER[\S\s]+?Tempo de viagem total:.*h .*m

Isso faz que o motor de busca avalie sua expressão no modo lazy, ao invés do modo greedy.
Assim, caso vc queira obter todas as matches (2 no caso do texto compartilhado), use a flag global na sua expressão. Caso queira apenas a primeira match, não use a flag global.


php_error: Cannot use positional argument after named argument

Question: $name = explode( separator: '.', $name );
enter image description here
Here is where my code is wrong. I tried to separate the image name from the image extension but it gives an error, but I think the format of the code is correct, so what is the problem here?
Comment: You may be getting confused by your IDE automatically showing you the name of argument variables.
Answer: You do not need to add separator: in the explode statement.
So just use the following:
<?php

$name="test.jpg";
$name = explode('.', $name );

//filename (without extension)  (for xxxx.xxxx)
echo $name[0];
echo "
";

//extension of the filename (for xxxx.xxxx)
echo $name[1];
?>


Intuition behind the definition of initial morphism and embedding as stated in Joy of Cats

Question: In Definition 8.6 of Joy of Cats the authors write (I have changed the wording to avoid explaining the conventions that the authors introduce earlier which would lengthen the post unnecessarily),

Let $(\mathbf{A},U)$ be a concrete category over $\mathbf{X}$ (i.e, where $\mathbf{A}$ is a category and $U:\mathbf{A}\to\mathbf{X}$ is a faithful functor).

An $\mathbf{A}$-morphism $A\overset{f}{\to} B$ is called initial provided that for any $\mathbf{A}$-object $C$ and for the $\mathbf{X}$-morphism $U(C)\overset{g}{\to} U(A)$ there exists a unique $\mathbf{A}$-morphism $C\overset{g^\ast}{\to} A$ such that $U(g^\ast)=g$ whenever for the $\mathbf{X}$-morphism $U(C)
\overset{U(f)\circ g}{\longrightarrow} U(B)$ there exists a unique $\mathbf{A}$-morphism $C\overset{h^\ast}{\to} B$ such that $U(h^\ast)=U(f)\circ g$.
An initial morphism $A\overset{f}{\to} B$ for which $U(f)$ is a monomorphism is called an embedding.

My questions are,

What is the reason for calling the for calling the $\mathbf{A}$-morphism initial in (1) of the above definition?
What would be the problem if we would simply define an embedding as follows,

2.$^\ast$  An morphism $A\overset{f}{\to} B$ for which $U(f)$ is a monomorphism is called an embedding.

I thought that an answer to (1) could be found by showing that the morphism $f$ is the initial object of some suitable category. But footnote 45 confused me where it is written that,

"Notwithstanding their names, the concepts of initial object and initial morphism are unrelated."
Comment: I think these were my thoughts: First of all, being initial in this sense is a property which boils down to representing a certain functor, and this is initial in the usual sense for the category of elements of said functor. I am not sure if I will find the time to make this an answer any time soon, but you can try to put things together by yourself...
Comment: It may be helpful to scroll down a bit to the examples in 8.8. In particular "a continuous map $f: (X, \tau) \to (Y, \sigma)$ is initial if and only if $\tau$ is the 'initial topology' with respect to $f$ and $\sigma$". $\mathbf{Top}$ also provides the motivation for the terminology "embedding".
Comment: Your link in the first sentence does not seem to work as intended.
Comment: @SCappella: But I still don't understand why the morphism is called **initial**. Is it merely a suggestive terminology because only due to the motivating terminology or there is some really deep categorical fact hidden behind choosing this terminology. For example, if we could prove that the initial morphisms are precisely the initial objects of some category whose objects are $\mathbf{A}$-morphisms then we can "naturally" call them "initial" morphisms.
Comment: Regarding "embedding", a bit earlier the authors write, "Below, we introduce the concept of *embedding*, which agrees with the intuitive notion of "embeddings of subobjects" in every familiar construct." Does this mean that if we don't take the morphism to be initial then we can construct an example of a construct (no pun intended!) in which the notion of embedding (as defined in 2$^\ast$ will not correspond to that intuitive notion we have)? If so can you provide an example?
Comment: Isn't this also initial in the full sub-category of the slice $\mathbf A/B$ consisting of those morphisms $g\colon C\to B$ such that $|g|\colon |C|\to |B|$ factors though $|f|$?
Comment: @Ben: If it's possible then can you provide an answer elaborating this comment?
Answer: I'll sum up my comments (and response to your comments) in an answer.

The definition of initial is chosen to generalize the situation where $\mathbf{A}$ is $\mathbf{Top}$ and $U$ is the forgetful functor to $\mathbf{Set}$. A function $f: X \to UY$ (where $Y$ is a topological space) induces a topology on $X$, called the initial topology, which is the "smallest topology that makes $f$ continuous". This, at least a priori, has nothing to do with initiality in the sense of category theory. I suppose there's a vauge connection with categorical initiality here. Letting $T_f$ be the poset of topologies for which $f$ is continuous (ordered by inclusion), the initial topology is the initial (i.e. minimal) object in this poset (thought of as a category in the usual way). That's a bit of a tenuous connection, though. I'm inclined to trust the authors of ACC and say there's no real relationship between the two notions. It certainly wasn't their intention.
Embeddings are, at least in topology, thought of as morphisms that are homeomorphisms to their image. If you dropped the initiality condition, the "embeddings" would simply be injections. So for example, for a given topological space, the inclusion of the underlying discrete space into the original space is an injection, but not an homeomorphism to its image (i.e. the original space) unless the original space is discrete.

Again, look through the examples in 8.8 to see how this definition of embedding works in other cases, like $\mathbf{Haus}$, $\mathbf{FHaus}$, $\mathbf{Ban}$ and $\mathbf{Met}$. You'll see that it matches up with the usual choice in most cases. These ideas are further explored in Chapter VI with topological categories.
Answer: As asked for in the comments, here is what I've been thinking. I've been a bit too optimistic and this turns out to be more subtle than I initially thought.
As a slogan, I think we can say that

the concept of initiality in a concrete category is actually a nice example of a terminal object (instead of an initial one), but
the initiality condition is (in some sense) stronger than the (non-trivial version of the) terminality-property.

Of course, a terminal object of some category is an initial object of the opposite category, but this shouldn't count here if you ask me.
Let me fix a setup and some terminology for convenience: We have a faithful functor $|\cdot|\colon A\to X$ which allows us to consider $A$-morphisms as (certain) $X$-morphisms. That is, up to an isomorphism of categories, we can and will assume that $A(a,b)\subset X(|a|,|b|)$.
Let $f\colon a\to b$ be an $A$-morphism. It is called initial if and only if the following holds: for every $c\in A$, an $X$-morphism $|c|\to |a|$ is actually an $A$-morphism $c\to a$ (i.e., an element of the subset $A(c,a)\subset X(|c|,|a|)$) if and only if the composite $|c|\to |a|\to |b|$ is actually an $A$-morphism $c\to b$.
From here, I see two ways to go: Either, we may ask if $f\colon a\to b$ is in some sense initial or terminal in some arrow category, or (motivated by the initial topology), we may forget $a$ itself and only remember $b$, $|a|$ and the $X$-morphism $f\colon |a|\to |b|$, since the defining property is actually independent of $a$. I will concentrate on the latter part, mentioning the former idea only shortly at the very end.
To formulate the idea more precisely, let $b$ be an object of $A$, $x$ an object of $X$ and an $X$-morphism $f\colon x\to |b|$. (Think $x = |a|$.)
Let me define a lift of $x$ compatible with $f\colon x\to |b|$ to consists of an object $c\in A$, together with an $X$-morphism $\varphi\colon |c|\to x$ such that the composite $f\circ \varphi\colon c\to b$ is an $A$-morphism.
The $f$-compatible lifts of $x$ form a category, where a morphism $(c,\varphi)\to (c',\varphi')$ consists of an $A$-morphism $g\colon c\to c'$ such that $\varphi'\circ g = \varphi$.
Here is the upshot:
Proposition 1 – An $A$-morphism $f\colon a\to b$ is initial if and only if $a$, together with the identity map $\mathrm{id}\colon |a|\to |a|$, is terminal in the category of lifts of $|a|$ compatible with $f\colon |a|\to |b|$.
Proof:
Note that $f\colon a\to b$ is initial if and only if $A(c,a) = \{g\in X(|c|,|a|)\mid f\circ g\in A(c,b)\}$ for every $c\in A$. On the other hand, consider the sub-functor $F\subset X(\cdot,|a|)\colon A^{op}\to(Set)$ mapping $c$ to $\{g\in X(|c|,|a|)\mid f\circ g\in A(c,b)\}$. It's category of elements is the opposite of the category of $f$-compatible lifts of $|a|$. Therefore, $f\colon a\to b$ is initial if and only if $A(\cdot,a) = F$, which is the case if and only if $(a,\mathrm{id}_{|a|})$ is initial in the category of elements of $F$, i.e., if and only if it is terminal in the category of lifts of $|a|$ compatible with $f$, as claimed.
Alternative, more elementary proof: Suppose that $f\colon a\to b$ is initial and let $(c,\varphi)$ be any lift of $|a|$ compatible with $f\colon |a|\to |b|$. That is, $\varphi\colon |c|\to |a|$ is such that the composite $f\circ \varphi\colon |c|\to |b|$ is actually an $A$-morphism $c\to b$. By assumption, this implies that $\varphi$ is actually an $A$-morphism $c\to a$ which is in fact the unique morphism $(c,\varphi)\to(a,\mathrm{id}_{|a|})$. Conversely, if $(a,\mathrm{id}_{|a|})$ is terminal, and if $h\colon |c|\to |a|$ is any morphism such that $f\circ h$ is an $A$-morphism $c\to b$, then $(c,h)$ is an $f$-compatible lift of $|a|$ and so there is a unique $A$-morphism $g\colon c\to a$ such that $\mathrm{id}_{|a|}\circ g = h$. Therefore, $g = h$ is an $A$-morphism, as desired.
Proposition 2  – An $A$-morphism $f\colon a\to b$ is initial if and only if the category of lifts of $|a|$ compatible with $f$ has a terminal object $(c,\varphi)$ such that $\varphi$ is an $X$-isomorphism.
Proof. Proposition 1 proves one implication. Conversely, suppose that $(c,\varphi)$ is terminal where $\varphi\colon |c|\to |a|$ is an $X$-isomorphism. Since $(a,\mathrm{id}_{|a|})$ is a lift of $|a|$ compatible with $f$, there is a unique $A$-morphism $g\colon a\to c$ such that $\varphi\circ g = \mathrm{id}_{|a|}$, so that $\varphi^{-1} = g$ is an $A$-morphism. Therefore, $\varphi$ is an isomorphism $c\cong a$ over $b$. Thus, $(a,\mathrm{id}_{|a|})$ is itself terminal in the category of $f$-compatible lifts of $|a|$ and the rest follows from Proposition 1.
It can also be shown:
Proposition 3 – Let $f\colon x\to |b|$ be an $X$-morphism where $b$ is an object of $A$. Suppose that $(c,\varphi)$ is a terminal lift of $x$ compatible with $f$, where $\varphi$ is a monomorphism. Then $f\circ \varphi\colon c\to b$ is an initial $A$-morphism.
Right now, I cannot come up with an example where $\varphi$ is not a monomorphism. (Anyone?) But one where it is not an isomorphism is easy to find. For example, let $X = (Set)$, $A = (Grp.)$ with the obvious forgetful functor, $b = (\mathbb Z,+)$ and $x = \{0,1\}$. Then $c = (\{0\},+)$ and $\varphi\colon |c| = \{0\}\to \{0,1\} = x$ is the inclusion and certainly not surjective. Nonetheless, the inclusion $c\to b$ is of course initial.

As promised, here is a short remark concerning terminality of $f$ itself instead of $a$:
Trivially, $f$ is a weak terminal object in the full sub-category of the slice $A/b$ of those morphisms which factor through $f$. If $f$ is an initial morphism, then this category has another description, yet again relying only on $|a|$ and $f\colon |a|\to |b|$, yielding the following:
An initial morphism $f\colon a\to b$ is weakly terminal in the full sub-category of $A/b$ consisting of those morphisms $c\to b$ such that such that the underlying $X$-morphisms $|c|\to |b|$ factors through $f\colon |a|\to |b|$. But this doesn't seem to uniquely define $a$ or the initiality of $f$.


use corrected or uncorrected variance when calculating skewness & kurtosis?

Question: In several online sources, e.g. NIST engineering statistics handbook I have read that for the calculation of skewness & kurtosis I should use N in the denominator instead of (N-1) when calculating the variance.
However the programming language I work with (IDL) has (N-1) there (see moment function of IDL).
This seems copied from Numerical Recipes, pp 722-724.
Which is correct? Just to be sure before I submit an error report.
Wouldn't the unbiased estimators be even more complicated?
Comment: Do you really need an unbiased estimate?  Or are you computing these measures for some other purpose, such as describing data or testing the shape of their distribution?
Comment: I don't need an unbiased estimate. But when submitting an error report it would be useful to have a confirmation, that what IDL does is neither correct for the biased nor the unbiased form.
Comment: I don't understand what you mean by "neither correct."  In what sense could one evaluate "correctness" in the absence of a clearly stated purpose?
Comment: While something being correct depends on the context, some things are wrong in all or at least most practical purposes. A function delivered with a programming language should deliver meaningful results for most practical purposes. - Shouldn't there be a definition for biased and for unbiased estimates? makes 2 correct solutions, all else false (ok, +-3 in case of Kurtosis, makes 4 correct solutions)
Comment: Actually, there are far more "correct" solutions than that.   The problem is that bias often is just a small part of the potential error in any estimator.  Thus, one cannot maintain that "correct" implies "unbiased."  This consideration opens the field to infinitely many possible kurtosis estimators. You're doing well to investigate and understand what your programming language does, but is there any need to go further?  Either use what it offers, apply an adjustment to its results, or code your own if you need something different.
Answer: Kurtosis is equal to $E(Z^4)$, where $Z = (X-\mu)/\sigma$. (Subtract 3 if you want, it doesn't matter).
If you apply this formula to the empirical probability distribution of the data, where you put $1/n$ probability on each distinct observation $x_i$ (and collate probabilities for the repeats), then you get the following estimate of kurtosis:
$\hat{k} = (1/n) \sum_{i=1}^n \{(x_i - \bar{x})/\hat{\sigma}\}^4$, where $\hat{\sigma}^2 = (1/n)  \sum_{i=1}^n (x_i - \bar{x})^2$.
This logic suggests using the $n$ formula for variance rather than the $n-1$ formula.
I am not saying that this formula gives the best estimator. Rather, I am saying that there is a consistent logic to this estimator, because it uses the same formula as for any other probability distribution.
I would be interested in knowing how this estimator compares to others, in terms of mean squared error, mean absolute error, and median absolute error, if someone has some research they would like to share with the community.


Creating setup for windows 10 machine using visual studio 2010

Question: I have tried to create a setup file for a web application using Visual Studio 2010. When I tried to install the setup in windows 10 machine, I recieve the error message as

This setup requires IIS 5.1 or higher and windows xp or higher.
This setup cannot be installed on windows 2000
Please install IIS or a newer OS and run the setup again

Is there any solution to overcome this scenario? I want to know whether this can be done using VS2010 or not? What is the best alternative if the answer is NOT?
Answer: Do waht most sensible installer people do - forget the idiotic behavior the (way long retired) vs included stuff does.
Use WIX / the WIX toolset (http://wixtoolset.org/)
THAT SAID: 2010 is ancient and you really should consider at one point going to a SUPPORTED VERSION of visual studio. Can not even say whether WIX is supported on a THAT ancient version of Visual Studio. Time to upgrade - particularly as it will likely be free for you.
Answer: I am guessing that you're using the ClickOnce / Publish / vdproj or similar.
There is a "LaunchCondition" check in the vdproj file / deployment project which checks for the IIS version.
This link guides you to the location for some set-ups and has some useful ideas:
https://secureinfra.blog/2014/06/11/getting-error-this-setup-requires-internet-information-server-5-1-or-higher-and-windows-xp-and-higher-when-installing-setup-project-on-windows-server-2008-and-iis-7/
I found mine in the .vdproj file
The location of the IIS version in the registry has moved, so I changed my coding to:
<code>"Condition" = "8:IISMAJORVERSION >= \"#10\""
</code>
and the RegKey to search for IISMAJORVERSION as:
<code>"RegKey" = "8:SOFTWARE\\Microsoft\\InetStp"
</code>


CentOS 6 - Kernel 3 from CentOS 7 Repo?

Question: i want to run kernel 3 on centos 6. I found out, that it cant get installed over yum and i would need to compile it by my own.
My question: Could i use the centos 7 repo to install kernel 3.x from there? I cant find out the correct repo file for centos7, i would need to hardcode the variables but i dont know the value:

mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os

Would i can install Kernel 3 from CentOS 7 repo?
Comment: I would recommend not installing a CentOS 7 package on a CentOS 6 system. Going the other way is more acceptable, but I still wouldn't want to do it myself.
Comment: I'm pretty sure people have 3.x kernel already compiled for your version&architecture. You may wan to try OVH's 3.10 ftp://ftp.ovh.net/made-in-ovh/bzImage/
   I wouldn't want to use CentOS 7's because of systemd(but i may be confusing everything)
Answer: This is highly not recommended because it changes a basic building block of the distribution and will certainly create unpredictable behavior in your system. If you want to do it for fun, compile the kernel from scratch (there are many tutorials showing how to do that).
My suggestion is to use CentOS 7 which offers kernel 3.x thoroughly tested with all the other components. You can take advantage of the fact that CentOS 6->7 is the first supported upgrade path.
Answer: To get a recent long-term support kernel purpose-built for CentOS 6, consider using kernel-lt from ELrepo.

CentOS 6 - Kernel 3 from CentOS 7 Repo?


Nome no index de um array

Question: Preciso criar um array ou objeto, mas com nome/index dinâmico, tipo este do exemplo, porém o nome deve vir de uma variável:
var1 = "testeIndex";

var obj = {
    var1 : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
    var2 : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
    var3 : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
};

Porém, quando boto o nome da variável, mesmo sem aspas, o index recebe o nome literal da variável.
É possível fazer o que estou tentando fazer?
Answer: Tente com
var obj = {
    [var1] : {
        // ...
    }
}

Referência:
https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript
Segundo o link, essa notação é suportada a partir do ECMAScript 2015.
Em versões anteriores é necessário construir o objeto passo-a-passo, com:
obj = {};
obj[var1] = { /*...*/ };
// etc.

Ver também:
Compatibilidade com navegadores: (é a linha Computed property names)
Comment: Seria legal inserir informações sobre compatibilidade, como por exemplo a sessão [Browser Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Browser_compatibility) da MSN (é a linha _Computed property names_)
Comment: Deu certo, obrigado!

Nome no index de um array


Is it necessary to learn php in order to use drupal to manage my site?

Question: I am planning on using Drupal to manage a website. Should I learn PHP because I understand Drupal is built on PHP language?
I don't know PHP and I am not planning to learn it, but I have decided to use Drupal as my CMS, will I still efficiently manage my geospatial data handling site?
Comment: There's plenty of modules that can be used from a GUI, and you'll be able to do most things with that. The difficulty is, when a module provides 95% of the functionality you want, and the remaining 5% are really important to you. Then someone needs to implement the those 5%. Of course, you can always pay someone for that.
Comment: Drupal has a well built admin interface using which you could manage and create most of the site. You might need to learn php if you want to granular customizations for which you might end up writing a custom module of your own.
Comment: All depends on what you plan to do. If you would ask more precise questions, you could get better response here.
Comment: Hi, please don't fundamentally change a question once it's been answered. It invalidates existing answers and just isn't what we do here. If you have extra information, _add_ it to the question rather than removing the original intent. I've rolled back the changes. Thanks
Comment: If my comment suggested that radical edit, then I'm sorry. I only wanted to provide explanation, not suggest a course of action.
Answer: No, it's not "necessary". Drupal core has a UI to perform its basic functions, as do most contributed modules.
Beyond that, it's totally up to you to say whether you need to learn PHP, based on the level of customisation you need in your site
If all the functionality you'll ever need can be provided through the UI of whatever modules you decide to use, then no, you won't need to learn PHP. If all of that functionality isn't provided "out-of-the-box", then yes, you'll need to learn PHP.
As with anything, your mileage will vary. The only possible way to answer this question properly is for you to get stuck in and try it out for yourself.


Zend Plugin works only in one module

Question: I have created a plugin, that ckecks authorization status and gives access for using application. This plugin works fine, but in whole project. I want to make it works only in admin module. How can I do this?
I have defined plugin in application.ini:
resources.frontController.plugins.authcheck = Application_Plugin_AuthCheck

Thanks for your help.
Answer: One way:
admin.resources.frontController.plugins.authcheck = Application_Plugin_AuthCheck

Second way:
check in plugin module's name:
if ($this->getRequest()->getModuleName() == 'admin') {
    //process
}

Zend Plugin works only in one module


Can't get logbacks TimeBasedRollingPolicy running

Question: I can't get this snippet running:
TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setFileNamePattern("%d{yyyy-MM-dd}.log");
rollingPolicy.start();

Whatever pattern I try, I keep getting
Caused by: java.lang.IllegalStateException: FileNamePattern [%d{yyyy-MM-dd}.log] does not contain a valid DateToken
    at ch.qos.logback.core.rolling.TimeBasedFileNamingAndTriggeringPolicyBase.start(TimeBasedFileNamingAndTriggeringPolicyBase.java:46)
    at ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy.start(DefaultTimeBasedFileNamingAndTriggeringPolicy.java:32)
    at ch.qos.logback.core.rolling.TimeBasedRollingPolicy.start(TimeBasedRollingPolicy.java:90)

I've tried various examples from the docs, but what works in logback.xml doesn't seem to work in code.
Answer: According to this: https://github.com/tony19/logback-android/issues/51 you need a context and an appender. There is an example there.
Comment: In other words, call `rollingPolicy.start();` later