Is it safe to use velcro Command strips on the inside of the body of an acoustic guitar?

Question: I recently purchased a used Taylor 214ce-SB DLX.  Since Taylor guitars do not come with an on-board tuner, I'm looking for a way to discreetly place a tuner somewhere on the guitar, and a potential solution is inside the soundhole, using something such as the Korg RP-C1 Rimpitch Chromatic Acoustic Guitar Tuner.  The problem is that I'd rather not have the clip showing on the front of the guitar's body.
So, I'm wondering if it would be safe to attach the tuner to the inside of the body near the soundhole using Command Picture Hanging Strips (or something similar, preferably with velcro).
Is there any chance of a Command strip damaging the wood?  Considering that I'd be using it on a guitar and not a wall, would using the proper removal method be safe if I'd end up needing to completely remove the tuner?  (Also, is there any chance of installing a tuner in the way that I've described having a negative effect on the guitar's tone?)
Answer: Based on a long history of using industrial-grade self-adhesive velcro [I kid you not] & comparing that to 'what is needed so you can remove an adhesive without damaging wallpaper'
It will fall off in the first 5 minutes of use.
Avoid.
To better explain...
The 'no damage wallpaper' system relies on the force being vertical to a long strip of very poor adhesive - no movement, no off-axis force.
First time you pull in the 'wrong' direction, it will come unstuck... intentionally.
Good for wallpaper, not good for your performance.
Trying to fish your rattling tuner out of the guitar mid-gig is not going to be amusing for anyone except the audience ;-)
Comment: You changed the ref tuner in your question, but I'd  say 'just use the clip mechanism it was designed with'.
Comment: In that case, is there any type of adhesive that you might recommend that would work better?
Comment: What do you think about installing the D'Addario Clip-Free Tuner (amzn.to/2qp35Oi) using a velcro Command strip instead of a screw (I think that my Taylor's tuning machines don't have screws in the rear, so I wouldn't be able to install it the normal way)? That way, I wouldn't have to worry about putting something inside the soundhole, and it would be potentially easy to remove the tuner (because Command strips are removable) if I ever needed to. I also think that that tuner would be light enough (it's just 1.28oz) to not come unstuck eventually.
Answer: Do NOT put any velcro strips on the sound board or you risk darkening the sound and reducing your sustain.
If I were you, I'd just get a snark tuner and clip it on the head stock. They're great. Highly visible, responsive, and you don't have to mar your guitar. Also, you can keep the tuner if you ever sell the guitar.
Comment: It's interesting that you say that. I ended up ordering the Shadow Sonic Tuner (https://amzn.to/2qpp4o5), which mounts using velcro.  In various places online, people have given it good reviews, with no mentions (that I've seen) of it affecting the sound or sustain at all.  Plus, Epiphone has a special offering that tuner for free during its "Epiphone Acoustic Month" (https://bit.ly/2Ht8VoY), so it seems like whoever made the decision to introduce that special doesn't share your concerns.  Could you explain more about how mounting a tuner with velcro would have any actually noticeable effects?
Comment: I just found a post on Acoustic Guitar Fourm that specifically mentions how mounting with velcro "has negligible effect on top vibration" (https://bit.ly/2JBchaa). Obviously, the poster is just a random guitar player posting in an online forum. Still, I'm intrigued that the claim basically directly contradicts what you said. I'll be quite interested to hear what you have to say in terms of how the velcro would be detrimental! (I'll also be asking a guitar technician about this when I go in for a setup once the guitar arrives in the mail.)
Comment: Operative words are *noticeable* and *negligible.* I cannot imagine defiling my Martin w/velcro or tape on the soundboard. But I'm just a random guitar player posting in an online forum too. The sound of an acoustic guitar comes primarily from the vibration of the soundboard and attaching anything weighing 2.4 ounces seems like it'll dampen the vibrations.  That shadow tuner is WAY over priced IMHO and it seems silly to put it in that awkward spot. What happens when it falls off inside? Or you need to put in a [pickup](https://www.amazon.com/Dean-Markley-Acoustic-Guitar-Pickup/dp/B0002M6R3U).
Comment: @1dareu2mov3 Also note that the snark is lighter (just weighed mine at 1.2 ounces) and only costs $10 -- free delivery with amazon prime.
Comment: Yeah, that's why I'll definitely ask about it when I go in for the setup. If the guitar tech mentions anything at all negative about the tuner, I'll return it right away! Your concerns do seem potentially warranted, so I'll let you know what I learn. As for the price - yeah, it's probably more expensive than it should be, but other than the similarly-priced Wittman MiniTurner (https://bit.ly/2v5MwLW) and the D'Addario Clip-Free Tuner (https://amzn.to/2qp35Oi), which won't work with my headstock, it's the only tuner I've found that's completely hidden from a front-on view of the guitar.
Comment: Regarding the Snark tuner that you mentioned, I've considered a tuner like that, but I just don't like the look of a tuner left clipped-on to the headstock (and I'd prefer to leave it on pretty much permanently).
Comment: Your aesthetic decisions are entirely up to you! I would point out that you can always un-clip the snark and put it aside if you need to.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/75865/discussion-between-1dareu2mov3-and-s-imp).


Is it okay to play something off the key in a track?

Question: I recently saw the guitar tabs of a For a better day by Avicii and found out that C# chord is played in the interlude though it is not a part of the F Maj key(The key of the song). I am very new to music and I want to know if it's okay to find something off the key or should I remain in the key when making my own tracks??

Link:https://tabs.ultimate-guitar.com/tab/avicii/for-a-better-day-chords-1763071
Also if you have time, give me feedback on this idea that I recently created:
https://drive.google.com/file/d/1FKCxxIEdxeQ6fL2BPR0o-4HBxVK2Ne50/view?usp=sharing
Thanks.
Comment: "chords in the same key would always sound good": maybe not.  But what does "sound good" mean?  It depends on what you're trying to do.
Comment: You missed the A a couple of lines higher too !
Comment: He's kinda playing with D minor here, going between IV-V-I in F major and iv-V-i in D minor, heading into that extended vamp on the D minor chord. This isn't really an answer to the general question though, which, yeah, play any chord that sounds good.
Comment: (to be clear: i'm not sure avicii had any particular formalization of this in mind, i'm not sure he "knew" that he was kinda "dipping into" a related key; i think he just knew what he wanted his song to sound like and did that, dude had a phenomenal head for sound. "theory" in the sense of "thinking about and being able to deconstruct music" is extremely important, but academic eurocolonial theory is just one route to that)
Comment: So can I conclude that the chords in the same key would always sound good, but there are some other chords too which though not in the key of the song but will sound great too??
Answer: As long as your feeling of which chord is "home" doesn't change, you can use any chord and note in any key. And even if it changes, then the key changes, but that's perfectly OK too.
Comment: Or even simpler: you can use any chord and note you like.
Answer: I listened to the song and I'm not hearing anything but the Dm chord there.  Don't confuse bass activity with actual chords.  Sometimes things just like to move around-- they don't have to be analyzed harmonically.
Answer: It's so commonplace - and has been for centuries, to use non-diatonic notes (and harmonies/chords) in pieces that I'm surprised there are so many questions such as this on this site. (yes, it's a dupe).
The C♯ in question lasts for about one beat. It's getting from C to D chromatically.
There has never been any theory, rule, call it what you will, stating non-diatonics can't be or aren't used in any key.


Change a single string

Question: Just a quick and probably stupid question, but...
Basically, I wanted to play music again after years and years of not doing it, so I pulled out that old charango I have.
The first string was basically broken so I bought a new string (a guy at a music store sold me the one I needed) but now, few days later... I never had to do this so I'm afraid I don't even know how to do it.
See below some pics to show you what I have :

About the second pic, there is obviously a hole on both sides to put the string in.
I watched a few videos but I'm still insecure since it was never the same system, and I'm afraid to break something.
Thanks in advance for your kind help.
Answer: It's obviously a string for a guitar, not a chirango.
However, IF the hole is wide enough for the wound part to go through, you may be able to just thread the whole string through. It MAY just have too much winding on it, which will then poke out the wrong side of the bridge.
Plan B, go back to the shop, with your pics, and explain that what you need isn't what you have bought.
Plan C, if all fails, go to plan A, but use a small spacer so the string end gets moved further from the bridge.
A banjo string will probably do the next best job.
Comment: Hi, thanks for your answer !

It is indeed a guitar string ; the guy at the shop told me that they had no charango string but that guitar string could work, he seemed pretty confident about it. I went to the shop with my charango so he could easily see what I needed.

However, the little metal circle part definitely can't go through the hole, it is way too big.

Sadly I cannot go back to the shop for a while. I remember he told me something about putting the string into the circle thing, but unfortunately that was a quick explanation and I can't remember a lot of it.
Comment: There's a faint possibility you could use the 'little metal circle part' as he said, but that is the whole point in the arrangement, that it doesn't go through the small hole. If it did, it would be useless for anything! He meant tread it through the bridge hole, and back through the 'little metal cirle part'. It may work - I've done it in desperation, it depends how the windings react to the angle they're subjected to. I have an old guitar here that I did it to 6 yrs ago, and they're still on.
Comment: Alright, I might go back to the shop in a few days.
However, I was thinking about something that might be stupid too but I guess it is better to ask.
I've been watching videos about stringing guitars and I wondered if I couldn't just get rid of the "little metal circle part" to keep a "regular string" and just do like I saw in this video : https://youtu.be/mGO30uYiIaY?t=71
Wouldn't that work ?
Comment: With a bit of effort [screwdriver/pliers etc], you can remove the brass ball-end & just use the remaining loop as originally intended for that instrument. You might have issues with the wrapped length, but you might not ;)
Comment: I think I'll try that tomorrow.
What do you mean exactly by "issues with the wrapped length" ? If it's about the string length, it is much longer than needed
Comment: The "wrapped length" here means the 1/2-inch or so part near the metal ball where there are extra wrappings to secure the ball. That part is a little wider that the regular part of the string, and it must not be too wide to fit in the hole in the bridge. ... But looking at the existing strings, it looks okay to me if I'm judging the sizes accurately.

Change a single string


If $M$ is normal and $M \cap U = U'$ for some special subgroup $U$, then $M / G'$ is a Hall-subgroup of $G / G'$.

Question: Let $G$ be a finite group and $U \le G$ be a finite group of odd order. Suppose that $N_G(U) = TU$ where $T = \langle t \rangle$ for some involution $t \notin U$. Also suppose $U^g \ne U$ implies $U^g \cap U = 1$.

Assume $M \unlhd G$ such that $M \cap U = U'$ and $G' \le M$. Then $M/G'$ is a Hall-subgroup of $G/G'$.

How to show that? We have that $M/G'$ is a Hall-subgroup iff $\operatorname{gcd}(|M : G'|, |G : M|) = 1$. I guess the best might be to show that every Sylow subgroup of $M/G'$ is also a Sylow subgroup of $G / G'$, but here I am stuck and do not know how to proceed. So any help would be appreciated!?
Comment: If $P$ is a nontrivial Sylow $p$-subgroup of $U$ then $P \in {\rm Syl}_p(G)$ and by the Frattini Argument $G=N_G(P)UG'$. But $|N_G(P):N_U(P)| = 2$, so $|M/G'| \le 2$. So $M/G'$ has order $1$ or $2$, and it is a Hall subgroup of $G/G'$ but in a rather trivial fashion.
Comment: What are the conditions on $G'$? Is it just a normal subgroup of $G$ that is contained in $M$? If so, then it is enough to show for $G'=\{e\}$, but then you have no condition on $M$ other than it is normal in $G$. In any way, it seems that the group $G'$ is irrelevant for the proof.
Comment: @Prometheus: $G'$ (and similar $U'$) is the commutator subgroups, $G' = [G, G] = \langle [x,y] : x,y \in G \rangle$, and similar $U'$ is the group generated by all commutators made by elements from $U$.
Comment: ok, that makes more sense
Comment: @DerekHolt Thanks! Now I solved everything. But the computations to get to $|M/G'| \le 2$ were quite messy (see my answer at iii)), if you have any easier argument than mine I would be glad if you share it!
Answer: With Derek's comment I was able to solve it:
i) If $P \in \mbox{Syl}_p(U)$, then $P \in \mbox{Syl}_p(G)$.
Assume $P < Q$ for some Sylow $p$-subgroup of $G$, then as $P < N_Q(P) \le Q$ we can choose $g \in N_Q(P) \setminus P$. Then $P = P \cap P^g \le U \cap U^g$, hence as $P \ne 1$ we have $U = U^g$ and therefore $g \in TU$. As $g \notin U$ we can assume $g = tu$, but $tu$ has even order as $(tu)^2 \in U$.
A different way of seeing this: Consider the transitive action of $G$ on the right cosets of $U$ in $G$. As $Uxg = Ux \Leftrightarrow g \in U^x$ every $g \in G$ fixes at most two cosets. For assume $g \in U^x \cap U^y \cap U^z$ where $|\{U^x, U^y, U^z\}| = 3$, then $g^{x^{-1}} \in U \cap U^{yx^{-1}}$, hence $U = U^{yx^{-1}}$ and similar $U = U^{zx^{-1}}$. But $|\{ U, Uyx^{-1}, Uzx^{-1} \}| = 3$, and hence we would have three different cosets in $N_G(U)$, but this is not possible.
To see that the cosets are different, note that $Ux = Uy \Leftrightarrow yx^{-1} \in U$ implies $U^x = (U^{yx^{-1}})^x = U^y$ (or use $Ux = Uy \Leftrightarrow x^{-1}U = y^{-1}U$). So for example $U = Uyx^{-1}$ would give $U^x = U^y$ and similar for the others.
Now look at the orbits of $P$ on the cosets of $U$, as $P$ could fix at most two cosets, we have with $|P| = p^k$
$$
 |G : U| \equiv 1 \pmod{p} \quad\mbox{ or }\quad |G : U| \equiv 2 \pmod{p}
$$
and in both cases $|G : U|$ is not divisible by $p > 2$.
Note that by the equivalence of group actions and actions on cosets of some subgroup, in above terms we have shown that for three different points (the cosets), the point stabilizers corresponding to these points intersect trivially (the point stabilizers are the conjugates of $U$, as $G_{Ux} = (G_U)^x = U^x$ with common notation for stabilizers). Also note that by the condition that an element has just one fixed point is also excluded, as if $g \in U^x$, then $g^{x^{-1}} \in U = U^t$, hence $g^{x^{-1}}$ fixes also $Ut$.
ii) $G = N_G(P)UG'$ and $|N_G(P) : N_U(P)| = 2$.
As $G' \le UG'$ the subgroup $UG'$ is normal, and by i) in particular $P$ is also a Sylow subgroup of $UG'$, hence Frattini gives the first claim. As $1 \ne P\cap P^g$ implies $g \in N_G(U)$ we have $N_G(P) \le TU$. Now if $N_U(P) = U$, then $P$, as a characteristic subgroup in $U$, is normal in $TU$, hence $TU \le N_G(P)$. Otherwise we have some $u \in U$ not normalising $P$, which gives $UN_G(P) = TU$. Further $2 = |TU : U| \ge |TU \cap N_G(P) : U \cap N_G(P)| = |N_G(P) : N_U(P)|$ and by the remarks before we have $N_U(P) \ne N_G(P)$.
iii) $|M / G'| \le 2$ and $M/G'$ is a Hall subgroup in $G/G'$.
By similar arguments as in i) we have $G = UM$, hence
$$
 G / M \cong UM / M \cong U / (U \cap M) \cong U / U'
$$
and so $G/M$ is abelian, which gives $G' \le M$ (so this assumption could be dropped in the question) and $|G : M|$ is odd as $|U|$ has odd order.
Now
$$
 |M : U'| = |M : G'|\cdot |G' : U'|
$$
and
\begin{align*}
 |M : U'| & = |M : M\cap U| \\
          & = |MU : U| \\
          & \le |G : U| \\
          & = |N_G(P)UG' : U| \\
          & = |N_G(P)UG' : N_G(P)U||N_G(P)U : U| \\
          & = |G' : N_G(P)U \cap G'||N_G(P)U : U| \\
          & = |G' : N_G(P)U \cap G'||N_G(P) : N_G(P) \cap U| \\
          & = 2 \cdot |G' : N_G(P)U \cap G'| \\
\end{align*}
and we have $U' \le N_G(P)U \cap G'$ so that $|G' : N_G(P)U \cap G'| \le |G : U'|$. Taken together
$$
 |M : G'||G' : U'| \le 2|G' : U'|
$$
hence $|M : G'| \le 2$ and $|G/G' : M/G'| = |G:M|$ has odd order.


Raspagem de dados usando Robobrowser

Question: Estou tentando fazer a raspagem de um formulário, para inserir um anexo e enviar, usando o Robobrowser.
Para abrir a página eu faço:
browser.open('url')

Para pegar o formulário eu faço:
form = browser.get_form(id='id_form')

Para inserir os dados no form eu faço:
form['data_dia'] = '25'  # por exemplo

Para submeter o formulário eu faço:
browser.submit_form(form, form['btnEnviar'])

ou apenas
browser.submit_form(form)

Porém isso não está funcionando, o form não está sendo enviado.
Ao tentar buscar todos os inputs dá página, descobri que o botão para enviar não está vindo pelo Robobrowser.
fazendo,
todos_inputs = browser.find_all('input')

        for t in todos_inputs:
            print(t)

não obtenho a tag input com id 'btnEnviar', que no código html da página está dentro do form. Os outros inputs do form estão vindo, como 'dia', 'mes' e 'ano', por exemplo.
Não postei o código html pois o mesmo precisa de login e senha para acesso.
O problema é que o Robobrowser não está conseguindo raspar todas as informações do html, apenas uma parte, fazendo com que eu não consiga enviar o formulário. Existe uma solução para isso? Ou existe um outro jeito de preencher um formulário e enviá-lo com outras ferramentas, exceto RoboBrowser e BeautifulSoup?
Answer: Robobrowser é um módulo que combina o requests para baixar as páginas e o BeautifulSoup para parseá-las.
O seu problema é que o botão que você quer clicar, provavelmente, na verdade não existe mesmo na página! É bem provável que as páginas do site que você quer usar, assim como muitas outras na internet, são disponibilizadas incompletas, sem todos os elementos, e só depois esses elementos são colocado na página através de código feito em javascript que é executado em seu navegador após o carregamento.
Portanto, ao inspecionar o código da página usando o seu navegador, o javascript já terá executado e completado os elementos de forma dinâmica, por isso você encontrará o botão lá. Como o BeautifulSoup não executa javascript, na página que ele parseou na memória ao rodar o script o botão não existe.
Isso é muito comum nas páginas da web hoje em dia, que são bastante dinâmicas. Te deixando com duas opções:

Analisar o código javascript da página e descobrir onde ele cria o botão. Ou então analisar o que o botão faz. Você pode ir lendo e acompanhando o código javascript manualmente até encontrar uma forma de imitar o que ele faz ao clicar nesse botão, quais parâmetros passar, etc. Em seguida escreva código em python para simular essas ações. Não é uma tarefa fácil mas o código ficaria bastante otimizado pois seria código python sem precisar abrir um navegador de verdade, que seria a segunda opção:
Utilizar um navegador de verdade, que rode javascript. A biblioteca Selenium permite que você abra e controle uma janela de navegador real através do seu script. Como a página abrirá em um navegador, o javascript vai funcionar e você consegue clicar no botão. O lado negativo é que abrir um navegador é pesado e lento, além de carregar vários elementos e imagens desnecessárias ao processo, portanto, não seria tão eficiente quanto acessar diretamente a fonte.

Raspagem de dados usando Robobrowser


DNS zone file syntax check through SVN

Question: I have server in development environment, we manage our DNS files through svn repositories. Few days ago, We messed up our DNS server by committing zone file with invalid serial number.
So I want to have provision that will validate syntax of zone file before someone commits it. I know about named-checkzone command that validates zone file but can I try this in pre-commit or post-commit ? If yes, then How would I do that ? Or is there any other way to accomplish this ?
Any help would be appreciated.
Update
If this is not be possible through SVN, then is there any way to check for syntax in zone file before reloading the bind daemon itself ?
Answer: Test configuration using Jenkins and SVN hooks.

Create new branch for every configuration change that you make.
Create Jenkins job that pulls DNS configuration using SVN hook and then runs "named-checkzone" against it. If everything is ok, merge that branch to the master. Otherwise, send notification that configuration test failed.
If everything went ok, deploy "master" to production.

If that is too much, you can just modify init script or systemd unit file to run "named-checkzone" on start and reload of bind server.

DNS zone file syntax check through SVN


How many runs will be considered when a team needs 1 run and the player hits a boundary?

Question: If a team needs 1 run to win and the player hits a Six(6) then, How many runs would be considered? Would it be considered 1 run or 6 runs?
Comment: Possible duplicate of [Does the batsman get runs on No ball when the team requires only 1 run to win?](http://sports.stackexchange.com/questions/2121/does-the-batsman-get-runs-on-no-ball-when-the-team-requires-only-1-run-to-win)
Comment: Not a duplicate: this question has nothing to do with no balls.
Answer: If the batsmen do not take a single run while the ball goes to the boundary line it will be considered a six and 6 runs will be added to the batsman's total runs as well.
However, there is an exception. If the bowler bowls a no ball, and the batsman hits a six off that ball, the six is not counted. Only an extra run of a no ball will be added in the team's total.
Answer: hims056's answer is completely correct, but just to quote the actual Laws on this one (Law 21.6(c)):

If a boundary is scored before the batsmen have completed sufficient runs to win the match, the whole of the boundary allowance shall be credited to the side's total and, in the case of a hit by the bat, to the striker's score.


Problema com variável de conexão ao Banco C# Visual Studio

Question: Tenho minha string de conexão que pega a variável de conexão do App.Config
static String string_conn = ConfigurationManager.ConnectionStrings["bd1"].ConnectionString;

Porém eu coloquei uma função que lista os bancos em um Combobox no form login e manda o nome da conexão para esse form principal que contem a conexão acima, porem eu preciso que esse valor que vem do form login fique no lugar desse

ConnectionStrings**["bd1"]**

por exmplo:
   String nomeConexao = Form1.LoginInfo.StringConexao;

static String string_conn = ConfigurationManager.ConnectionStrings[nomeConexao ].ConnectionString;

Ou seja no lugar de
ConnectionStrings["bd1"]

Fique
ConnectionStrings[nomeConexao ]

só que da erro, ele não aceita a variável mesmo sendo uma string o que eu posso fazer?
Answer: Minha sugestão seria fazer o seguinte.
Declarar a sua variável de conexão assim:
string _conn;

E no evento de mudança do index do seu ComboBox, colocar o seguinte código:
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedConn = (sender as ComboBox).Text;

    _conn = ConfigurationManager.ConnectionStrings[selectedConn].ConnectionString;
}

Dessa forma, após selecionar a conexão desejada no ComboBox, você teria a conexão desejada na variável global _conn.
Answer: Consegui resolver!
Eu estava colocando o trecho de código no lugar errado, foi descuido meu.
Eu estava colocando fora da função de click do botão.


Should I Try to be Streaming mp3s

Question: I'm developing a program in python that plays audio files from various websites, mostly mp3s. My first thought to play these files was to try streaming them with requests then decoding the chunks, seeking would be some sort of range in the request header.
So I've tried doing some tests with this and ran into some problems converting small chunks of data to the playable form. Before I dig in and try to fix them, I was wondering if streaming is even necessary. Is that how programs like vlc deal with it? How would you go about dealing with it?
I did a lot of google searching and didn't come up with anything useful.
Answer: Yes, if you're playing back as you're downloading, streaming is the way to go.
This generally doesn't require any special requests on your part.  Simply make a request, decode the data as it comes in, buffer it, and put backpressure on the stream if your buffers are getting full.
What ends up happening is that the TCP window size will be reduced, slowing the speed at which the server transmits to you, until it matches the rate of playback.  (In practice, this means that the window slams to zero pretty quickly, then spurts open for a few packets and back to zero again, since internet connections these days are typically much faster than required.)
Now, you still may want to handle ranged requests if you lose your connection.  That is, if I'm listening to audio for several minutes and then lose my connection (such as when changing from WiFi to LTE for example), your app can reconnect and request all bytes from the point at which it left off.  Browsers do this.  It becomes more important when using common HTTP CDNs which are less tolerant of connections that stay open for long periods of time.  Typically, if the TCP window size stays at zero for 2 minutes, expect that TCP connection to close.
You might download a copy of Wireshark or some other packet sniffer and watch what happens over the wire while you play one of these HTTP streams in VLC.  You'll get a better idea of what's going on under-the-hood.

Should I Try to be Streaming mp3s


Prolema com layout do R Studio

Question: Acabei de instalar o R Studio e ele não está igual eu vejo em todos os tutoriais na internet com quatro janelas. Ao invés disso está assim:

Alguém sabe como arrumar?
Answer: Este não é o RStudio. Este é o R puro, sem IDE. Baixe o RStudio Desktop neste link e seja feliz.
Comment: Obrigada! Agora funcionou.

Prolema com layout do R Studio


How to select the most important features to use in forecasting Neural Network Model?

Question: I have a data collection contains many variables as inputs and the output is the daily cash demand in an ATM.
How can i select the most important variables which have the most influence on the output (Demand) to to use in my forecasting Model based on Neural Network?

Thank you.
Answer: It depends on
a) what input variables you have access to?
b) What output you want to measure ? (frequency, amount of money,..)
But given thats its amount of money,I'd start with: days since payday or 1st of the month, weekday, time of day,  frequency of withdrawals


Is it 3-D Catalan numbers?

Question: I am studying Catalan numbers recently but I think that how about 3-D Catalan?
So that I imagine following situation ;

A man travel through the path-way parallel to   $  x, y, z $ axis from O $(0, 0, 0)$ to  $P (n, n, n)$ $ (n \in  N)$
  However he chooses the Points  $(x, y, z)$  satisfy   $ x \leq   y \leq z $  , and the path-way is always the shortest way  $(x, y, z \in  Z)$
  during all his trip.
  What number of path-ways he can choose in his trip?

Abobe situation ,
This is my question.
Comment: The answer for this question is $\frac{2{\cdot}(3n)!}{(n+2)!{\cdot}(n+1)!{\cdot}n!}.$
https://oeis.org/A005789
Comment: You want *my* advice ? Determine the first few terms of this "three-dimensional" Catalan sequence, and then [check to see if by any chance it's not already known](http://oeis.org).
Comment: Multidimensional Catalan numbers have been studied.
Answer:
The problem from 2017 Cayley Contest of CEMC of University of Waterloo is about 3D Catalan Number.  The answer is: $\frac{2\cdot(3n)!}{n!\cdot(n+1)!\cdot(n+2)!} = \frac{2\cdot9!}{3!\cdot4!\cdot5!} = 42$

Is it 3-D Catalan numbers?


Deselect selected rows from ag grid angular

Question: Is there any grid api to deselect ag-grid selected rows programatically?
I'm trying to perform some operation on the selected row, basically an async operation , after which I need to deselect this row from the grid .
Answer: Used grip api deselectAll function . It worked !
this.gridOptions.api.deselectAll();

Comment: Can we deselect any specific row in aggrid?
Comment: this works fine but due to this table is continuously refreshing
Comment: It is better to assign the API object into its own object (and run this function from it), upon "gridReady" event, but basically this code works fine for its purpose. Thanks
Comment: My solution was similar, but I did not need gridOptions. Since I already had: ````onGridReady(params: GridReadyEvent) {this.gridApi = params.api}```` I just could do this: ````this.gridApi.deselectAll()````
Answer: I believe it is weird but setting rowDeselection to true didn't work for me. What I wanted was simple: Being able to deselect a row when it was selected already. So I checked the Row Selection section of AG Grid's documentation and I find this:

rowMultiSelectWithClick: ... Clicking a selected row in this mode will deselect the row.

Huh! Yeah that sounds like what I need! But I don't want multiple selection...! I want single selection ONLY. So I thought maybe setting rowSelection to single will fix it and the selection will be single and deselectable. And... yes it works! The reason I was in doubt initially when doing this is using "rowMultiSelectWithClick" together with "single rowSelection" sounds contradictory, but it works anyways and this is the thing that matters really! :)
So e.g., if you're using it in React (quite similar in Angular or Vanilla JavaScript), just add:
<AgGridReact
    rowSelection="single"
    rowMultiSelectWithClick={true}
    //...
>

Answer: For anyone that finds this in the future:
Allow manual row deselection by setting gridOptions.rowDeselection = true as Victor said.
Programatically deselect all rows using gridOptions.api.deselectAll() as OP discovered.
To programatically deselect a single row, use rowNode.setSelected(false).
rowNode.setSelected(isSelected, clearSelection) can be used to select rows as well, and will deselect all rows other than the subject rowNode if clearSelection is true.
Comment: What is rowNode, where do you get it?
Comment: A `rowNode` is the datatype returned by the functions that get rows.
Examples of these functions called from the gridApi: https://www.ag-grid.com/angular-grid/grid-api/#reference-rowNodes
Read more about row nodes here: https://www.ag-grid.com/angular-grid/row-object/
Answer: You could try the deselectAll() method in the GridApi. Though, it doesn't appear that AgGrid has an option to deselect specific rows.
Comment: Yes, Though I was having single select ag grid instance , So this worked.
But If you want to deslect some specific rows you can use api.forEachNodeAfterFilter( function(node) {
  // select the node
  node.setSelected(false);
});
Comment: Nice~ I have faved your question. because I use AgGrid myself and might stumble upon this issue myself eventually :)
Answer: set gridOptions.rowDeselection to true with rowSelection as multiple will deselect a selected by click when holding control key.
Answer: To deselect a specific row/node use api.getSelectedNodes() instead of getSelectedRows(). Then for each node use node.data for the row info you need and then node.setSelected(false) to deselect when done.
let selected = gridOptions.api.getSelectedNodes();
_.each(selected, function(node) {
    let row = node.data;
    //stuff
    node.setSelected(false);
});


Add observation to the end of the table SAS

Question: Let say I have a table like:
Z 25  26  27 ... 100
0 300 200 200    100
1 278 262 177     45
2 168 222 122     22

(The 1st line is also the header).
Now I want to add more 20 observations in my table:
Z 25  26  27 ... 100
0 300 200 200    100
1 278 262 177     45
2 168 222 122     22
3 84  111  61     11
...
22 84  111  61     11

So that (all observation with Z=3 to 22) = (observation with Z = 2) * 1/2. Is there anyway to do that?
Comment: Please remember to show what you've tried so far per the SO guidelines [ask]
Answer: The special variable name list _numeric_ is used to array all the numeric variables.  A loop over that array will let you divide each variable of a selected row by 2.
Example:
data have;
input Z _25  _26  _27 _100;
datalines;
0 300 200 200    100
1 278 262 177     45
2 168 222 122     22
run;

data newrows(drop=last_z);
  set have nobs=nobs point=nobs;   * read last row;

  last_z = z;

  array _ _numeric_;               * array all numeric variables;

  do _n_ = 1 to dim(_);
    _(_n_) = _(_n_) / 2;           * divide each variable by 2;
  end;

  do z = last_z + 1 to last_z + 20;  * output 20 'new' rows;
    output;
  end;

  stop;
run;

proc append base=have data=newrows;
run;

Answer: Just to be clear, a SAS variable name can not be a number. However, this gives you what you want
data have;
input z a b c;
datalines;
0 300 200 200
1 278 262 177
2 168 222 122
;

data want;
   set have end=lr;
   array arr a--c;
   output;
   if lr;
   do over arr;
      arr = arr / 2;
   end;
   do _N_ = 1 to 20;
      z + 1;
      output;
   end;
run;

Updated Code:
data have;
   do z = 0, 1, 2;
      array arr _25-_100;
      do over arr;
         arr = ceil(rand('uniform')*100);
      end;
      output;
   end;
run;

data want;
   set have end=lr;
   array arr _25--_100;
   output;
   if lr;
   do over arr;
      arr = arr / 2;
   end;
   do _N_ = 1 to 20;
      z + 1;
      output;
   end;
run;

Comment: You can use name literals if you want to, but it is not recommended. e.g. '1'n, '2'n, etc.
Comment: You can show me, if the name of the variable is like: _25, _26... _100; how should I modify the code "array arr a--c;"? is it like array arr _25-_100?; thanks


How would a properly format a regular expression for this?

Question: I am attempting to validate a regex expression for the following procedure:
Example:
1234567 Marko's word document 31.10.1998

Pseudo Example:
[Seven digit #] [space] [Unspecified amount of text] [space] [. delimited date]

Can someone assist me on constructing one? This is for the VBA flavor of regex.
Comment: Have you written any code for that? Where are you stuck?
Comment: depend on how strict you want the date validation to be. is `31.09.1998` a valid one?
Answer: I would start here.
^\d{7}\s.*\s\d{1,2}\.\d{1,2}\.\d{4}$

This is what each section corresponds to.
(beginning) = ^
[Seven digit #] = \d{7}
[space] = \s
[Unspecified amount of text] = .*
[space] = \s
[. delimited date] = \d{1,2}\.\d{1,2}\.\d{4}
(end) = $

But the .* in the middle might allow more than you are ok with.
Also the \d{1,2}\.\d{1,2}\.\d{1,4}$ won't actually filter dates, just decimals. So it will allow a string like "99.99.9999"
You can use this tool to hone it down if you need something more specific:
https://regex101.com/r/dU5lQ3/2
Comment: shouldn't that `\d{1,2}\.\d{1,2}\.\d{1,4}` bit just be `\d{2}\.\d{2}\.\d{4}` or does vb not support that?
Comment: I did it because I assumed 1.1.2010 is accepted just as 01.01.2010 would be accepted. But you're right, that depends on the OP. I guess it's safe to remove the \d{1,4} though. Unless they want two digit years or a year prior to the year 1000.


How to do weighted pair hierarchical clustering in R?

Question: Here is an example of hierarchical clustering of genes in the microarray data using the weighted pair gene method in Spotfire. I am not sure how to do this in R. In the hclust function, I see ward", "single", "complete", "average", "mcquitty", "median" or "centroid" as the methods.
Also, lets say I have performed hierarchical clustering and found groups of genes using cuttree method. I wanted to plot the expression of genes in a group across columns (which may represent treatment, time, etc.). And I want to do this for all the groups separately. In a way similar to the Mfuzz package's way of showing clusters.
Can any one please help me?
TIA for any pointers.
Answer: About your first question, it seems that the mcquitty option corresponds to WPGMA clustering, while average is for UPGMA. It is just by looking at the source code, so it is worth to double check it. But it also referred as is in the upgma() function from the phangorn package.
About your second question, I think you just have to subset your genes by the group labels found after cutree, and then plot expression profiles as usual.
Comment: Thanks a lot. I was dumb not to look at the source code. It mentions this clearly...


Infimum and limit

Question: I was having trouble with the following question. Any help would be highly appreciated.
Let $A$ be the set of K-dimensional vectors with non-negative components. Let $B$ be the set of K-dimensional vectors with positive components.
Let $f:A\rightarrow \mathbb{R}$ be a continuous function. Let $c\in\mathbb{R}$ be any number and let $C=\{a\in\ A | f(a)\geq c\}$.
Let $b_n$ be a sequence in $B$ that converges to another element $b\in B$ w.r.t. the Euclidean norm.
Show that $\lim_{n\rightarrow \infty} \inf_{a\in C} ab_n = \inf_{a\in C} ab$, where multiplication is the dot product of vectors. Also, $C$ is given as non-empty, and clearly by the construction of $A$ and $B$ the infimum will never be $-\infty$.
I can only show one direction.
Comment: Wnat do you mean by $ab_n$ and $ab$? Is that supposed to be a dot product? Where do $f$ and $C$ fit into this problem?
Comment: Instead of "K-dimensional vectors" I'd prefer "elements of $\mathbb R^K$" (for several reasons). And do you mean $\inf_{a\in C, n\in\mathbb N} ab_n=\inf_{a\in C} ab$? That would surely be wrong. Or possibly $\lim_{n\to\infty}\inf_{a\in C} ab_n=\inf_{a\in C} ab$?
Comment: Thanks Hagen, hopefully fixed for the last time now. It is basically being able to switch limit with infimum, which happens when function converges uniformly. That wont be the case here though.
Answer: Here is a proof sketch.

First of all, for every $x\in B$ there exist $y\in C$ such that $x\cdot y = \inf_{c\in C} x\cdot c$. Indeed let $\alpha = \min_{c\in C} x\cdot c$. Let $R= \{z:z_i \leq \alpha / x_i\}$. Then
$$\inf_{c\in C} x\cdot c = \inf_{c\in C\cap R} x\cdot c.$$
But $C$ is a closed set, $R$ is a closed and bounded set, therefore, $C\cap R$ is a compact set. Thus there exist $y\in C\cap R$ that minimizes $x\cdot y$.
Let $a^*\in B$ be the value of $a$ that minimizes $a\cdot b$; let $a_n^*\in B$ be the value of $a$ that minimizes $a\cdot b_n$.
We need to prove that $\lim_{n\to \infty}  a_n^*\cdot b_n = a^*\cdot b$. Note that $a_n^*\cdot b_n \leq a^* \cdot b_n$ for every $n$ and thus $\lim\sup_{n\to \infty}  a_n^*\cdot b_n \leq \lim_{n\to \infty}  a^*\cdot b_n =a^*\cdot b$. Now we prove that $\lim\inf_{n\to \infty}  a_n^*\cdot b_n \geq a^*\cdot b$. Let $k_n$ be a subsequence s.t. $a_{k_n}^*\cdot b_{k_n} \to \lim\inf_{n\to \infty}  a_n^*\cdot b_n$. Note that $a_n$ is a bounded sequence, and hence $a^*_{k_n}$ is also bounded. Let $a'$ be a limit point of $a_{k_n}^*$. Then
$$\lim\inf_{n\to \infty}  a_n^*\cdot b_n = \lim_{n\to\infty} a_{k_n}^*\cdot b_{k_n} = a'\cdot b \geq a^*\cdot b.$$

Infimum and limit


The trace map on elliptic curve is surjective.

Question: Let $E$/$K$ be an elliptic curve over a finite field $K$, and let $L/K$ be a finite Galois extension.
Define a map $T$ : $E(L) \rightarrow E(K)$, $P \mapsto \sum_{\sigma \in G_{L/K}} P^\sigma$.
In fact, it is an exercise #10.22-b) in 'The arithmetic of Elliptic Curves' by J.Silverman.
How to prove the map $T$ is surjective?
Answer: Let $L/K$ be an extension of finite fields of degree $n$.
Let $F\colon E\to E$ be the Frobenius endomorphism. Then $1+\cdots+F^{n-1}\colon E\to E$ is not constant. Indeed, $1-F^n=(1-F)(1+\cdots+F^{n-1})$ is non-constant, since the kernel is $E(L)$, which is a discrete group. Since $E$ is a proper curve, any non-constant morphism $E\to E$ must be surjective.
Now, let $x\in E(K)$ be an arbitrary point. By surjectivity, there exists some $y\in E(\overline K)$ such that $x=(1+\cdots +F^{n-1})y$. But now applying $1-F$ shows $(1-F^n)y=(1-F)x=0$, i.e., $y=F^ny$. Thus, $y\in E(L)$, as desired.
Comment: Amazing!!!!! How obtain this idea? Thanks a lot. :)


onReceive() is not triggered with incoming SMS

Question: I was trying to read incoming text messages and perform some actions based on the text in the SMS but the onReceive() method is not triggered.
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dost.anshdeep.dosti">
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Ringing"
            android:label="@string/title_activity_ringing"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="com.dost.anshdeep.dosti.Ringing" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Alarms"
            android:label="@string/title_activity_alarms"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="com.dost.anshdeep.dosti.Alarms" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <receiver android:name=".SmsListener">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

SmsListener.java
 public class SmsListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Hello",Toast.LENGTH_LONG).show();
        //Log.d("Message Received : ",msgBody);
        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                        String msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
                            Log.d("Exception caught", e.getMessage());
                }
            }
        }
        //Toast.makeText(context,msg_from,Toast.LENGTH_LONG);
    }
}

Can I know what is the issue with this code as I can't figure out why the onReceive() is not called.
Comment: I really appreciate your help Arshad but its not working for me. And I wished to know the reason why my code is not working. Still the onReceive() is not invoked. Any help will be greatly appreciated.
Answer: Try declaring your BroadcastReceiver like this in Manifest
<receiver
        android:name=".SmsReceiver"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS">

        <intent-filter android:priority="2332412">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>

    </receiver>

and Your BroadCast Receiver
public class SmsReceiver extends BroadcastReceiver {

private static final String TAG = SmsReceiver.class.getSimpleName();

@Override
public void onReceive(Context context, Intent intent) {

    Log.e(TAG, "Checking Sms");
    Bundle bundle = intent.getExtras();
    try{
        if(bundle != null){
            Object[] pdusObj = (Object[]) bundle.get("pdus");
            for (Object aPdusObj : pdusObj) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
                String senderAddress = currentMessage.getDisplayOriginatingAddress();
                String message = currentMessage.getDisplayMessageBody();

                Log.e(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);

                if (!senderAddress.toLowerCase().contains(GlobalFunctions.SMS_ORIGIN.toLowerCase())) {
                    return;
                }

                // verification code from sms
                String verificationCode = getVerificationCode(message);

                Log.e(TAG, "OTP received: " + verificationCode);

                if(AppController.isActivityVisible()) {
                    Intent smsService = new Intent(context, SmsService.class);
                    smsService.putExtra("otp", verificationCode);
                    context.startService(smsService);
                }
            }
        }
    } catch (Exception e){
        Log.e(TAG, "Exception");
        e.printStackTrace();
    }

}

}
Note: Do not copy the whole code, it contains my declared variables. Just follow the code and write your own as per your neeed
Comment: Please note that if another application declares a broadcast receiver listening for the same intent with higher priority and does not pass on the intent then this all lower priority broadcast receivers will not receive the intent. Handcent SMS is known to do this.
Answer: On API 23 and above, you should also get permission to receive SMS at runtime. look here


Máscara de entrada AngularJS vs JQuery

Question: Tenho um ng-repeat e preciso que o campo de entrada tenha o seguinte formato:

9.999,99

Código:

    {{item.ano}}

       <input type="number"  step="any" ng-model="item.valor" class="form-control" ng-disabled="{{item.ano < @Model.Confo.ano}}">

    {{item.somatorio | number:2}}

Qual a melhor forma de conseguir resolver isto?
Answer: Utilize o jQuery Mask
Exemplo de uso
$("input[type=number]").mask("0.000,00");

https://github.com/igorescobar/jQuery-Mask-Plugin
Answer: Recomendo o uso do Angular UI
Ex:
<input type="number"  step="any" ng-model="item.valor" class="form-control" ng-disabled="{{item.ano < @Model.Confo.ano}}" ui-mask="9.999,99">

http://angular-ui.github.io/ui-utils/#/mask
Answer: Eu aconselho fazer algo "manualmente", em javascript:

<form id="form1">
<input type="text" id="zipCode" onkeyup="javascript:mask('zipCode', '0.000,00', event);" value= 9.999,99 >
</form>

Máscara de entrada AngularJS vs JQuery


jquery ui function problem

Question: Really my total hairs gone for it problem.
 $('ul#listticker').prepend($('

.......

').fadeIn(2000));

$("ul#listticker li:first").show("slide", { direction: "up" }, 1000);

It is perfectly working in IE but not working in firefox.
I found solution for it that is
my class user-box is
#fbook-iq .user-box {
    width:280px;
    height:41px;
    float:left;
    margin-bottom:1px;
    padding:9px;
}

if i remove float:left line perfectly working
#fbook-iq .user-box {
    width:280px;
    height:41px;
        margin-bottom:1px;
    padding:9px;
}

Really i don't know what logical behind it.
please help me.
Answer: Why is the user-box class floating left? This points to the div element inside the li, and I don't quite see any reason for it. If the float: left on this element breaks behavior in Firefox, you might try to rather set the li containing element to the needed width and height, and leave the div element a non-floating block element. It's a work-around, but if it solves your problem, it solves your problem.

jquery ui function problem


Is it possible to use Swift 4.0 (4.0.3) with XCode 9.3?

Question: I'm trying to upgrade to XCode 9.3 so that I can run my app on an iOS 11.3 device, but I'm having some issues.
My app has up until this point been built in XCode 9.2 with Swift version 4.0.3. I would like to keep the app on Swift 4.0.3, but I can't seem to choose that option in XCode.
I have toolchains set up to point to: Swift 4.0.3 Release 2017-12-05
When I go to Build Settings -> Swift Language Version I have only three options: Swift 3.3, Swift 4.1, and Unspecified. None of these are working for me.
How can I build and run my app on a device using Swift 4.0?
Comment: Why do you need to keep using Swift 4.0?
Comment: "*None of these are working for me*" – can you please expand on the problem you're facing? Using a Swift 4.0.3 toolchain should work AFAIK.
Comment: Swift 4.1 is backward compatible with 4.0.3.  You should be able to use the new toolchain without making any code changes.
Comment: Try [this method](https://stackoverflow.com/a/46649266/3687801). Process is the same. Just consider **Xcode 9.2 -> 9.3** instead of 8.x -> 9.x
Answer: It's not possible.
But you can have two different Xcode versions in the Applications folder, just rename one of them.
Comment: I actually do have that. However, the problem is in my 9.2 version I can't debug the app on an 11.3 device. Puts me in a  tough spot.
Comment: That's how it has always been.  There are ways to achieve what you are after.  Look for posts about debugging iOS 10 in Xcode 7.


getting an Unknown Warning (This is a site for Magento, not an X-Men character. ;-))

Question: i am Trying to ask question in Magento 2 I am Getting a Warning
Question
Not Getting Values of selected Custom Options On Add to Wishlist In Magneto 2
Warning
This is a site for Magento, not an X-Men character. ;-)
I looks Bit Funny But i still want to know what is this
Comment: cc : [Mass Edit functionality](https://magento.meta.stackexchange.com/questions/2472/mass-edit-functionality)
Answer: You are getting this because your are typing in "maGNeto" instead of "maGEnto"


Does every non-empty set of natural numbers have a unique least element?

Question: First of all, I apologize if this question is too elementary or pedantic. It is usually said that every non-empty set of natural numbers has a least element. However, books usually don't mention if the least element is unique. So, what is the proof that the least element in a non-empty set of natural numbers is unique?
Comment: Because you can't have repeated items in a set.
Comment: What definition of the naturals numbers are you using? Are you allowed to assume that the naturals are totally ordered or just that they are well ordered?
Answer: Ordering on the natural numbers is anti-symmetric, i.e. if $x\leq y$ and $y\leq x$ then $x=y$
Comment: @RossMillikan this is sufficient for the question that is asked, namely is "the least element in a non-empty set of natural numbers [...] unique?" In the rationals and the reals, if you hand me non-empty set and tell me it has a least element, that least element is unique by this reasoning
Comment: This is not sufficient.  It applies to the rationals and reals as well, neither of which is well-ordered by the usual order.
Comment: @RossMillikan As pereptually mentioned, I was only addressing the uniqueness question that the questioner raised


Delta method for ratio metrics

Question: I have the following issue: I would like to do a power analysis (find the right sample size) for a ratio metric ($Z = \frac{X}{Y}$). The in-house statistical software I inherited uses a delta correction or delta method for that and before blindly using that I would rather like to understand what this method does. I understand it is somehow related to the variable $Z$ not being normally distributed and/or $X$ and $Y$ being correlated.
More concretely I would like to understand what happens if I don't use the delta correction, in what way the sample size estimation may be off if I don't use it and in how far it compensates for the (presumed) violation of the prerequisites. Also, I would be interested in whether there is something I can test the distribution against which would allow me to omit the delta correction.
Comment: That's going to depend on the ranges of $X$ and $Y$.   For example, if $X,Y \in [100,150]$, you may not have much of a problem, whereas if $Y \in [1,100]$ you probably will.
Answer: The $\delta$-method is an elementary statistical result for calculating the asymptotic standard error of a smooth function of random variables. A ratio such as $X/Y$ is smooth provided 0 is not in the sample space of $Y$ ($Y$ must be strictly positive or strictly negative). The $\delta$-method has nothing to do with the actual normality of the variables since it is an asymptotic result. If $\bar{X}$ is asymptotically normal and $\bar{Y}$ is asymptotically normal (with a very low probability of achieving 0) then their ratio $\overline{X/Y}$ is asymptotically normal with a variance given by the quadratic form defined by the covariance matrix of $X,Y$ and the Jacobian.
Comment: +1 Should the answer maybe say "approximate asymptotic standard error", since typically only the first order term, and rarely the second order term are actually calculated out of an infinite series?
Comment: @Alexis The asymptotic standard error should be correct. The later order terms shouldn't matter because the estimator converges to its expectation by the SLLN. In finite samples, "approximation" should be used very loosely, because the rate of convergence can be abysmal.
Comment: TY! So the higher-order terms in the $\delta$-method do what? Accelerate the rate of asymptotic convergence? Incorporating them often produces results which are different—even if only by a small amount—from the first order term only, so what does that difference (i.e. 1st order only, or 1st order plus higher order terms) imply?
Comment: @Alexis you seem to have some intuition about the purpose of higher order terms, since you said yourself "the second order term is rarely calculated out of an infinite series". Incorporating higher order terms in the form of tensors will improve the local approximation of the standard error.
Comment: Yes. Sorry... taking advantage of you to learn stuffs. :D
Comment: @AdamO thanks for your explanation. Since the delta method is new to me, please allow me some questions to better understand.

In our case, Y can be zero, but only if X is zero (the measure is basically "X out of Y"). So if I am not mistaken, the function should be smooth.

What is the reason behind using an asymptotic SEM insterad of just SEM?

What could go wrong if I just use this formula to calculate SEM?
std(Z)/sqrt(n)

Delta method for ratio metrics


creating a custom report page with a table

Question: Drupal 8.9.6, I'm trying to create a custom module admin report page.
I have a custom sub theme of seven called wd_admin.
I made a page controller that generates a table as markup, but want to use a twig file to render the html, and can't figure out the theming.
It is using block.html.twig to render the content, and the first suggested template is block--wd-admin-content.html.twig. So I created it, and plumbed it in with hook_theme and hook_theme_suggestions_block_alter, but it affected the content on all admin pages, wrong move.
Seems like for this to work it would have to be specific to the page. What do I need to do to render this page, maybe a page.html template?
Comment: Yeah, you're doing it wrong. Can you post your controller's code?
Comment: Thanks; too long to post so here's a gist. I have some test code to create a table, I want to instead send the variables to a twig template.  https://gist.github.com/pglatz/4f2d826909124dfddbd9ba3f79a424ba
Answer: Yeah I think you're conflating a few different concepts and making everything way more complex than it needs to be.
If you all you want to do is render a particular custom template with your controller then you'd want to:
// In fun.module
function fun_theme() {
  return [
    'a_fun_template' => [
      'variables' => [
        'heading' => '',
        'activities' => []
      ],
    ],
}

// Then in your controller
public function yourRenderMethod() {
  $heading = 'Some fun activities';
  $activities = [
     'Rocket League',
     'Violin'
  ];
  return [
    '#theme' => 'a_fun_template',
    '#heading' => $heading,
    '#activities' => $activities,
  ];
}

// Then in a-fun-template.html.twig
{#
  Do whatever with your variables, like print them
#}

{{ heading }}

{% for activity in activities %}

{{ activity }}

{% endfor %}

EDIT: I think I figured out why you're looking at the block. All that that is is the "Main page content" block from the blocks page. This just renders the main content for the page, which in this case would be the contents of your controller's template. Now that said, what I wrote before was...
I really don't understand where the block is coming into play here, but I think you're misunderstanding that as well.
First, the default template suggestions are very general. block--wd-admin-content.html.twig is probably added by wd_admin to every admin block by default. That's why a template by that name would be used by all blocks in the admin area. Generally the longer the suggested template name, the more specific it is. Template suggestions that you add to hook_theme_suggestions_block_alter() will apply to all blocks unless you wrap the suggestion in conditional logic that says otherwise. If all you're doing is using a hook_theme template in a controller then you don't need this hook at all.
Comment: Edited to add some context about the main page content block
Comment: Thanks, Mrweiner, your clear explanation was a big help. best, Phil
Comment: Awesome, glad to hear it. Wold be great if you could mark one of the answers accepted just so that the bot doesn't necromance this for years. :)
Answer: I found a pretty good solution here, no twig required: https://www.digitalnadeem.com/2019/12/13/how-to-create-a-custom-filter-form-and-update-custom-table-data-in-drupal/
I'm going to be presenting this with some options, so doing it in a form makes a lot of sense.
I'd still like to understand all that's involved with presenting twig templates better. I've been studying code in core, but a lot of what was done there is pretty complicated. It's well engineered and beautifully written, but I'm struggling to find all the parts involved in advanced theming.


Como separar uma string de uma certa linha de um data.frame e ao mesmo tempo criar mais linhas?

Question: Tenho um data.frame com uma coluna com strings do tipo "123-235-203".
Por exemplo, a linha:

string           coluna1 coluna2
  123-235-203      x        y

Quero separar essa string, de forma que a linha que  a contem se multiplique  preservando os valores das outras colunas:
strsplit(string, "-")

Transformando a linha em 3 linhas.

string coluna1 coluna2
  123      x        y
  235      x        y
  203      x        y

Há uma forma de fazer isso usando dplyr ou tidyr?
Comment: Você quer que a coluna da string vire três colunas?
Comment: @CarlosCinelli Desculpa, aí está. Eu quero separar a string, separar pelos traços e transformar em 3 linhas.
Answer: O próprio Hadley nos oferece a resposta na vignette do tidyr.
library(tidyr)
library(dplyr)
df <- data.frame(
x = 1:3,
y = c("a", "d,e,f", "g,h"),
stringsAsFactors = FALSE
)
df %>%
transform(y = strsplit(y, ",")) %>%
unnest(y)

Comment: de fato a sua solução é mais elegante :)
Answer: Criar uma base para teste:
b <- data_frame(x = 1:10,y = 1:10, string = rep("123-235-203", 10))

Com o código a seguir você pode obter o que queria:
b %>%
  separate(string, into = c('s1', 's2', 's3'), sep = '-') %>%
  gather(string, valor, -x, -y) %>%
  select(-string) %>%
  arrange(x)

A função separate do tidyr transforma a sua string em três colunas (s1, s2 e s3).
A função gather do tidyr multiplica as linhas.
A função selectdo dplyr retira a nova coluna stringque não é mais necessária.
O arrange é só para ficar mais fácil de entender.

O resultados está abaixo:
# Source: local data frame [30 x 3]
#
#    x y valor
# 1  1 1   123
# 2  1 1   235
# 3  1 1   203
# 4  2 2   123
# 5  2 2   235
# 6  2 2   203
# 7  3 3   123
# 8  3 3   235
# 9  3 3   203
# 10 4 4   123
# .. . .   ...

No caso em que as strings podem ter tamanhos variáveis, mas existe um máximmo de "-"'s você pode fazer assim:
b <- data_frame(x = 1:10,y = 1:10, string = rep(c("123-203", "123-203-555"), length.out = 10))

b %>%
  separate(string, sep = '-', into = c("s1", "s2", "s3"), extra = "merge") %>%
  gather(string, valor, -x, -y, na.rm = T) %>%
  select(-string) %>%
  arrange(x)

adicionei o argumento extra = "merge" no separate para que ele não retorne erro.
adicionei o argummento na.rm = T para que ele não crie linhas com NA.
Comment: acho que isso não resolveria o problema, se as strigs são diferentes. Vamos supor que uma é "123-345"  e a outra é "123-12-345". A primeira rende 2 strings e a segunda, 3. De qualquer forma, achei uma forma no próprio tidyr. Vou postar a resposta embaixo. O Hadley é mesmo genial.
Comment: você tem razão, não tinha entendido que isso podia ser variável. Existe um máximo pelo menos?
Comment: acabei de postar uma resposta...
Answer: Aqui é uma solução usando o pacote data.table
> library(data.table)
> dTbl <- data.table(x = 1:3, y = c("a", "d,e,f", "g,h"))
> dTbl[, .(y=unlist(strsplit(y, ','))), by=x]
   x y
1: 1 a
2: 2 d
3: 2 e
4: 2 f
5: 3 g
6: 3 h
>


Android app loading images from /drawables-nodpi/ with scaling

Question: I recently rebuilt my Android project to target 2.2 from 2.1.
In the old project, I did not specify a target SDK (the manifest did not contain something like: android:minSdkVersion="8"). This gave me an error in the console when running, but everything worked fine so I didn't fool with it.
The new project now uses android:minSdkVersion="8"  in the manifest.
But now my drawables from the /drawable-nodpi/ folder are loading with scaling, making them much smaller and significantly changing the desired visuals.
If I cut out the  tag from my manifest, they load properly without scaling.
Even when loading my images like so:
<code>            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScaled = false;
            Bitmap bm = BitmapFactory.decodeResource(_resources, resId, opts);
</code>
They are still scaled when I declare the minimum SDK in the manifest, but not scaled if I remove that tag.
Why is this happening? How can I load them without scaling while still declaring the minimum SDK?
Comment: I am doing the exact same thing as you and my bitmaps are indeed loaded without scaling. The only thing I can think of is to make sure you don't have a bitmap of the same name in one of the other drawable folder
Answer: Did you try this?
From Google:

If you plan on reading an image as a
  bit stream in order to convert it to a
  bitmap, put your images in the
  res/raw/ folder instead, where they
  will not be optimized.
Comment: From my understanding of the documentation, that would be useful were I concerned with the compile-time optimization of images done by the aapt tool (reducing color palette from 256 to 128, for example). This is not the case -- my images are being loaded and scaled at run-time, ignoring the BitmapFactory.Options inScaled setting, and the /drawable-nodpi/ folder location, which is a separate issue.


Controle transacional no contexto de tratamento de exceções usando Demoiselle

Question: Olá,
estou com dúvidas sobre o controle transacional via Demoiselle (@Transactional) no contexto de tratamento de exceções com o ExceptionHandlerInterceptor do Demoiselle.
Eu tenho o seguinte web service:
import br.gov.frameworkdemoiselle.transaction.Transactional;
import br.gov.frameworkdemoiselle.exception.ExceptionHandler;
import br.gov.frameworkdemoiselle.stereotype.Controller;

@WebService
@Controller
public class SislvServiceImpl implements SislvService {

    @Override
    @WebMethod
    @Transactional
    public RegistrarLaudoRetorno registrarLaudo(SolicitanteHeader solicitanteHeader, RegistroLaudoRequest laudoRequest)
            throws MalformedMessage, InternalServerError, Unauthorized, LaudoRejeitado {

        OperacaoRegistrarLaudo op = Beans.getReference(OperacaoRegistrarLaudo.class);
        return op.registrarLaudo(solicitanteHeader, laudoRequest);
    }

    @ExceptionHandler
    public void excecao(Exception e) throws Exception {
        SislvExceptionHandler handler = Beans.getReference(SislvExceptionHandler.class);
        handler.handle(e);
    }

}

Ao executar op.registrarLaudo(), em algum momento o seguinte método será executado para que a chamada ao WS seja adequadamente auditada:
private void auditarNoBancoSislv() {
    AuditoriaRequisicaoWs auditoriaRequisicaoWs = auditoriaRequisicaoWsFactory.createAuditoriaRequisicaoWs();
    auditoriaRequisicaoWsDAO.insert(auditoriaRequisicaoWs);
}

Nesse caso, o caminho feliz, tudo ocorre corretamente!
Mas se o método op.registrarLaudo() dispara alguma exceção, então teremos o tratamento feito pelo exception handler em SislvServiceImpl e a execução do método handler.handle(). Em algum momento o método 'handler.handle()' também executará o método de auditoria auditarNoBancoSislv(). O problema é que como tivemos uma exceção que interrompeu a execução de sislvServiceImpl.registrarLaudo(), a transação aberta em sislvServiceImpl.registrarLaudo() não será efetivada, e assim o método auditarNoBancoSislv() não surtirá efeito: a auditoria não será gravada no banco de dados!
Minha tentativa de solução foi a seguinte, alterar o método excecao()  para
    @ExceptionHandler
    @Transactional
    public void excecao(Exception e) throws Exception {
        SislvExceptionHandler handler = Beans.getReference(SislvExceptionHandler.class);
        handler.handle(e);
    }

A ideia é que se uma exceção ocorrer em sislvServiceImpl.registrarLaudo(), o Demoiselle irá ordenar o rollback dessa transação (TransactionalInterceptor) e também irá executar meu método sislvServiceImpl.excecao() (ExceptionHandlerInterceptor). Aí quando o método sislvServiceImpl.excecao() for executado, uma nova transação seria aberta para podermos gravar coisas no banco, já que a transação anterior já teria sido fechada. Mas não funcionou! =(
Outra tentativa foi a seguinte:
@Transactional
private void auditarNoBancoSislv() {
    AuditoriaRequisicaoWs auditoriaRequisicaoWs = auditoriaRequisicaoWsFactory.createAuditoriaRequisicaoWs();
    auditoriaRequisicaoWsDAO.insert(auditoriaRequisicaoWs);
}

Nesse caso a lógica seria: para o caminho excepcional, ao se chegar nesse em auditarNoBancoSislv() não há nenhuma transação ativa, então abre-se uma nova transação, o que não funcionou!!! Já para o caminho feliz, o Demoiselle teria que perceber que já existe uma transação ativa, e simplesmente não fazer nada para que o código aproveitasse a transação já ativa, o que funcionou, embora não sei se exatamente como o descrito.
Em ambas as tentativas, anotei com o @Controller do Demoiselle as classes contendo os método anotados com o @Transactional. E em ambos os casos os objetos contendo os métodos anotados com o @Transactional são instanciados via CDI.
E por último, mas não menos importante, meu beans.xml:
<beans ...>
    <interceptors>
        <class>br.gov.frameworkdemoiselle.exception.ExceptionHandlerInterceptor</class>
        <class>br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor</class>
    </interceptors>
</beans>

Obs: o comportamento de rollback quando acontecer uma exceção é o que eu quero para a aplicação. Só no momento da auditoria é que eu quero efetivar a gravação no banco em qualquer circunstância.
Por fim, a ajuda que preciso é para encontrar uma forma de persistir os dados em banco ao invocar o DAO no caminho excepcional, que começou a ser executado por um método invocado pelo ExceptionHandlerInterceptor do Demoiselle logo após uma exceção ter interrompido um método anotado com o @Transactional do Demoiselle.
Grato pela atenção!
Leonardo Leite
=================
Edição posterior: nova tentativa.
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class Auditor {

    @Inject
    private EntityManagerFactory entityManagerFactory;

    ...

    private void auditarNoBancoSislv() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        AuditoriaRequisicaoWsDAO auditoriaRequisicaoWsDAO = new AuditoriaRequisicaoWsDAO(entityManager);
        AuditoriaRequisicaoWs auditoriaRequisicaoWs = auditoriaRequisicaoWsFactory.createAuditoriaRequisicaoWs();
        entityManager.getTransaction().begin();
        auditoriaRequisicaoWsDAO.insert(auditoriaRequisicaoWs);
        entityManager.getTransaction().commit();
    }

}

Não deu certo. Erro:
16:22:15,319 ERROR [br.gov.serpro.siscsvws.SiscsvExceptionHandler] (http-/0.0.0.0:8443-1) Erro interno inesperado.: java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
    at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:1019) [hibernate-entitymanager-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1]
    at br.gov.serpro.siscsvws.auditoria.Auditor.auditarNoBancoSislv(Auditor.java:48) [classes:]

Linha 48 é a entityManager.getTransaction().begin();.
Informação adicional, persistence.xml:
<persistence ...>

    <persistence-unit name="siscsv-ds" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/SiscsvDS</jta-data-source>

        <class>br.gov.serpro.siscsv.entity.auditoria.AuditoriaRequisicaoWs</class>
        ....

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.default_schema" value="siscsv" />
            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />

        </properties>
    </persistence-unit>
</persistence>

Comment: Obs: versão do Demoiselle: 2.5.0.
Answer: Em resumo, o jeito que resolvi foi deixando de usar a anotação @Transactional e fazendo o controle transacional por meio da interface UserTransaction.
Em termos de código, o resultado ficou algo equivalente a:
import br.gov.frameworkdemoiselle.exception.ExceptionHandler;
import br.gov.frameworkdemoiselle.stereotype.Controller;

@WebService
@Controller
public class SislvServiceImpl implements SislvService {

    @Inject
    private MyTransactor transactor;

    @Override
    @WebMethod
    public RegistrarLaudoRetorno registrarLaudo(SolicitanteHeader solicitanteHeader, RegistroLaudoRequest laudoRequest)
            throws MalformedMessage, InternalServerError, Unauthorized, LaudoRejeitado {

        transactor.begin();
        OperacaoRegistrarLaudo op = Beans.getReference(OperacaoRegistrarLaudo.class);
        RegistrarLaudoRetorno retorno = op.registrarLaudo(solicitanteHeader, laudoRequest);
        transactor.commit();
        return retorno;
    }

    @ExceptionHandler
    public void excecao(Exception e) throws Exception {
        transactor.rollback();
        transactor.begin();
        SislvExceptionHandler handler = Beans.getReference(SislvExceptionHandler.class);
        Exception e = handler.handle(e);
        transactor.commit();
        throw e;
    }

}

========================================

import javax.transaction.UserTransaction;

public class MyTransactor {

    @Inject
    private UserTransaction userTransaction;

    public void begin() {
        try {
            userTransaction.begin();
        } catch (NotSupportedException | SystemException e) {
            throw new IllegalStateException("Não consegui iniciar transação", e);
        }
    }

    public void commit() {
        try {
            userTransaction.commit();
        } catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
                | HeuristicRollbackException | SystemException e) {
            throw new IllegalStateException("Não consegui finalizar transação", e);
        }
    }

    public void rollback() {
        try {
            userTransaction.rollback();
        } catch (IllegalStateException | SecurityException | SystemException e) {
            throw new IllegalStateException("Não consegui cancelar transação", e);
        }
    }

}

Eu cheguei a fazer tentativas com a anotação @TransactionAttribute, mas não obtive sucesso. Por isso mantive a opção pelo controle "manual" da transação. Mas está funcionando.
Answer: O problema ocorre porque uma vez que o método registrarLaudo está anotado com @Transactional, todos os métodos invocados a partir dele serão aninhados na mesma transação. Logo, um rollback em qualquer momento da operação vai impedir o commit de todas as transações aninhadas.
Para resolver essa situação é preciso criar uma outra transação (independente) para os logs de auditoria.
O recurso ManagedExecutorService do Java EE 7 traz o que parece ser uma excelente alternativa para essa necessidade. Aqui tem um exemplo de como esse recurso pode ser utilizado.


What are fast and safe options to setup a VPN between the office and GCP?

Question: Aim: to setup a VPN between GCP (Google Cloud Platform) and the office

Create VPN connection

Create a VPN connection

Idea
We are now considering to setup StrongSwan, but wonder if this will work from a random system within the office or is a public IP required?
The idea we have now is to create a VM in Digital Ocean (DO), configure a StrongSwan server, enter the IP to the GCP network UI and then let the desktops connect to the DO VM? Is this a safe and the fast way to configure a VPN between the office and GCP?
Answer: Google Cloud VPN makes it easy to configure a IPsec site-to-site VPN tunnel between GCP and your local network. In order to configure the tunnel you need to have a VPN gateway on your local network with public IP that will connect to the Cloud VPN. The only scenario supported right now is IPsec gateway-to-gateway as mentioned on this link:

Cloud VPN only supports IPsec gateway-to-gateway scenarios. You must have a dedicated physical or virtual IPsec VPN gateway on the client side. Cloud VPN does not currently support client-to-gateway (road warrior) scenarios. In other words, it doesn't work with client software on a laptop, only with full IPsec VPN gateway software. Cloud VPN does not support VPN technologies other than IPsec.

In case you are looking for client-to-gateway scenario you can install and configure VPN software like Strongswan on a GCE VM as a server and VPN clients can connect to this VPN server. You can refer to this thread where similar scenarios was discussed.


How to print paragraphs in twig template?

Question: I have a content type, basic, where i have added a Paragraph field field_pr that has two fields: field_text, field_color. I have a twig template node--basic--full.html.twig where I want to print the value of the paragraph field node.field_pr.
node.field_pr can have between one and ten paragraph values.
When I print the array for content.field_pr, I get a huge array. However, I only want the values from the field_pr.field_text and field_pr.field_color. How would I be able to do this from the node twig template?
I have tried the following but cannot seem to access the values. What am I missing?
{% for field in content.field_pr %}
   {{ field[loop.index0].entity.field_text.value }}
   {{ field[loop.index0].entity.field_color.value }}
{% endfor %}

{% for field in content.field_pr %}
   {{ field[loop.index0]['#paragraph'].field_text.value }}
   {{ field[loop.index0]['#paragraph'].field_color.value }}
{% endfor %}

Here is an image of the array that is printed for the node.field_pr field.
Answer: Not sure if it's possible with your current approach. Here is how I would approach this.
In your node template file just do a {{ content.field_pr }}
Create a template file for your paragraph.

paragraph__[view_mode] (e.g. paragraph--default.html.twig)
paragraph__[type] (e.g. paragraph--image.html.twig)
paragraph__[type]__[view_mode] (e.g.
  paragraph--image--default.html.twig)
source: Theming in Paragraphs for Drupal 8

In paragraph--[type].html.twig you do {{ content.field_text }} and {{ content.field_color }}
Comment: Apologies for my ignorance but how do I render paragraph.html.twig on my template file (page.html.twig)?
Comment: @clestcruz why not in node.html.twig?
Comment: @clestcruz i recommend using what NoSssweat said. Use `node.html.twig` and display the field using `{{content.field_machine_name_paragraph}}`. Then enable [Twig debugging](https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) and you can create a new twig template from there.
Comment: @NoSssweat node.html.twig? Sorry I was trying to figure out how I can just print the values from my paragraph to my templates file. So far I've managed to create a paragraph.html.twig. I'm still new to Drupal apologies
Comment: @clestcruz, yes you'll need to create node--[content-type-name].html.twig. Ex: node--articles.html.twig and follow my answer.
Comment: @NoSssweat Not sure if this is the same or different but what I did was created a page--articles.html.twig
Comment: @clestcruz node is inside page. More specifically the `{{ page.content }}` part outputs the node twig. You're better off using node because page contains the entire page structure. Page It's not meant to be used for printing fields.
Comment: @NoSssweat Hmm well this is new to me. Most of my content type in drupal are using page--name-of-content-type.html.twig and not node.html.twig to render the values from the fields. So you're telling the correct  way to print the fields is to use node.html.twig instead?
Comment: @clestcruz yes exactly, the drupal way is to use node.htm.twig to print node fields. If you have a block, you use block.html.twig.
Comment: @NoSssweat ok, but how do I fetch or print the values from the paragraphs to my node.html.twig I tried calling it like a partial template `{% include '@iom/layout/paragraphs/paragraph--multimedia.html.twig' %}`
Comment: @clestcruz read my answer. First you print the paragraph field in node.html.twig then create a paragraph template file (if you want).
Comment: @clestcruz if you haven't yet, you need to go to your content type's manage fields and a paragraph field. Then you just simply print this field in node.html.twig just like any other field, nothing special. BTW no need to `{% include %}` any template.
Comment: @NoSssweat Thanks for referring me here... I'm trying to do something similar to above, But my paragraph template isn't overriding. My field in a content type is called "field_legal_section", referencing a paragraph type called "legal_section"... so I created "paragraph--field-legal-section.html.twig" and dropped {{ content.id }} & {{ content.field_section_title }}. But content type template is just rendering default values for the token in my content type template ( {{ content.field_legal_section }} ) . What might I be missing?
Comment: @turpentyne Did you place it in `/themes/your_theme/templates` folder? Did you clear the cache?
Comment: @NoSssweat I've done both - placed in the template folder of my theme and cleared the cache.
Comment: @NoSssweat update... I figured out the main problem.. Your example above looks like it's naming the template for the paragraph field within the content type. That's what I assumed was needed. When I change the template to my paragraph type's name (which is slightly different) it works - although it's not showing the field ID, which is my primary goal.
Comment: @turpentyne Good catch! What exactly are you referring to when you say field ID? the machine name of the field?  `field_legal_section`  or ???
Comment: @NoSssweat Not the machine name, but a unique id... Maybe it's called something else? Basically, each paragraph entry ends up with a sequential number? I can see it when I pull the paragraph in a view using "Paragraph: ID" , so I presumed I could get it with just {{ content.id }} ... but no luck.
Comment: @NoSssweat I just tried {{ paragraph.id() }} and {{ content.id() }}.. it still didn't work. Maybe at this point I need to make a new question for this. I haven't found an answer that quite works yet
Comment: @turpentyne you can get it with `{{ elements['#paragraph'].id() }}`
Answer: To print paragraph fields in a loop (for sliders, etc.) in page--content-type.html.twig use below snippet:
{% for item in node.field_paragraph_mac_name %}
  {{ item.entity.field_title.value }}

{% endfor %}

Comment: Why we can't use {{ item.entity.field_title }} directly? The problem is for field such as "body" that need specific rendering. Using  {{ item.entity.field_body.value }} will requiere to use an usafe {{ item.entity.field_body.value|raw }}.
Comment: To print **alt** tag, use `alt="{{item.entity.field_image.alt}}"`.
Answer: I figured this one out. With Twig Tweak enabled you can print paragraphs from the node object without using content:
{% for item in node.field_my_paragraph_field %}
     {{ drupal_entity('paragraph', item.target_id) }}
{% endfor %}

Comment: Just use `{{ content.field_my_paragraph }}` instead, does exactly the same, is cache safe, is more performant, and does not require an extra module.
Answer: Building on the answer by user33560. If you have have nested paragraphs and you want to print or get the 2nd-level paragraph fields from within the 1st-level paragraph.html.twig:
{% set paragraph_name = content.field_paragraph_name %}

{% for item in paragraph_name['#items'] %}
    {{ drupal_entity('paragraph', item.target_id) }}
{% endfor %}

You can also use {{ content.field_paragraph_name }} to print all paragraph items, or print a subset such as {{ content.field_paragraph_name.field_example }}. Use {{ content.field_paragraph_name|without('field_example') }} to temporarily suppress the printing of a given child element.
Answer: You can use {{ node.ref_field_name.entity.field_name.value }}


System process (PID 4) constantly accessing the hard disk

Question: Recently I noticed some of our machines are getting sluggish, mainly after boot-up. Using the Resource Monitor I detected excessive disk access from the system process with PID 4. Following some tips, I disabled the anti-virus on the System Volume Information folder, hoping it will help (I don't want to disable system restore).
However, it seems like PID 4 is accessing everything. When running a simple extraction of a ZIP file, I can see the WinRAR reading a few hundreds KBs per second from the file, but PID 4 reads dozens of MBs per second from the same file. After cancelling the operation, PID 4 keeps accessing the file for around 30 seconds, reading many MBs per second. This is not a Resource Monitor bug, as the disk is clearly active, and stops once resource monitors says PID 4 is finally resting.
Why is this miraculous process accessing everything every other process accesses?
I'm using the AVG antivirus. Disabling it did not change this behavior/
What is going on here?
Comment: PID 4 is the Process ID for the Windows SYSTEM process. It's a lot like PID 1 on Unix systems, in fact. A *lot* of services run under PID 4.
Comment: Don't services run under their own processes? Anyway, even if that is so, why is it ordinary file accesses in regular non-service processes are mostly done under PID 4?
Comment: I have the same problem and can't find any solution too. By any chance, do you use TrueCrypt? I use TrueCrypt system-wide encryption and I suspect that might be the cause, as it is running under "System" as a driver, and it needs to encrypt/decrypt every file access.
Comment: No, no TrueCrypt or any form of encryption here.
Comment: Mine was hammering wbem\repository\objects.data, not sure why.
Comment: Related question here: http://superuser.com/questions/349349/windows-7-system-process-reading-writing-like-crazy
Comment: Same problem, especially when opening IE. Chrome can run fine with 20 tabs open, but running IE with 2 tabs makes PID 4 spaz out, system is non responsive for around 30 seconds. Not running TrueCrypt. I use MS security essentials as AV.
Comment: Check this to detect what file this process write - https://superuser.com/questions/716905/how-to-check-what-files-a-process-has-written-into and then investigate for each folder.
Answer: This is an older question, but I had this issue, and for me it was SuperFetch. I tried everything I could find on PID 4 excessive hard drive usage, and some of it helped. A RAM upgrade from 4GB to 8GB only made the issue more obvious - RAM usage was low, no paging, but yet the hard drive was lit up for ~10 minutes after my laptop booted.
Long story short, there's a registry setting that controls what level of SuperFetch is appropriate. You can see below the EnableSuperfetch value is now set to 1, which seems to be "prefetch all executables and libraries". The default is a 3, which seems to mean "prefetch all executables, libraries, and documents". I have many documents, so I think this was taking way too long. Every document opened is another one that SuperFetch has to "analyze" to see how you're using it.
The registry key/value in question is:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters\EnableSuperfetch
So far the only downside is that my outlook folders take a few extra seconds to open, and some commonly used documents like MS Project files take longer. But those delays pale in comparison to the disk thrash I was getting before!
Comment: Peefetch settings [described here](http://www.thewindowsclub.com/disable-superfetch-prefetch-ssd)
Comment: worked great for me ..!!
Answer: A lot of system services (I don't mean Windows Services) run under PID 4, the "System" process.  Every time you open a file, you trigger a slew of background mechanisms such as the virtual memory manager caching the file in memory, moving other things around in memory, servicing page faults, etc.  That activity is separate from the disk activity charged against the process that originally accessed the file, e.g. WinRAR.
That said, what you're describing still doesn't sound like normal behavior to me.  You should see a quick bump in disk activity from the System process when the file is accessed, and then it should go back to 0 rather quickly - within a couple seconds.
I did a little testing on my own machine using Windows Resource Monitor, and I saw somewhat similar behavior. What I think we're witnessing is Resource Monitor showing us some sort of rolling average that is slow to drop off.
Try looking at PID 4 disk activity using another tool such as Sysintenals' Process Explorer.  I got a much different impression from it, as the Read Delta and Read Bytes Delta by the System process seem to return to 0 much faster than when viewed through ResMon.

Edit: If that's not it, then I think a more in-depth analysis is going to be needed in order to answer the question.  For instance, you can list the currently-loaded file system filter drivers with fltmc.exe, and kernrate.exe can help you isolate those modules which are causing inordinately high disk I/O.
Comment: @zmbq: Have you managed to find out what's going on?
Answer: System process is used by Windows Update. If you have selected to install updates automatically, it is probably your systems is currently installing windows software. If you run Windows Update and try to install updates you will receive a message saying you cannot install as Windows is currently updating the system.
Change the Windows Update to not downloading and installing without manual action and wait the current installation to finish.
Comment: This worked for me. My problem was IE made System (PID4) use 100% of the drive. Turning off IE's Automatic Update (Help->About IE->Install new versions automatically) fixed it.
Comment: @Coomie what version of IE has this 'feature'?
Comment: @MDMoore313 IE 10
Comment: @Microsoft, Why should IE upgrade itself from kernel-mode/ring0?
Answer: I had the exact same symptoms. In my case they were related to Norton360 and the MS-SQL VSS service. Once I disabled VSS, my activity dropped significantly. System still locks up when Norton does it's thing, but it's semi bearable since it only seem to happen every hour.
Answer: Posting this answer here as I stumbled over this thread when looking for answers on why system process 4 was consuming so many read/write traffic.
Users when having mapped drives or going out to a UNC path to a share, especially something with a good sized directory structure would all the sudden have a ton of receive traffic continuously from the host server. Normally I would see 100-300k, as soon as you expand in the nav pane it would shoot up in the 20,000k plus range.
Ended up disabling the automatically expand to current folder option in Explorer and that traffic goes away.
http://www.sevenforums.com/tutorials/1014-navigation-pane-automatically-expand-current-folder.html
Answer: I had a similar issue, however in my case it appears that somehow Offline Files was enabled. I'm going to be investigating things on the server side (e.g. I thought it was disabled globally via Group Policy and on the shares.....) but I had two Windows 7 machines at a remote office merrily trying to sync several hundred GB over a VPN connection.
(Edit before posting: Offline files were not properly disabled on the shares, possibly following a server migration.
Answer: Beware that the Windows "Resource Monitor" computes an average I/O speed for the last 60 seconds for the 3 columns "Read (B/sec)", "Write (B/sec)" and "Total (B/sec)", which means that there is an inertia.  This applies to all processes, including explorer.exe, or command-line processes.  Even after the process has exited, it still appears in the "Resource Monitor", with a linearly decreasing I/O speed down to 0.
In contrast, Sysinternals Process Explorer columns called "I/O Delta Read bytes" and "I/O Delta Write Bytes" show the real instant values.
These observations were made on Windows 10 Pro 20H1.


how to parse 3 level nested array using newtonsoft json

Question: I have the following json which is in geojson format, and Id like to be able to parse this into a nested list in c#:
public IList<IList<IList<double>>> Coordinates { get; set; }
"coordinates": [
    [
        [-3.213338431720785, 55.940382588499197],
        [-3.213340490487523, 55.940381867350276],
        [-3.213340490487523, 55.940381867350276],
        [-3.213814166228732, 55.940215021175085],
        [-3.21413960035129, 55.940100842843712]
    ]
]

I have tried the following but I get an exception:
    var node = jsonProperties["geometry"]["coordinates"].Values();
    var coordinates = node.Select(x=>x.Value<List<double>>());

Exception detail:

Cannot cast Newtonsoft.Json.Linq.JArray to
  Newtonsoft.Json.Linq.JToken.
Comment: why you don't use node variable ? Where is d variable comes from?
Comment: @Anjmao sorry that was a typo
Comment: It looks like you need to reference the first element of "coordinates" array, not the coordinates array itself.  Did you try something like `var node = jsonProperties["geometry"]["coordinates"][0].Values();` (unsure of exact syntax).
Answer: To deserialize using newtonsoft. Create Foo class with a coordinates property, inclose the JSON script with curly brackets to denote it as an object then call JsonConvert.DeserializeObject<Foo>(Json).
private class Foo
{
     public List<List<List<double>>> coordinates { get; set; }
}

 var json = @"{
                 coordinates: [
                                [
                                    [-3.213338431720785, 55.940382588499197],
                                    [-3.213340490487523, 55.940381867350276],
                                    [-3.213340490487523, 55.940381867350276],
                                    [-3.213814166228732, 55.940215021175085],
                                    [-3.21413960035129, 55.940100842843712]
                                ]
                            ]
                    }";
var result = JsonConvert.DeserializeObject<Foo>(json);

Comment: You can also have proper C# PascalCase naming by setting `ContractResolver` property to `CamelCasePropertyNamesContractResolver` instance (second parameter)
Answer: I suggest you to parse them into something more suitable like List<Tuple<double, double>> though there is also solution for nested lists. Please check my inline comments:
const string json = @"
    {
        ""coordinates"":
        [
            [
                [-3.213338431720785, 55.940382588499197],
                [-3.213340490487523, 55.940381867350276],
                [-3.213340490487523, 55.940381867350276],
                [-3.213814166228732, 55.940215021175085],
                [-3.21413960035129, 55.940100842843712]
            ]
        ]
    }";

var jsObject = JObject.Parse(json);
/*
 * 1. Read property "coordinates" of your root object
 * 2. Take first element of array under "coordinates"
 * 3. Select each pair-array and parse their values as doubles
 * 4. Make a list of it
 */
var result = jsObject["coordinates"]
                .First()
                .Select(pair => new Tuple<double, double> (
                        pair[0].Value<double>(),
                        pair[1].Value<double>()
                    )
                ).ToList();

And for List<List<List<double>>> please see @YTAM answer.
Answer: May not be exactly what you want but using dynamic type I could access the values. For example this sample code
class Program
{
    static void Main(string[] args)
    {
        string sampleJson = @"{ ""coordinates"": [
            [
                [-3.213338431720785, 55.940382588499197],
                [-3.213340490487523, 55.940381867350276],
                [-3.213340490487523, 55.940381867350276],
                [-3.213814166228732, 55.940215021175085],
                [-3.21413960035129, 55.940100842843712]
            ]
        ]}";

        dynamic d = JObject.Parse(sampleJson);

        Console.WriteLine(d.coordinates[0].Count);
        foreach (var coord in d.coordinates[0])
        {
            Console.WriteLine("{0}, {1}", coord[0], coord[1]);
        }

   Console.ReadLine();
}

displays the following:
5
-3.21333843172079, 55.9403825884992
-3.21334049048752, 55.9403818673503
-3.21334049048752, 55.9403818673503
-3.21381416622873, 55.9402150211751
-3.21413960035129, 55.9401008428437


How to select element by attr in Vue JS

Question: I will convert an application I developed with Jquery to Vue JS.
I used the function below to select an element.
Jquery Code:
function setColor(row,col) {
var element=$('[data-row=' + row + '][data-row=' + col + ']');
 element.addClass("bg-red");
}

How can I do the same with Vue JS?
Comment: Please share how you have tried it in vue so far.
Comment: I have not tried a solution with Vue js. @Tuna
Comment: I couldn't find a solution to try.
Answer: Try with $refs
Add your element to ref="yourRef", you can select it using by this.$refs.yourRef[0].$el in method
For Class styling you can use v-bind:class
Comment: I know this method, but it wasn't the solution I wanted.
That's why I created the method of adding all the elements to an array and searching within the array.
Answer: Using document.querySelector you can try like this
var element = document.querySelector('[data-row="'+ row + '"][data-cell="' + cell +'"]');
element.addClass('bg-red')

or use the class and style bindings
https://v2.vuejs.org/v2/guide/class-and-style.html

How to select element by attr in Vue JS