What is Tempo (Speed): Moderate 4

Question: I can look up the range of tempos that classify as moderate, but cannot find a source that tells me the specific bpm for:
Tempo (Speed): Moderate 4
Assuming the time signature is 4:4
Comment: This question doesn't make sense - "Moderato" or "Moderately" by definition is a range of tempi that are not too extreme in either direction.  In other words, moderate.
Comment: What is the context? I can think of one place where I've seen this: when there's a piece with many different moderatos (and other tempos) this could indicate the return of the tempo and character of whatever was played when moderato was played the 4th time. Another guess for 4 would be "in 4". This could be useful if, for example, the (beginning of the) piece/part has a 2/2 -feel and one wants moderate quarter notes instead of moderate half notes. I actually think this second interpretation is more probable since you say "moderatE 4" instead of "moderatO 4".
Comment: Can you post a picture of the marking?
Comment: What is the piece? Is a recording of it available to listen to ?
Comment: It is on page 10 from Berklee Practice Method: Guitar, I don't believe there is a recording
Comment: Hey, on the bright side, at least he's using a Mac! :-) .  Anyway, play it a few times and adjust the tempo to get the performance to emote feeling you want.
Answer: The only really awkward thing about what you posted is the "Tempo (Speed):" part. It's as if the editor is treating this as beginner music, but then using a tempo designation that you would be more likely to see in professional show books. (Then again, this is a Berklee book...)
I consider this marking to be quite a bit different from plain old "Moderato". Most definitions of Moderato I've seen are 86-97 BPM. However, that is in a classical context. Popular contemporary music is usually treated differently, and indeed, some newer metronomes are indicative of what I might call "tempo inflation," shifting BPM numbers up across the whole range of definitions.
Anyhow, the thing to realize is that any tempo marking written out in words is giving you much more information than a simple metronome marking (BPM). Words have connotations of feel, and indeed should be contextualized within the time period they were written. If you're just trying to find a mapping from the words to a BPM, you're missing the point.
So, back to the question at hand. As I mentioned above, I disagree somewhat with how the editor has decided to print this tempo mark. The way I would expect to see it in a professional show book would be "Moderate Four," just written up in the corner where the tempo is supposed to be. No need for "Tempo (Speed):" (and indeed, I think his use of the numeral 4 causes some unnecessary confusion). What this tells us is:

There is a "groove" that gives some (slight!) emphasis to all four beats in each bar (as opposed to 1 and 3 or 2 and 4)
The tempo should feel moderate (taking into account the feel/groove); not rushed, not dragging... think "walk in the park".

Guess what! It's super-subjective! (But so are a lot of things in music!) For me (and without seeing the full piece of music), this means about quarter = 110, with the groove I described above. For you or your guitar teacher it might be different, but this doesn't mean there's no wrong answer! If someone with more experience than you says it should go one way, you should probably listen to them, because the reason all of this vocabulary exists is because it has useful meaning to the professionals that play this kind of music every day.
Comment: Thanks. I thought it was a weird indication for tempo too. I've been overly technical (not amazing with theory... just over thinking). Now I've been trying to play more freely and with feeling. However, I feel like knocking out the Berklee book will put me in a good position to have a lot more ideas while trying to play more loose and freely.
Comment: Oh yeah, all I meant about Berklee was that their curriculum is geared towards contemporary popular music in the first place, as opposed to classical conservatory schools.
Answer: Moderato is specifically vague. 108 to 120 bpm is the range. No classical music needs more than this 'guide' as that term 'moderato' is sufficient. I just hope your 'moderate' is in fact 'moderato'.
Most pop music will have a metronome mark, which is far more specific, although not often adhered to particularly.
Comment: Thanks(+1), I guess I'll just practice it at 108, 112, 116 and 120.  I was just hoping there was a standard to what I posted in the image.
Answer: There is no standard "Moderate 4".  For one thing "Moderate" is English while the normal language would be Italian, "Moderato".  And incidentally more than half of the answers are for "Moderato", missing the fine difference.  So that is a good indication that this is a non-standard thing to write over a score.
Then "Moderate 4" is a crutch since "4" is not really used as an indication of note length.  Any sketch referring to a particular note value is going to use a note symbol, like "♩=80" for quarter notes at a speed of 80 per minute.
When the basis for a speed is the denominator of the time signature fraction, you don't really need to specify the reference at all.
So "Moderate 4" is likely intended to be helpful to beginners not really yet into score parlance and it suggests that whatever this was written with does not make it easy to put quarter note symbols into a heading.
Another option would be if you have an electronic keyboard with a button marked "Moderate 4" and the score is a school particularly for that keyboard.  But since we are talking about guitars here, that is not a likely scenario.

What is Tempo (Speed): Moderate 4


Adding a reference to a dll in a WCF project

Question: I've just started using WCF here at work and am trying to add a reference to a DLL that's available here at work.
I continually get this error:

Error  1   Reference required to assembly 'Name.of.the.dll.here, Version=1.0.2824.29400, Culture=neutral, PublicKeyToken=111111111' containing the implemented interface 'Name.of.the.dll.here.IInterface'. Add one to your project.

I've tried adding the reference a variety of ways (Productivity Power tools, VS2010 adding reference). The reference exists in my references folder.
The dll is targeting .NET 3.5 and my WCF is 4.0, but I'm not sure if that would make a difference.
Any clue why my refrence doesn't work?
Comment: Make sure that all the dependant assemblies of Name.of.the.dll are also added to the WCF project.
Comment: @Rajesh, add that as an answer and I'll accept it. Apparently I wasn't looking too hard and I had the `.Server` reference and it was telling me I needed the `.Shared` reference. Doh!
Answer: Make sure that all the dependant assemblies of Name.of.the.dll are also added to the WCF project


Probabilistic and/or defeasible reasoning in Protege?

Question: I have found some promising (old) articles but the trail has run cold.
Ideally I am looking for working plugins/code, but if they are simply not available, then any concrete directions on how to build probabilistic and/or defeasible reasoning for integration into Protege would still be useful.

RaMP Defeasible Reasoning plugin for Protege. Appears to be dormant/abandoned. Perhaps project/code was lost along with http://code.google.com/p/nomor/
PR-OWL http://www.pr-owl.org/. Extends OWL to support probabilistic ontologies. Appears to be dormant/abandoned.
Defeasible RuleML looked interesting, but I cannot find any concrete implementations/plugins/code. http://ruleml.org/1.0/defeasible/defeasible.html.
Defeasible Logic RuleML-compatible Rule
Language. Even if code can be found, this implementation looks experimental, and does not leverage more recent standards and formats. Paper: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.103.5914&rep=rep1&type=pdf Resources: http://lpis.csd.auth.gr/systems/resources.html#drdchairruleml2010
Answer: There's Pronto (available here), which is built on top of Pellet. I cannot recall if it comes as a Protege plugin, but as it is tied to Pellet I imagine it shouldn't be too hard to implement an OWLReasoner wrapper for the two.
Comment: As far as I can see, the code is based on an old version of Pellet which itself is based on OWL API v3. Might lead to some conflicts
Comment: I gave it a bash to try and compile it with a newer OWLAPI, but this was a few years ago. Getting it to work on Protege 4.3 should be ok, Protege 5 a bit more challenging.


equivalent conditions of u.a.n

Question: Suppose that $X_{1},X_{2},\cdots$
  are independent random variables with mean $E[X_{k}]=m_{k}$ and variance $Var(X_{k})=\sigma_{k}^2$, and define $D_{n}^2=Var(X_{1}+\cdots+ X_{n})$.Show that
$\{\frac{X_{k}-m_{k}}{D_{n}},1\le k\le n,n\ge 1\}$ are u.a.n sequences iff $\lim\limits_{n\to\infty}\max\limits _{1\le k\le n}\frac{\sigma_{k}^2}{D_{n}^2}=0$. I have figured out the sufficient ,but the neccesity I have no idea .Would you give me some suggestion?Thank you.
Comment: Could you define "u.a.n." (uniform asymptotic normality?)?
Comment: @Davide Giraudo $\{a_{nk},1\le k\le n,n\ge 1\}$are u.a.n sequences if $\lim\limits_{n\to\infty}\max\limits _{1\le k\le n}P\{|a_{nk}|\ge \varepsilon\}=0$.
Answer: Assume that u.a.n. does not hold hence there exists $\varepsilon\gt0$ and some sequences $(n(i))$ and $(k(i))$ such that $n(i)\to\infty$ when $i\to\infty$, $1\leqslant k(i)\leqslant n(i)$ and $P[|X_{k(i)}-m_{k(i)}|\geqslant\varepsilon D_{n(i)}]\geqslant\varepsilon$ for every $i$. In particular, for every $i$,
$$
\sigma^2_{k(i)}=E[(X_{k(i)}-m_{k(i)})^2)\geqslant(\varepsilon D_{n(i)})^2P[|X_{k(i)}-m_{k(i)}|\geqslant\varepsilon D_{n(i)}]\geqslant\varepsilon^3D_{n(i)}^2,
$$
hence $\max\limits_{1\leqslant k\leqslant n(i)}\sigma^2_k/D_{n(i)}^2\geqslant\varepsilon^3$. This contradicts the condition that $\max\limits_{1\leqslant k\leqslant n}\sigma^2_k/D_{n}^2$ converges to zero.
(You said you figured out the other implication.)
Comment: @Did.Thank you for your answer,but how about the other implication?Maybe there is something wrong with my expression.I just want to verify the other.Thank you for your time and consideration again.
Comment: Since you wrote "I have figured out the sufficient", I thought you had figured out the other implication. If you want somebody to check your proof, show your proof.
Comment: ,sorry.I think I'm confusing the sufficency with necessity .Thank you for your time and consideration again.

equivalent conditions of u.a.n


Função não dispara

Question: Estou começando a trabalhar / aprender o DOM, porém estou tendo dificuldades, pois:

        const celsius = document.getElementsByName('celsius')[0]
        const fahrenheit = document.getElementsByName('fahrenheit')[0]
        const buttonClear = document.getElementsByName('limpar')[0]
        const buttonSubmit = document.getElementsByName('converter')[0]

        //buttonClear.addEventListener('click', limparBox(celsius, fahrenheit))
        //buttonClear.onclick = limparBox(celsius, fahrenheit)

        function limparBox(input1, input2) {
            input1.value = "";
            input2.value = "";
        }
input[type=text] {
  padding: 5px;
  border: solid 1px black;
  font-style: italic;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  text-align: center;
  border-radius: 2px;
}

button[type=submit] {
  background-color: #74f541;
  padding: 10px;
  font-weight: bold;
  border-radius: 3px;
  border: solid 1px black;
}

button[type=reset] {
  background-color: #f2fa83;
  padding: 10px;
  font-weight: bold;
  border-radius: 3px;
  border: solid 1px black;
}
<input type="text" name="celsius" placeholder="Celsius">
<button type="submit" name="converter">Converter para Fahrenheit</button>
<button type="reset" name="limpar">Limpar Textos</button>
<input type="text" name="fahrenheit" placeholder="Fahrenheit">

Essa minha function se eu executar no console do próprio browser as caixas são limpas, porém quando eu coloco ela (function) para executar ao click de um button não é chamada, tentei tanto por meio de uma callback quanto por uma propriedade onclick.
Também só é possível acessar os elementos DOM estando no escopo global do javascript?
Comment: Qual seria o problema da minha pergunta por favor para que nas futuras eu tenha um desempenho melhor na pontuação?
Answer: Seu código não está funcionando porque você não está passando uma função para o evento de onclick.
buttonClear.addEventListener('click', limparBox(celsius, fahrenheit))
buttonClear.onclick = limparBox(celsius, fahrenheit)

Nessas duas linhas de código, você está invocando a função limparBox e passando o retorno dela como handler, mas essa função nem sequer tem um retorno (não que ela precise).
Para passar uma função, você precisa passar o nome da função sem invoca-la, por exemplo:
buttonClear.addEventListener('click', limparBox)
buttonClear.onclick = limparBox

Mas isso não vai dar muito certo no seu caso, pois você quer invocar as funções passando os parâmetros celsius e fahrenheit, então ao invés disso, você pode criar uma nova função anônima, e invocar a função limparBox com os parâmetros corretos dentro dela:
buttonClear.addEventListener('click', function() {
    limparBox(celsius, fahrenheit)
})

//ou

buttonClear.onclick = function() {
    limparBox(celsius, fahrenheit)
}

E você não precisa estar no escopo global para acessar o DOM, o objeto document é acessível globalmente, o que significa que você pode acessa-lo dentro de qualquer escopo, seu código poderia ser escrito da seguinte forma também:
// handler para limpar os inputs
document.getElementsByName('limpar')[0].addEventListener('click', function() {
    const celsius = document.getElementsByName('celsius')[0]
    const fahrenheit = document.getElementsByName('fahrenheit')[0]

    celcius.value = ''
    fahrenheit.value = ''
})

Comment: Obrigado por disponibilizar seu tempo para responder minha perguntar. Tentarei pesquisar e formalizar mais minha pergunta da próxima vez.

Função não dispara


Double sum of natural numbers squared

Question: I am wondering how you would compute a double sum such as
$$\sum_{n=0}^{p}\sum_{m=0}^n (m+n)^2$$
I understand methods for finding closed forms of sums using Discrete Calculus from reading Concrete Mathematics where for example one could view $\sum_{m=1}^p m^2 = \sum_{m=1}^p \Delta(\frac{1}{3}m^{\underline{3}}+\frac{1}{2}m^{\underline{2}})$ and then using the fact the the sum telescopes. I run into trouble applying that approach here because I get terms such as $(2n+1)^{\underline{2}}$. Is it possible to realize this as the forward difference of something? If it's not then what is a way to evaluate the sum?
Comment: I am not sure how helpful this is but your sum can be shown to be equal to $\sum\limits_{n=1}^p [n^2+(n+1)^2+\cdots+(2n)^2]$.
Comment: Another method would be to develop : $(n + m)^2 = n^2 + 2nm + m^2$. Each sum of squares is known, and the sum with term $nm$ is also known I think, but otherwise juste use the trick of @ShyamalSayak
Comment: @eti902 Good point.
Comment: Welcome to Math SE. FYI, using an [Approach0 search](https://approach0.xyz/search/?q=OR%20content%3A%24%5Csum_%7Bn%3D0%7D%5E%7Bp%7D%5Csum_%7Bm%3D0%7D%5En(m%2Bn)%5E2%24&p=1), there's the similar [exact closed form expression](/q/2994151), where the [answer](/a/2994285) shows the expression is equivalent to $\sum_{i=0}^n\sum_{j=0}^n(i+j)^2$, i.e., where the upper limit of both summations is the same, fixed value of $n$, while only the outer summation of yours has a fixed value of $p$.
Answer: I'm offhand unaware how to determine the summations using forward differences. Instead, with the Faulhaber's formula examples, and eti902's comment suggestion, we get for the inner summation
$$\begin{equation}\begin{aligned}
\sum_{m=0}^{n}(m^2+2mn+n^2) & = \sum_{m=0}^{n}m^2 + 2n\sum_{m=0}^{n}m + n^2\sum_{m=0}^{n}1 \\
& = \left(\frac{n^3}{3}+\frac{n^2}{2}+\frac{n}{6}\right)+2n\left(\frac{n^2+n} {2}\right) + n^2(n+1) \\
& = \left(\frac{n^3}{3}+\frac{n^2}{2}+\frac{n}{6}\right)+ (n^3+n^2) + (n^3+n^2) \\
& = \frac{7n^3}{3} + \frac{5n^2}{2} + \frac{n}{6}
\end{aligned}\end{equation}$$
Alternatively, based on ShyamalSayak's comment suggestion, using $i = m+n$, we instead get
$$\begin{equation}\begin{aligned}
\sum_{m=0}^{n}(m+n)^2 & = \sum_{i=n}^{2n}i^2 \\
& = \sum_{i=0}^{2n}i^2 - \sum_{i=0}^{n-1}i^2 \\
& = \left(\frac{(2n)^3}{3} + \frac{(2n)^2}{2} + \frac{2n}{6}\right) - \left(\frac{(n-1)^3}{3} + \frac{(n-1)^2}{2} + \frac{n-1}{6}\right) \\
& = \left(\frac{8n^3}{3} + 2n^2 + \frac{n}{3}\right) - \left(\frac{n^3-3n^2+3n-1}{3} + \frac{n^2-2n+1}{2} + \frac{n-1}{6}\right) \\
& = \frac{7n^3}{3} + \frac{5n^2}{2} + \frac{n}{6}
\end{aligned}\end{equation}$$
In either case, the outer summation is then
$$\begin{equation}\begin{aligned}
\sum_{n=0}^{p}\left(\frac{7n^3}{3} + \frac{5n^2}{2} + \frac{n}{6}\right) & = \frac{7}{3}\sum_{n=0}^{p}n^3 + \frac{5}{2}\sum_{n=0}^{p}n^2 + \frac{1}{6}\sum_{n=0}^{p}n \\
& = \frac{7}{3}\left(\frac{p^4}{4}+\frac{p^3}{2}+\frac{p^2}{4}\right) + \frac{5}{2}\left(\frac{p^3}{3}+\frac{p^2}{2}+\frac{p}{6}\right) + \frac{1}{6}\left(\frac{p^2+p}{2}\right) \\
& = \frac{7p^4}{12} + 2p^3 + \frac{23}{12}p^2 + \frac{p}{2} \\
& = \frac{p(p+1)(7p^2+17p+6)}{12} \\
& = \frac{p(p+1)(p+2)(7p+3)}{12}
\end{aligned}\end{equation}$$

Double sum of natural numbers squared


SubSonic Alias/Where Clause

Question: I want to convert the following SQL Query to a SubSonic Query.

SELECT [dbo].[tbl_Agency].[ParentCompanyID]
 FROM [dbo].[tbl_Agency]
 WHERE REPLACE(PhoneNumber, ' ', '') LIKE REPLACE('%9481 1111%', ' ', '')

I thought I would do it like below, but I just can't get it to produce valid SQL.
     //SubSonic
     string agencyPhoneNumber = "9481 1111";
     SubSonic.SqlQuery subQueryagencyPhoneNumber = new SubSonic.Select(Agency.ParentCompanyIDColumn.ColumnName);
            subQueryagencyPhoneNumber.From(Agency.Schema.TableName);

     //WHERE
     subQueryagencyPhoneNumber.Where("REPLACE(" + Agency.PhoneNumberColumn.ColumnName + ", ' ', '')").Like("%" + agencyPhoneNumber + "%");

Does anyone out there know how to fix this - I'm using SubSonic 2.2.
I feel like I'm taking crazy pills here - this should be straightforward, right?
Cheers,
JohnBob
Answer: I think you'll need to add the like expression to the inline SQL.
Something like:
var whereSql = string.Format("REPLACE({0}, ' ', '') Like '%{1}%'", Agency.PhoneNumberColumn.ColumnName, agencyPhoneNumber);

subQueryagencyPhoneNumber.Where(whereSql);

See a similar question at Calling an SQL function from a Subsonic.Select
Comment: Thanks for the comment, but this didn't work.
It doesn't register the above statement as a valid constraint.
Comment: Gave up and did it as a stored procedure with dynamic sql.
blazergh! Wanted to do it in SubSonic, ah well.
Comment: @JohnBob Could always do it as a CodingHorror to keep all the logic in code
Answer: If worst comes to worst with really complicated queries you can still use subsonic using the .CodingHorror() methods as described @ http://subsonicproject.com/docs/CodingHorror
As long as you select valid column names that subsonic knows about when you cast the collection -> .ExecuteAsCollection() you'll be fine and still be able to use you Active record.
This has saved me a lot of times when i've had really large complicated queries. Just make sure you still use the parameters and clean your statements so that your input is sanitized.

SubSonic Alias/Where Clause


Autohotkey. Increasing send key iterations

Question: I'd like to be able to send the TAB key an ever-increasing number of times as part of a loop. Essentially, I want to cycle through some parts of the webpage with tab, get to where I need to be, do some stuff, and start over. But each time I start over, I will have added two additional items that need to be cycled through. So I need a loop that looks like this:
n = 1
Start the loop
Send {Tab n}
DO STUFF
n += 2
Repeat the loop with n updated

I'm not sure if I can use variables like that, however. Any suggestions would be most appreciated.
Answer: Something like this?
n = 1
Loop ; Start the loop
{
    Msgbox % "n = " n
    SendInput, % "{Tab " n "}"
    ; DO STUFF
    n += 2
} ; Repeat the loop with n updated

You can check the documentation here: Loop
Comment: You're not referencing the variable `n`. Use `SendInput, % "{Tab " n "}"` or `SendInput, {Tab %n%}` in legacy (please don't use legacy). Also switch to using [`SendInput`](https://www.autohotkey.com/docs/commands/Send.htm#SendInputDetail). And [here's](https://www.autohotkey.com/docs/commands/Send.htm#Repeating_or_Holding_Down_a_Key) the documentation link for the repeating key syntax in a `Send` -command.


How to use Pattern layout with SocketAppender

Question: I read org.apache.log4j.net.SocketAppender does not use a Layout.
But, I really need to format my logs and I need to use a ConversionPattern.
Does anybody know an alternate to this? I have to use some kind of SocketAppender.
Thanks
Comment: Aside from the accepted answer, https://stackoverflow.com/a/46218631/1290868 may help
Answer: The logs sent through a SocketAppender are serialized and can't have a layout specified to it until it is deserialized. On the remote host you'll have access to all the same information and should be able to specify the layout that the logs are printed in. So the difference is only that you specify the layout on the other side.


Adding java directory to my path automatically

Question: I'm doing this in my makefile to try and get the PATH to Java, but the resulting string from find isn't escaped properly to be used in bash, how do I get find to return the escaped path to java.exe?
JAVA_EXE := "$(shell find /c/Program\ Files\ \(x86\)/Java/ -type f -name 'java.exe' -print0 -quit)"
JAVA_PATH := $(dir $(JAVA_EXE))

Comment: You sure you need it to be escaped? You can directly write to a makefile variable named `PATH`, then do `export PATH` to turn it into an environment variable.
Comment: JAVA_EXE contains the location of the file non-escaped and usable to execute, but I need the path to the file not the file itself
Comment: I get it, but what are you planning to do with the path? Do you want to add it to the `PATH` variable?
Comment: Yes, for the path but I need two distinct variables. One to the executable and another *for adding to path*
Comment: Then my first comment applies. You might not need to escape it to add it to the `PATH`.
Comment: You are probably correct, but I definitely have to do something with it, because it contains the filename java.exe at the moment
Comment: Didn't you remove the filename using `$(dir ...)`?
Comment: I tried, but that doesn't work because the filename is invalid in bash  (i.e. contains spaces and ( and ) which are unescaped
Comment: Do not add quotes around the results of the `$(shell ...)` command.  That is wrong. See https://stackoverflow.com/questions/23330243/gnu-makefile-how-to-and-when-to-quote-strings/23332194#23332194
Comment: The short answer is, you cannot use paths containing spaces in makefiles.  You definitely cannot use them with any make functions like `dir`, etc.  Sorry about that.
Comment: @MadScientist I don't believe that is true if I can get an escaped answer from find
Comment: `dir` is a make function.  Make has no facility for escaping whitespace.  There's no way to get the make function `$(dir ....)` to work the right way, if `...` is a path containing whitespace.
Comment: I can remove the java.exe with

JAVA_PATH := $(subst java.exe,,$(JAVA_EXE))

This still doesn't answer my main question which is how to get  an escaped directory from find...
Answer: Ok, so I've learned a lot since I last posted this question.
I needed a script, like so called addJavaToPath.sh
#!/bin/sh
JAVA_EXE=$(find "/c/Program Files" -type f -name java.exe -print -quit 2>/dev/null)
echo JAVA_EXE: $JAVA_EXE
JAVA_PATH=${JAVA_EXE%'java.exe'}
echo JAVA_PATH: $JAVA_PATH
export PATH=$PATH:"$JAVA_PATH"

and then you type:
source addJavaToPath.sh

it needs to be sourced because you want to mess with path and normally that export would only last for the life of the script


How to rewrite this PHP function to ruby?

Question: I am newbie in ruby and regular expressions and I have this function write in PHP, and I would need to rewrite it to Ruby.
function date_number_id($id_number) {
    if (preg_match('~^([0-9]{2})([0-9]{2})([0-9]{2})/([0-9]{3,4})$~', $id_number, $match)) {
        return (strlen($match[4]) < 4 || $match[1] >= 54 ? "19" : "20") . "$match[1]-" . sprintf("%02d", $match[2] % 50) . "-$match[3]";
    }
    else
    {
      return false;
    }
}

Could you help me please, with it?
Many thanks!
EDIT: This is a function that prints from the identification number the birthday day. The input is for example: 890807/5089
Comment: It always helps to provide some input/output for people who are not into PHP but still willing to help.
Comment: Hm - that example won't match - you're requiring a slash after the first 6 chars in your regexp...
Comment: Sorry @Amadan, my inattention. Fixed.
Answer: Unless I missed something...
def date_number_id(id_number)
  match = /^([0-9]{2})([0-9]{2})([0-9]{2})\/([0-9]{3,4})$/.match(id_number)
  if match
    return "#{match[4].to_i < 4 || match[1].to_i >= 54 ? '19' : '20'}#{match[1]}-#{sprintf("%02d", match[2].to_i % 50)}-#{match[3]}"
  else
    return false
  end
end

I think the mapping to PHP is obvious, but if there's something you don't understand why it is so, ask.


Equivalent to Oracle NTH_VALUE function

Question: Let us have the following data
CREATE TABLE [dbo].[LogTable] ([DateSent] [datetime] NULL)
GO
CREATE CLUSTERED INDEX [IX_LogTable_DateSent] ON [dbo].[LogTable] ([DateSent] DESC)
GO

INSERT INTO [LogTable]
SELECT TOP 500000 NULL, DATEADD(day, ( ABS(CHECKSUM(NEWID())) % 65530 ), 0)
FROM sys.sysobjects
CROSS JOIN sys.all_columns

I would like to find the second and the third lowest value for each year in DateSent. Oracle offers the NTH_VALUE function for that, however, there is no such thing in SQL Server. I have created the following query
SELECT YEAR(datesent),
(
    SELECT datesent
    FROM
    (
        SELECT datesent, ROW_NUMBER() OVER (ORDER BY datesent) r
        FROM logtable
        WHERE YEAR(datesent) = YEAR(lt.datesent)
    ) logtable_ranked
    WHERE logtable_ranked.r = 2
) second_lowest_in_year,
(
    SELECT datesent
    FROM
    (
        SELECT datesent, ROW_NUMBER() OVER (ORDER BY datesent) r
        FROM logtable
        WHERE YEAR(datesent) = YEAR(lt.datesent)
    ) logtable_ranked
    WHERE logtable_ranked.r = 3
) thirt_lowest_in_year
FROM logtable lt
GROUP BY YEAR(datesent)

which returns the correct result, but it takes more than 7s CPU time on my server. Moreover, time of this solution grows linearly with a number of NTH values I need.  Is there a better (faster and maybe more elegant) way to compute NTH_VALUE in SQL Server?
Answer: Use row_number() and conditional aggregation:
SELECT YEAR(datesent),
       MAX(CASE WHEN seqnum = 1 THEN datesent END) AS datesent_1,
       MAX(CASE WHEN seqnum = 2 THEN datesent END) AS datesent_2,
       MAX(CASE WHEN seqnum = 3 THEN datesent END) AS datesent_3
FROM (SELECT datesent,
             ROW_NUMBER() OVER (PARTITION BY YEAR(datesent) ORDER BY datesent) AS seqnum
      FROM LogTable lt
     ) lt
GROUP BY YEAR(datesent)
ORDER BY YEAR(datesent);

Comment: really nice one. take less than 2s of CPU time to execute.

Equivalent to Oracle NTH_VALUE function


Why is remote desktop still not working?

Question: I regularly use remote desktop to connect to PC's at work instead of going an physically sitting on the machine. We have 2 new computers, 1. Windows 7 2. Windows 8.1 ... I'm trying to connect to them view their internal IP address and it's not having any of it.
On the computers in question I have:

Enabled Remote Desktop in Computer Properties.
Allowed the port through the Firewall.
Allowed Remote Desktop through the firewall.
Fixed the IP address so it doesn't change.
Stopped the computer sleeping.
Enabled Network sharing and visibility options.

I'm running out of ideas and I need to get this up and running before we apply the external ip addresses.
As I mentioned I can remote to other PC's in the office, so it shouldn't be anything wrong with the network.
Comment: If you try and ping the computers, do you get a response? When you say enabled, did you also give permissions to your user to rdp in? What is the actual error message that you're getting (besides the machine wanting none of your rdping)
Comment: how about defining "It's not having any of it"? I'm not aware of that being a recognised error message anywhere in Windows in general, let alone the client or server side of the RDP stack in particular.
Comment: `and it's not having any of it` What does this mean??? What error-message are you getting. Does the machine you're trying to control have a password for the account you're using to get in?
Comment: What checkbox did you tick when enabling RDP? `Allow... with any version or RDP` or the more secure `Only allow with NLA`? What version of Windows do you have on your own PC?
Comment: @Rik I have tried connecting from Windows 7 & 8, the options that have been ticket are that available; Allow remote connections to this computer this is the only tick box available on the machine, it's running Windows 7 Home Premium.

I do have additional options on my computer which is running Windows 7 Proffesional, for example the option you mentioned.

But that tick box option isn't available on the computer I'm attempting to connect with.
Comment: @Reaces when I ping the IP Addresss I get a response and the time is 5ms and TTL: 128 ... The error message is the general one where it says check the network, computer is turned on and remote desktop is enabled.
Comment: @Rik I get the general error message where it ask's you to check the computer is on and that remote desktop is enabled.
Answer: You have a Windows 7 Home Premium. That version doesn't allow access via Remote Desktop. The ticked option you mention is for "Remote Assistance". You need to "invite" the remote party to view your computer with "Remote Assistance". You can see this from the checkbox is in the "Remote Assitance" groupbox and not in the "Remote Desktop" groupbox.
If you want to use RDP onto this machine you'll need to upgrade to Professional or use another form of remote control.


How to write camera and gallery access permission on the Info.plist file

Question: After submission for review, I got this from Apple review:

We noticed that your app requests the user's consent to access the camera and photos, but doesn't sufficiently explain the use of the camera and photos in the purpose string.

In my app, camera and gallery access is needed in various places like for uploading product images, sending images to chat, posting images in the news feed, and uploading profile photo.
Apple requires an explanation to why the camera and gallery are being accessed.
If I explain the use for uploading profile image, this is irrelevant if they upload a product and also needs another explanation if the user will send photos to chat.
So the question is how can I generalize the camera's purpose string in a way that it can cover all my camera usage given that the purpose string is only one.
Or is there a way to write a camera purpose string for each and every camera usage?
Answer: Yes, @john we have to elaborate properly as they show the same message to the user on the permission popup.
I am using the below statement & app is accepted by AppStore
<code><key>NSCameraUsageDescription</key>
    <string>Access to your camera is required to capture photos required for loan processing or your profile.</string>
    <key>NSLocationUsageDescription</key>
    <string>To show your location on the map.</string>
</code>
Hope this will work!
Answer: There's no way to have multiple purpose strings because Apple is not allowing you to customize the permission dialog.
You can just put what they are used for in one sentence, like "Need your permission to Photo Gallery for post or chat"
I got the same response the other day. My case is using the photo for feedback or a user avatar. So I just put all of them in that string
Hope this will help.
Comment: `Need your permission to Photo Gallery for post or chat` apple doesn't accept this. I  already tried it.


why create-react-app create project and yarn start has error 'Cannot read property 'indexOf' of undefined'?

Question: i'm use create-react-app create project, and after yarn eject, i change webpack.config.js 'entry' propetry, and paths 'module.exports={}', when i yarn start, i get the error 'Cannot read property 'indexOf' of undefined'. i don't know where is mistakes.
env: macos 14
node: v10.13.0
npm: v6.11.3
yarn: 1.15.2
react: v16.9.0
webpack.config.js:
entry: {
      index: [
        paths.appIndexJs,
        isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient')
      ].filter(Boolean),
      query: [
        paths.appQueryJs,
        isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient')
      ].filter(Boolean),
      order: [
        paths.appOrderJs,
        isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient')
      ].filter(Boolean),
      ticketPage: [
        paths.appTicketPageJs,
        isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient')
      ].filter(Boolean)
    },

paths.js
module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),

  // this is new
  appQueryHtml: resolveApp('public/query.html'),
  appOrderHtml: resolveApp('public/order.html'),
  appticketPageHtml: resolveApp('public/ticketPage.html'),
  appIndexJs: resolveModule(resolveApp, 'src/index/index'),
  appQueryJs: resolveModule(resolveApp, 'src/query/index'),
  appTicketPageJs: resolveModule(resolveApp, 'src/ticketPage/index'),
  appOrderJs: resolveModule(resolveApp, 'src/order/index'),
  // new over

  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/setupTests'),
  proxySetup: resolveApp('src/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
};

i expect running 'yarn start', the react project is ok!
project folder:

(source: labike.xyz)
error:

(source: labike.xyz)
Answer: i found the error in paths.js:
module.exports = {
    ...
    appTicketPage: ...
}

i'm write error!


Name resolution in an IPv6 network without a DNS server

Question: Background:

I have a network with Windows and Linux machines
The router doesn't support IPv6, but the computers have link-local addresses (fe80::/10), and I plan to buy an IPv6-capable router in the future
I'm currently learning about IPv6 and experimenting with it, so there is no immediate problem to solve (since IPv4 works), but I want to learn about it now so it doesn't bite me later
I do not want to run a DNS server (for various reasons, such as not having a machine running 100% of the time, and not wanting to use static addresses)
IPv4 name resolution works using NBNS/WINS broadcast (natively on windows machines and using Samba/nmblookup on Linux machines).
If, for some reason, name resolution doesn't work, I can always resort to IPv4 literals, as I can easily memorize the last byte of a 192.168.1.0/24 address.

Now, the problem is that NBNS/WINS doesn't work with IPv6, so there is no name resolution. I can ping literal IPv6 addresses (after back-and-forth read/type cycles and lots of eye-squinting to find a single digit error...), but that's about it. I cannot do any name resolution. And unlike with IPv4, literal IPv6 addresses are not practical to use.
tl;dr: What's the equivalent of NBNS/WINS broadcast for ad-hoc name resolution on IPv6 networks?
Comment: Please read the FAQ.
Comment: @JohnGardeniers My apologies, I forgot that home networks belong to SU. But on the other hand, I also administer a small network at work, and I'm experimenting with IPv6 in my home network so I apply it later at work (no harm done if I break my home network). I'll remove "home" from my question.
Comment: Oh, and if a moderator feels that the question is more suitable for SU, feel free to migrate it.
Answer: You can use multicast DNS, which will provide you with <code>.local</code> domain names. This is implemented on Mac OS X, on Linux using Avahi, and on Windows using the Bonjour Print Services.
If you have a pure Windows Vista or 7 environment, you might be better off using Link-Local Multicast Name Resolution. You will need to make sure you enable the Network Discovery service; it is pretty poorly documented as far as I can see.
Comment: Thanks, Avahi and Bonjour Print Services did the trick, although I have to add ".local" to hostnames for multicast DNS to work. I also noticed that the Windows machines are already doing LLMNR among themselves.
Comment: You could probably add `.local` as a default search suffix, although I have not tested this on Windows and can't confirm that it works.
Answer: Name Resolution in IPv6 Networks does not work by itself.It depends on NetBios,WINS OR DNS servers.If for any reason the above mentioned services are not available, you cannot connect
a name server merely by its name. You should have IPv4 or IPV6 addresses of the machine
Comment: WINS is not supported on IPv6, per Microsoft.http://blogs.technet.com/b/askpfeplat/archive/2013/11/11/ipv6-for-the-windows-administrator-how-name-resolution-works-in-a-dual-ipv4-ipv6-scenario.aspx


Node JS(Express) connect-flash not working on redirects action

Question: I'm wondering why my connect-flash is not working.
I know connect-flash try to save message into session.
So I declare session like this :
app.use(session());

Then I set up flash :
app.use(flash());

The problem is that when I using with connect-flash, it didn't show just set message after redirect action.
req.flash('flash_var', 'ok');
res.redirect('/mail/send');

I couldn't see any message at the '/mail/send' routers.
app.get('/mail/send', function(req, res) {
  res.render('mail/console', {
    console.log("flash : "+req.flash('flash_var'); // null
    message: req.flash('flash_var')
  });
});

The console message are printing null values, The previous step does not seem to send the value normally. Of course I didn't see any 'flash_var' at ejs page.
What's wrong with my code?
if(req.flash("flash_var") != ""){
  flash_var = req.flash("flash_var");
  console.dir("flash_var dir : "+req.flash("flash_var"));
}

Answer: You don't use req.flash('flash_name') to get a flash message back. What you would do is req.flash()['flash_name']. In your case the message value in your res.render options object would be req.flash()['flash_var']. req.flash() is not an individual getter, it returns an object containing all flashes on the request object. The other way to use req.flash() is with two string inputs, like you did with req.flash('flash_var', 'ok').


Feeds: update nodes using a second import

Question: Is there a way in which you can use a second feeds import, to update nodes created during a first import?
In my first import, I create nodes and save a custom ID (from old system), and I want to reuse that custom ID in the second import to update the existing nodes and add a taxonomy value.

First importer:

Second importer:
Answer: To update existing content using feeds importer, you will have to mark Customer ID field as a Unique Key.
Comment: Where can you set that? I only see the option to put it as **Unique Key**
Comment: and do you need to do this in both importers or only in the 2nd one?
Comment: Yes you are right, thats Unique Key.
Comment: That doesn't work, it keeps on creating new nodes, instead of updating the existing ones based in the Custom ID
Comment: Have you selected Update existing content in module configuration?
Comment: Yes, I also tried with Replace but that has the same effect
Comment: Please share field mapping and configuration screenshot into your question.
Comment: Uploaded images..
Comment: In 2nd import, select zaal_id(field_zaal_id) as target instead of GUID.
Comment: You mean temporary target? http://cl.ly/image/2S0Z2O3V2e25?_ga=1.260744271.392578222.1446191095
Comment: Yeah right!!! :)
Comment: Temporary target doens't work, it does work when I add the field_zaal_id as target! Many thanks!


System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0. 3

Question: I am trying to make a .NET Core Web API but I couldn't find out a solution for my problem.
Full error is

[ERR] An exception occurred in the database while iterating the results of a query for context type '"MailAlertWebApiWithEF.Data.AlertContext"'."
""System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

I get that configuration codes from an existing database with

Scaffold-DbContext "server=.;ConnectionString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DBModels -force -v

My configuration is:
 public class AlertModelConfiguration<T>:BaseEntityModelConfiguration<T,int> where T:Alert
{

    public AlertModelConfiguration(ref ModelBuilder modelBuilder):base(ref modelBuilder)
    {
        modelBuilder.Entity<Alert>(entity =>
        {
            //entity.HasKey(e => e.AlertId);

            entity.Property(e => e.CreateDate).HasColumnType("datetime");

            entity.Property(e => e.DeleteDate).HasColumnType("datetime");

            entity.Property(e => e.Detail)
                .IsRequired()
                .HasMaxLength(2046)
                .IsUnicode(false);

            entity.Property(e => e.ErrorDetail)
                .IsRequired()
                .HasMaxLength(255)
                .IsUnicode(false);

            entity.Property(e => e.Title)
                .HasMaxLength(50)
                .IsUnicode(false);

            entity.Property(e => e.UpdateDate).HasColumnType("datetime");
        });
     }
}

My context is:
 public class AlertContext:DbContext
  {
    public AlertContext(DbContextOptions<AlertContext> options)
        : base(options)
    {

    }

    public virtual DbSet<Alert> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        new AlertModelConfiguration<Alert>(ref modelBuilder);

        base.OnModelCreating(modelBuilder);
    }
}

My ConnectionStrings inside at appsettings.json:
ConnectionStrings": {
   "AlertContext": "server=.;database=*****;poling=false;Connect
 Timeout=60;Integrated Security=SSPI"

When I start at debug mode the API gets stuck inside the engine layer.
My Engine and IEngine:
Task<CustomListEntity<Alert>> GetByIdAsync(int id);

 public  Task<CustomListEntity<Alert>> GetByIdAsync(int id)
    {
        return  CommonOperationAsync(async () =>
         {
             var predicate = PredicateBuilder.True<Alert>();
             predicate = predicate.And(p => p.Id == id);

             return new CustomListEntity<Alert>()
             {
                 EntityList = await _alertReqository.GetAll(skip: 0, take: 10, predicate: predicate,
                     orderExpression: null, rowCount: out var count, ascending: false).ToListAsync(),

                 Count = count,
             };
         }, new BusinessBaseRequest()
         {
             MethodBase = MethodBase.GetCurrentMethod()
         }, BusinessUtilMethod.CheckRecordIsExist, GetType().Name);
    }

I tried my own configuration file but the result is the same. What is wrong?
Answer: This error indicates that your connection string is not correct.
There is a typo in the word "pooling", try with the following connection string:
ConnectionStrings": {
         "AlertContext": "server=.;database=*****;pooling=false;
                 Timeout=60;Integrated Security=SSPI"

If still not working, make sure the server and database values are OK.
Answer: I also experienced this same error, but the problem is not with the connection string, but due to some confusions like below:
In Startup.cs file, I have added the below setting which is wrong:
services.AddDbContext<EFCFWithExistingDBContext>(x => x.UseSqlServer(MyDatabaseConnection));

Below is the right code. My error has gone.
services.AddDbContext<EFCFWithExistingDBContext>(x => x.UseSqlServer(Configuration.GetConnectionString("MyDatabaseConnection")));


Como mudar posição de uma table no vuejs

Question: Atualmente se encontra assim:

Na verdade era para ficar assim;

Estou tendo dificuldade, alguém pode me ajudar, por favor?
Esse é o código fonte.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Desenvolvido por Wladimir Alves Bandeira</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" >

                Tipo de moeda
                Valor
                Referencia

                 {{  val.nome }}
                 {{  val.valor }}
                {{  val.fonte }}

Comment: Está do outro jeito por está herdando todas as classes da tabela do Bootstrap 4. Para resolver isso vc vai ter que encapsular sua tabela dentro de um container e fazer um override com as classes do jeito que vc deseja. Se quiser eu posso fazer um modelo simples pra vc.
Comment: mostre para mim um modelo por favor.
Answer: No caso, vou realizar a resposta mediante ao que você disse:

Na verdade era para ficar assim;

Estou dizendo isto pois a maneira como as informações estão inseridas na tabela da maneira que está para a maneira que você quer, estão distintas. Se você deseja trazer no cabeçalho apenas as moedas, basta fazer o v-for no th e outro no td.
Depois, deve alterar as classes, segue exemplo abaixo que ficou semelhante ao resultado esperado ao meu ver:

new Vue({
  el: '#app',
  data() {
    return {
      bancodedados: [
        {
          nome: 'Dóla',
          valor: 32.889,
          fonte: 'azul'
        },
        {
          nome: 'Euro',
          valor: 40.605,
          fonte: 'azul'
        },
        {
          nome: 'Peso Argentino',
          valor: 0.1629,
          fonte: 'azul'
        },
        {
          nome: 'Libra Esterlina',
          valor: 4.615,
          fonte: 'azul'
        },
        {
          nome: 'Bitcoin',
          valor: 28050,
          fonte: 'azul'
        }
      ]
    }
  }
});
.table th, .table td {
  border: 3px solid black !important;
  text-align: center;
}

.table th {
  font-weight: normal;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

          {{ val.nome }}

            {{  val.valor }}


Tricky Triangle Area Problem

Question: This was from a recent math competition that I was in. So, a triangle has sides $2$ , $5$, and $\sqrt{33}$. How can I derive the area? I can't use a calculator, and (the form of) Heron's formula (that I had memorized) is impossible with the$\sqrt{33}$ in it. How could I have done this? The answer was $2\sqrt{6}$ if it helps.

Edited to add that it was a multiple choice question, with possible answers:
a. $2\sqrt{6}$
b. $5$
c. $3\sqrt{6}$
d. $5\sqrt{6}$
Comment: Did you actually try to use Heron's formula? The formula simplifies pretty nicely.
Comment: Are you familiar with the Law of Cosines?
Comment: @2012ssohn Of course i am, but how can i apply that formula to it? I even tried it at the time, but couldnt get anything useful about area from it
Comment: When i tried it i got an ugly glob of roots and addition that just wouldn't simplify for me. Maybe i just need to practice simplification
Comment: @JohnJPershing: Try multiplying-out factors of Heron's formula *before* substituting the specific side-lengths. Note that, if you think of the factors as something like $$\frac{1}{16}\;\cdot\;((b+c)+a)\;((b+c)-a)\;\cdot\;(a-(b-c))\;(a+(b-c))$$ then you can save a *little* mental energy recognizing that a couple of differences-of-squares come into play during the process.
Comment: Just out of curiosity, which competition was that?
Comment: Down at the USA Science and Engineering Festival, there was a game of "Who wants to be a mathematician" hosted by the AMS, and this was a question for it
Answer: From the law of cosines ($C^2 = A^2 + B^2 - 2AB\cos \theta$), we get that $(\sqrt{33})^2 = 2^2 + 5^2 - 2 \cdot 2 \cdot 5 \cos \theta$.
Simplifying this, we get $33 = 29 - 20 \cos \theta$, which means that $\displaystyle \cos \theta = -\frac{1}{5}$
Because $\cos^2 \theta + \sin^2 \theta = 1$, we get that $\displaystyle \sin^2 \theta = \frac{24}{25}$. This means that $\displaystyle \sin \theta = \frac{2\sqrt{6}}{5}$ (note that, because $0 \le \theta \le \pi$, $\sin \theta \ge 0$).
The area of the triangle is $\displaystyle \frac{1}{2} A B \sin \theta = \frac{1}{2} \cdot 2 \cdot 5 \cdot \frac{2\sqrt{6}}{5} = 2\sqrt{6}$.
Comment: Thank you, this is clear, concise, and could be done quickly and easily in the situation. This is probably what the judges/writers of it wanted readers to do.
Answer: Use the $\frac{1}{4}\sqrt{4a^2b^2-(a^2+b^2-c^2)^2}$ form of Herons' formula.
$$\begin{align}
  & \frac{1}{4}\sqrt{4\cdot4\cdot25-(4+25-33)^2} \\
= & \frac{1}{4}\sqrt{4^2\cdot25-4^2} \\
= & \sqrt{25-1} \\
= & 2\sqrt{6}
\end{align}$$
Comment: This is the way I would have done it, nice.
Answer: You could've used Heron's formula straight away, actually.
$$\begin{align}
T & = \tfrac{1}{4} \sqrt{(a+b-c)(a-b+c)(-a+b+c)(a+b+c)} \\
  & = \tfrac{1}{4} \sqrt{(2+5-\sqrt{33})(2-5+\sqrt{33})(-2+5+\sqrt{33})(2+5+\sqrt{33})} \\
  & = \tfrac{1}{4} \sqrt{(7-\sqrt{33})(-3+\sqrt{33})(3+\sqrt{33})(7+\sqrt{33})} \\
  & = \tfrac{1}{4} \sqrt{(7+\sqrt{33})(7-\sqrt{33})(\sqrt{33}+3)(\sqrt{33}-3)} \\
  & = \tfrac{1}{4} \sqrt{(49-33)(33-9)} \\
  & = \tfrac{1}{4} \sqrt{16 \cdot 24} \\
  & = \tfrac{1}{4} \sqrt{64 \cdot 6} \\
  & = \tfrac{8}{4} \sqrt{6} \\
  & = 2 \sqrt{6}
\end{align}$$
Answer: Since this was multiple-choice, I think it's worth noting that you could have guessed the right answer without doing (much) arithmetic: the diagonal of a right triangle with sides $2$ and $5$ has length $\sqrt{2^2+5^2} = \sqrt{29}$; since $\sqrt{33}$ is fairly close to this, the answer should be close to the area of a $2-5-\sqrt{29}$ triangle, which is of course $\frac12(2)(5)=5$.  If you imagine how to 'stretch out' the $\sqrt{29}$ diagonal to $\sqrt{33}$, it's clear that the right angle will have to become obtuse, and this in turn means that the area of the $2-5-\sqrt{33}$ triangle will have to be less than $5$; of the provided answers, only $2\sqrt{6}\approx4.472$ is less than $5$ (and of course very close to it).
Comment: @JohnJPershing For what it's worth, I think 2012ssohn's answer is much better than mine; it explains how to actually derive the correct value, rather than merely how to answer the multiple-choice question.  Both are valuable, but that one's likely to be more broadly applicable; I just wanted to offer an alternate approach for the test.
Comment: I like this response, and used a similar estimation method, using the areas of slightly bigger and smaller triangles that were easier to calculate
Comment: I hate it when there are two good answers, and both are right and good, and you wish you could accept both as correct
Answer: Let be $ABC$ the triangle. Consider the altitude $AH$ over the greatest side, the one whose length is $\sqrt{33}$. Now call $x=BH$, so $\sqrt{33}-x=CH$. Apply Pythagoras' theorem to get
$$\left\{
\begin{array}{rcl}
x^2+h^2&=&4\\
\left(\sqrt{33}-x\right)^2+h^2&=&25
\end{array}
\right.$$
Solve for $h$ and you are (almost) done.

Tricky Triangle Area Problem


Filter list by date and search through list

Question: I need to figure out how to order by date ascending and how I can add search to my list.
Here is example structure: https://jsfiddle.net/franso/jr7dsef3/

 <input type="text" v-model="search" placeholder="Search">
 <select v-model="title">
   <option value="Show all">Show all</option>
   <option value="Title 1">Title 1</option>
   <option value="Title 2">title 2</option>
 </select>
 <select v-model="name">
   <option value="Show all">Show all</option>
   <option value="Name 1">Name 1</option>
   <option value="Name 2">Name 2</option>
 </select>

{{ post.title }}

{{ post.name }}

{{ post.FinalApplicationDate }}

Comment: Have you had a look at the [mcve] guidance? Someone might be far more willing to take a stab at an answer if you presented your results and you picked either making the sort the problem to solve here or adding search. If you just need sort - remove all mention of search and focus on the mcve guidelines
Comment: Thank you @Ram i got the array sort() working.
Comment: Thank you for the guidance @bmike
Answer: You can use array.sort() for sorting date and use @change function on input tag for using search
Sort Javascript Object Array By Date


fade out load then fade in does not work

Question: so guys i have a list of bunch of stuff that a user can do it loads content of other pages into a div what happens is that the current content of the div flashes (fades out then in again) then the new content appear what i want to do is make the fadein animation wait until the content is ready to load then fade in the div here is the jquery code iam currently using
$(document).ready(function(){
    $("#History").click(function(){
        $('#Display').fadeOut("fast").load("History.php").fadeIn("fast");
    });
    $("#Items").click(function(){
        $('#Display').fadeOut("fast").load("SellerItems.php").fadeIn("fast");
    });
});

Answer: Use the callback function parameter that comes with both fadeOut() and load() methods. They will be called when the fade out is complete and the AJAX process is complete, respectively:
$("#History").click(function(){
    $('#Display').fadeOut("fast", function(){
        $(this).load("History.php", function(){
            $(this).fadeIn("fast");
        });
    });
});

Comment: It would be even more effective to load the content while the fadeOut is being performed using a promise.
Answer: Two things: 1, you need to hide the div before loading, and 2, fade in when it's ready.
I would animate the opacity here instead of using fadeIn for better control:
$("#History").click(function(){
    $('#Display').css('opacity', 0).load("History.php", function() {
        $(this).animate({ opacity: 1 }, 'fast');
    });
});

Comment: thanks a bunch dude this works perfectly the other ones flashes too if anyone is going to use this
Answer: The load method supports callbacks.
For example:
$('#Display').load("SellerItems.php", function() {
   $(this).fadeIn("fast");
});

Answer: jQuery's load function takes a callback that runs when the operation is complete, like:
$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

So what you should do is add the callbacks to your code:
$("#History").click(function () {
  $('#Display').load("History.php", function () {
    $(this).fadeIn("fast");
  });
});


iMask plugin for Angular: the unmask property doesn't allow typed

Question: I'm using the iMask plugin for Angular, and when I set the value of the unmask attribute to 'typed', I'm encountering an error that doesn't occur when I use 'true' or 'false' as the value.
This is the input:
 <input
  type="text"
  class="form-control"
  placeholder="Price"
  [(ngModel)]="book.price"
  id="book"
  name="book"
  #bookInput="ngModel"
  [imask]="currencyMask"
  [unmask]="'typed'"
  (ngModelChange)="onChange($event)"
/>

The Error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'toLocaleString')
TypeError: Cannot read properties of null (reading 'toLocaleString')
    at MaskedNumber.format (number.js:301:18)
    at MaskedNumber.typedValueEquals (base.js:377:127)
    at MaskedNumber.typedValueEquals (number.js:285:19)
    at set typedValue [as typedValue] (input.js:90:21)
    at set maskValue [as maskValue] (angular-imask.mjs:59:40)
    at IMaskDirective.writeValue (angular-imask.mjs:114:27)
    at setUpControl (forms.mjs:2938:23)
    at forms.mjs:3376:13
    at _ZoneDelegate.invoke (zone.js:368:26)
    at Object.onInvoke (core.mjs:26249:33)
    at resolvePromise (zone.js:1193:31)
    at zone.js:1264:17
    at _ZoneDelegate.invokeTask (zone.js:402:31)
    at core.mjs:25935:55
    at AsyncStackTaggingZoneSpec.onInvokeTask (core.mjs:25935:36)
    at _ZoneDelegate.invokeTask (zone.js:401:60)
    at Object.onInvokeTask (core.mjs:26236:33)
    at _ZoneDelegate.invokeTask (zone.js:401:60)
    at Zone.runTask (zone.js:173:47)
    at drainMicroTaskQueue (zone.js:581:35)

In the component I have the properties of currencyMask and book:
currencyMask={
  mask: Number,
  scale: 2,
  thousandsSeparator: ',',
  padFractionalZeros: true,
  normalizeZeros: true,
  radix: '.',
  mapToRadix: ['.'],
  min:0,
};
book: CreateBook = new CreateBook();

And CreateBook is:
class CreateBook {
    title:string="";
    price:number=0;
}

When the user inputs the price, i'm expecting to get the value of price as a number, not a string. If I use [unmask]="true" the value is being saved as a string. I'm using Angular 16.
I think this can be caused because price type is number and not Number but I already change the type and didn't works, I got the same error.
Answer: I had a similar case and it helped to define a custom format function
format: (x: string) => (x === "" ? null : x + "")


Completion of a flat morphism

Question: Let $\varphi: A \to B$ be a flat morphism of rings, $I$ an ideal in $A$ and $J= \varphi(I)B$. If $\hat{A}$ (resp. $\hat{B}$) denote the completion of $A$ (resp. $B$) with respect to $I$ (resp. $J$), is the induced morphism $\hat{A} \to \hat{B}$ flat?
I have a very simple motivation for this question: I actually want to know if $K[[t]]$ is flat over $R[[t]]$ when $R$ is a complete discrete valuation ring and $K$ is its fraction field. In this case, we would take $A=R[t]$, $B=K[t]$ and $I=(t)$.
Answer: If $B$ is a noetherian domain, by Krull intersection theorem it is Hausdorff for the adic topology definied by any ideal, and therefore if $B$ is flat over $A$, for any ideal $T$ of $A$ we have $T\otimes_AB \subset B$, and so $B$ is $I$-adically ideal-Hausdorff. Then by the local flatness theorem $\hat{A} \to \hat{B}$ flat. This answers only the particular case of $A=R[t]$, $B=K[t]$.
Comment: Thank you for your answer. What is the local flatness theorem exactly? Do you have any reference?
Comment: There are other cases where you can also apply the local flatness theorem and get an affirmative answer, for instance for noetherian local rings, but I do not know the answer to the question in its full generality.
Comment: You can find it in most standard books on basic commutative algebra (except Atiyah-Macdonald): Bourbaki's (not in the chapter on flatness, but in the one on filtrations), both Matsumura's, etc.

Completion of a flat morphism


What single day lineup featured the highest total for career HR?

Question: Watching the 1995 World Series between Cleveland and Atlanta.
I noticed Cleveland featured some bombers.  Here they are with their career HR:

LF Albert Belle - 381
DH Eddie Murray - 504
3B Jim Thome - 612
RF Manny Ramirez - 555

I searched for it but could not find definitively:
What single day lineup featured the highest total for career HR?
Comment: Haven't done the math, but the only one I can see off the top of my head might be '01 Cardinals... Mark McGwire and Pujols shared the lineup from time to time, having over 1200 HRs between them, plus Edmonds (393), Lankdford (238), for 1870 between the top 4 hitters; still almost 200 behind those four.  Bobby Bonilla did play for that team (287), so perhaps there is a game that all five played in?  Those Indians have Dave Winfield also, but I imagine he only DH'ed or PH'ed, so he wouldn't help.
Comment: Oh - JD Drew (242) also was on that team, and Bonilla did start a few times with the whole group above - never all six in a game I don't think, though, as there just wasn't room on the field for the six with only 3 OF and 2 CI spots.
Answer: STL in 2001 has a pretty powerful set of CI/OFs: Albert Pujols (656), Mark McGwire (583), Jim Edmonds (393), Bobby Bonilla (287), JD Drew (242), Ray Lankford (238).  Only problem is the six never start a game together, so the most you ever get is five - pretty sure every possible combination of 5 happens once, or at least most of them.  The five that exclude JD Drew happened fairly often until Lankford was traded; that's 2157 HRs from your top five bats!
The biggest HR day of that team was on 7/6 at CLE, where they conveniently had the designated hitter; that starting lineup hit a massive 2503 HR for their careers, and left out only JD Drew.  (Craig Paquette filled in as the sixth CI/OF/DH, adding his 99 career home runs to the 140 of Edgar Renteria, 40 of Fernando Vina, and 67 of eventual manager Mike Matheny, plus the 2157 above.
(If you're including anyone who makes an appearance in the game, then STL 2001 has some that all six of their big hitters appear in, plus Mabry or Polanco, which would add around 150 more to that total.)
However, this doesn't surpass 1995 CLE's normal starting lineup; that had 2669 HRs.
Even more astounding, you missed the player with the fourth highest home run total on that team.  Belle only came in fifth; Dave Winfield was an occasional DH on the team, with 465 career HRs.  On https://www.baseball-reference.com/boxes/CLE/CLE199505100.shtml for example, all five started; the team that day had 2,968 home runs by my calculations.  That total is repeated a few other times that season, but never exceeded.

All of that, though, doesn't beat the Bronx Bombers of 2005.   They had a killer lineup as well, led by Alex Rodriguez (696), Gary Sheffield (509), and Jason Giambi (440); but what sealed the deal was their middle infield, Derek Jeter and Robinson Cano, hitting for major power - 260 for Jeter and 324 for Cano.  Most teams (like the aforementioned Indians) got nearly all of their power from the outfield and the corner infield, but the Yankees didn't have a player to hit for less than 175 career HR - and that was Hideki Matsui, who certainly would've hit for more in the MLB if he'd spent more time over here.  In fact, you could easily add over 300 HR if you wanted to count all of his homers with the Yomiuri Giants
- but we won't for the purposes of this exercise.
On May 25, 2005, the starting lineup against the hapless Tigers hit for 3,305 career homers - none on that day, which is excusable since they probably were tired after going yard six times the day before.

One limitation of the python program I wrote to scrape this data is that it's quite hard to get information about pitchers, compared to hitters, due to some oddities of how Baseball Reference codes its (mostly easy to parse, except for this!) pages.  So I decided to discard pitchers' totals, assuming it's unlikely that they'd make a difference, but will inspect any NL teams' totals that get close to the top in case it does.

Some followup:  I finished running the program from 1969-present (something changed in the html formatting 1968->1969, and as I don't think there's any chance a pre-1969 team beats out the 'roid era I'm not going to chase it down right now), and think it's correctly handling pitchers now.  No NL team gets into the top 25, unsurprisingly.  The 2003 SF Giants are the highest NL team, just beating out 2001's STL and 2000's ATL with 2522 (ATL had 2514 and STL as noted above had 2503).
Counting only one appearance per year, here are the top 30:
<code> Game number, date, opp, result  HR#   Team Year
-------------------------------  ----  ---  ----
 46. Wed,5/25 vs DET W (4-2)#    3305  NYY  2005
   24. Wed,5/2 vs BAL L (0-5)    3223  NYY  2012
158. Wed,9/27 vs BAL W (16-5)    3202  NYY  2006
   5. Tue,4/5 vs MIN L (4-5)#    3178  NYY  2011
  105. Mon,8/2 vs TOR L (6-8)    3043  NYY  2010
37. Sun,5/11 vs CLE W (17-10)    2992  TEX  2003
  7. Sat,4/10 vs CHW L (3-7)#    2989  NYY  2004
 13. Wed,5/10 vs KCR W (3-2)#    2968  CLE  1995
 119. Tue,8/12 vs KCR W (9-0)    2876  CHW  2008
  22. Sat,4/28 vs BOS W (3-1)    2837  NYY  2007
    1. Tue,4/1 vs TOR W (3-2)    2837  NYY  2008
135. Fri,8/30 at SEA W (5-2)#    2821  BAL  1996
 45. Wed,5/23 at TBD L (6-10)    2805  TEX  2001
   56. Sun,6/7 vs TBR W (4-3)    2763  NYY  2009
 137. Mon,9/2 vs CHW W (9-1)#    2753  NYY  2013
   5. Fri,4/5 vs ANA L (1-3)#    2751  TEX  2002
  48. Tue,5/27 at CHW L (2-8)    2743  CLE  1997
  94. Thu,7/17 vs CLE W (5-4)    2720  NYY  2003
  19. Tue,4/21 at ANA W (8-3)    2702  BAL  1998
    1. Tue,4/2 vs NYY L (1-7)    2681  CLE  1996
   5. Mon,4/11 at CAL W (9-6)    2674  CLE  1994
 146. Thu,9/16 vs NYY L (5-9)    2611  CLE  1999
 109. Fri,8/6 vs NYY L (8-11)    2582  SEA  1999
  139. Thu,9/5 vs DET W (9-3)    2569  NYY  2002
 101. Sat,7/30 at CHW L (2-4)    2564  SEA  1994
  97. Sat,7/19 vs DET W (6-2)    2558  CHW  2003
  141. Sun,9/6 vs BAL L (2-5)    2550  SEA  1998
 38. Tue,5/19 vs NYY W (4-2)#    2540  OAK  1987
    1. Mon,4/3 at BAL W (4-1)    2533  CLE  2000
 110. Tue,8/13 at BAL L (7-8)    2527  TEX  1991
</code>
And just for fun, the bottom 20 - this is not the least home runs in a lineup, but rather the least most home runs in a calendar year (so this number here is the lineup with the most career HR, as of today, that team had in that year).
<code> Game number, date, opp, result  HR#   Team Year
-------------------------------  ----  ---  ----
   3. Mon,4/2 at TOR L (2-4)#     608  CHW  2018
   2. Sat,3/30 at KCR L (6-8)     605  CHW  2019
 63. Tue,6/13 at BOS L (3-4)#     604  PHI  2017
  86. Sun,7/16 at BOS L (2-3)     595  MIN  1978
 94. Sun,7/30 at HOU L (3-4)#     587  SDP  1972
  50. Wed,5/31 vs STL L (4-5)     576  NYM  1978
   82. Sun,7/3 vs NYM W (7-0)     569  SDP  1994
78. Wed,6/26 at HOU W (14-2)#     564  PIT  2019
  45. Wed,5/30 vs OAK L (4-5)     552  MIN  1979
 152. Tue,9/20 at MIL L (1-5)     545  SEA  1977
151. Fri,9/19 vs ATL L (3-12)     545  SDP  1969
  9. Wed,4/15 at ATL L (5-7)#     542  SDP  1970
 66. Wed,6/18 at KCR L (0-13)     537  CAL  1975
  88. Sat,7/12 vs CHW W (7-0)     530  KCR  1969
 144. Sat,9/7 vs TOR W (5-3)#     517  TBR  2019
 95. Sun,7/18 at CIN L (0-3)#     493  SDP  1971
  69. Thu,6/25 vs MIN W (4-1)     491  MIL  1970
 26. Sat,4/29 at SFG W (12-4)     479  SDP  2017
  19. Wed,4/29 at CIN L (5-8)     472  SDP  1981
</code>
Congratulations, San Diego Padres, you finally are the best at something!
And finally - here is the python file: https://github.com/snoopy369/Sports.SE/blob/master/hr_totals.py
Feel free to branch it and make it your own, maybe someone can fix the 1968-before pulls - I have no idea why those aren't working!
Comment: Career totals - as the OP provided.
Comment: Well, kicked it off with 1960-2019, wish me luck not getting IP banned from BBREF ;)  It's unlikely anyone 2010+ would have a high total, given most teams wouldn't have players that had completed their careers in that range, so I suspect that if anyone does beat that total it'll be someone from the Steroid Era, 90s or early 2000s, but I figured I'd include the 1960 Yankees and the Big Red Machine and such in case I'm being blind to something from back then (1960 yankees did have some big numbers, but not big enough I don't think...)
Comment: Are these the numbers at their maximum and back-seeking the highest combination, or the HRs scored as of the date of the game being described?
Comment: Excellent research. Thanks for putting in the work
Comment: Edited as I wrote a program to confirm this, and did so with 1995 CLE (confirmed 2968 as max).  I will see if I can run it on other years - not sure if BBREF will let me pull the number of pages needed to verify this for every team in every year, as that would be ... many.
Comment: Thanks for cycling it.  The cred is yours.
Comment: @JasonPSallinger Just FYI, this answer is definitely not right now that I've run the numbers partially; I found a bug in my program, so it's not totally done yet (I was giving Randy Johnson credit for 411 HR when it's really HRA...) but it's looking like the 2005 Yankees at least have even more homers.  Not sure how I missed that team in my recollection, guess I must have some implicit anti-Yankee bias that I don't know about...
Comment: As a side note for anyone else looking into the programming on this one -- bbref seems to have a bit of a challenging format to parse, because it hides many of its tables in comments.  Don't totally understand why.  But for example, the main table for players is fine - easy to access - but all of the other tables are hidden in a commented area to a parser, so for example I can't get to the batting stats of a pitcher (so if Ohtani were to make the difference here, we might be unable to see it in my program).  Annoying, and something to think about when working on this kind of thing!
Comment: @Joe  You've definitely earned it now.  Great content.


Why does this Twig code not perform math operations as expected?

Question: I have a registration form set up for athletes; I'm a volunteer coach.  The form contains 5 slots to register up to 5 children at a time.  There's also a donation field. Everything works fine unless the donation value goes over 999. I tried to use number_format in every way possible to grab the donation value and format it properly, but it still keeps adding a 1 when the number is higher than 1000.

This is the Twig code I am using.
{% apply spaceless %}
  {% set dv = (data.donation_value)|number_format(2)%}
  {% set cart_total = (data.child_registration_01_add)|number_format(0) + (data.child_registration_02_add)|number_format(0) + (data.child_registration_03_add)|number_format(0) + (data.child_registration_04_add)|number_format(0) + (data.child_registration_05_add)|number_format(0) %}

  {% set cart_1 = (data.child_registration_01_one)|number_format(2) + (dv)|number_format(2) %}

  {% set cart_2 = (data.child_registration_01_one)|number_format(2) + (data.child_registration_02_one)|number_format(2) + (dv)|number_format(2) %}

  {% set cart_3 = (data.child_registration_01_one)|number_format(2) + (data.child_registration_02_one)|number_format(2) + (data.child_registration_03_one)|number_format(2) + (dv)|number_format(2) %}

  {% set cart_4 = (data.child_registration_01_one)|number_format(2) + (data.child_registration_02_one)|number_format(2) + (data.child_registration_03_one)|number_format(2) + (data.child_registration_04_one)|number_format(2) + (dv)|number_format(2) %}

  {% set cart_5 = (data.child_registration_01_one)|number_format(2) + (data.child_registration_02_one)|number_format(2) + (data.child_registration_03_one)|number_format(2) + (data.child_registration_04_one)|number_format(2) + (data.child_registration_05_one)|number_format(2) + (dv)|number_format(2) %}

  {% if (cart_total)|number_format(0) == "1" %}
    {{ (cart_1)|number_format(2, '.', ',') }}
  {% elseif (cart_total)|number_format(0) == "2" %}
    {{ (cart_2)|number_format(2, '.', ',') }}
  {% elseif (cart_total)|number_format(0) == "3" %}
    {{ (cart_3)|number_format(2, '.', ',') }}
  {% elseif (cart_total)|number_format(0) == "4" %}
    {{ (cart_4)|number_format(2, '.', ',') }}
  {% elseif (cart_total)|number_format(0) == "5" %}
    {{ (cart_5)|number_format(2, '.', ',') }}
  {% else %}

 0.00

  {% endif %}
{% endapply %}

What am I doing wrong?
Comment: Welcome to Drupal Answers! It seems a rather complicate code to just sum all the values in the *Reg Fee* column and then add the value in the donation field. 1150 is the sum of the *Reg Fee* values; adding 1000 would give 2150. It seems that instead of adding 1000, the code is adding 1.
Comment: Did you try `number_format(2, '.', '')`?
Comment: @cilefen Yes, I've been trying to leverage number_format arguments. TWIG states that number_format defaults are (0, '.', ',').  So my last iteration I ended up removing the second and third arguements, using just the first.  No change.  Thanks
Comment: You did not really answer my question. Did you try precisely that?
Comment: Sorry @cilefen. Yes, I did go back and try precisely your recommendation.
Comment: It worked! @cilefen   I just had time to go back and test exactly your set of arguments everywhere and yes it worked!  **So happy** Thank you so so much!

Final question, how might I add this to the Drupal Webform documentation?
Answer: Use number_format(2, '.', '') to remove commas so you can perform math operations.


Proof of Bézout's identity - Cohn - CA p26

Question: Given two integers $a$ and $b$, there exist integers $u$ and $v$ such that $$au+bv=1$$ if and only if $a$ and $b$ are coprime.

Attempt Proof:
Assume $a$ and $b$ are not coprime, e.g. $a=kb,k\in \mathbb{Z}$.
$$bku+bv=1$$
$$b(ku+v)=1$$
$$ku+v=\frac1b$$
$ku+v$ is integer, so $\frac1b$ is integer, hence $b=\pm1$
$$ku+v=\pm1$$
Case $1$: $ku+v=1$, hence $ku$ and $v$ are consecutive integers in magnitude or something.
Case $2$: $ku+v=-1$...

I think this is the sort of direction I need to go, but I am unsure what to do here.
Comment: If $a$ and $b$ are not co-prime, it does not automatically follow that $a=kb$. Can you think of a less restrictive relationship between $a$ and $b$? For example, $6$ and $9$ are not co-prime.
Comment: @DilipSarwate $a=kb+l$?
Comment: @Committingtoachallenge: No. Not coprime means that $a$ and $b$ have a common divisor, that is, there is some $k\neq1$ such that $k|a$ and $k|b$.
Comment: @sranthrop $a=p_{a_1}p_{a_2}\dots p_{a_k}$,$b=p_{b_1}p_{b_2}\dots p_{b_k}$ where some of these prime factors are in both.
Comment: Thats equivalent, but more complicated maybe ;)
Comment: @sranthrop It seems like it might be :)
Answer: If $a>b\geqslant0$, then $a-b$ and $b$ are coprime. We get $(a-b)x+by=1$ for some $x$ and $y$ by induction, which implies $ax+b(y-x)=1$. The converse is trivial.
Answer: The existence is guaranteed by the Euclidian Algorithm (as far as you have learned it already). For the converse, if $au+bv=1$ is given and $k$ is a common divisor of $a$ and $b$, then the left hand side is divisable by $k$ (because there are $l,m$ such that $a=lk$ and $b=mk$, and this implies $1=au+bv=lku+mkv=k(lu+mv)$), so $k|1$. Thus, $k=1$ and therefore $a$ and $b$ are coprime.
Comment: This is really nice. Thank you. I love it.
Comment: Thanks, you are welcome :)


Form builder com array no angular

Question: Preciso criar um form que incrementa dinamicamente três campos ao clicar em um botão.
Procurei no site do angular mas lá só mostra como faz com um campo.
Tentei algo como:

          Nome Variação:
          <input [formControlName]="i" type="text" id="i" class="form-control">

          Valor:
          <input [formControlName]="i" type="text" id="i" class="form-control">

          SKU
          <input [formControlName]="i" type="text" id="i" class="form-control">

produtoForm = this.fb.group({
    variacoes: this.fb.array([
      this.fb.control(''),
    ])
  });
Minhas funções:
get variacoes() {
    return this.produtoForm.get('variacoes') as FormArray;
  }

  addVariacao() {
    this.variacoes.push(this.fb.control(''));
  }

A ideia seria que meu form tivesse um objeto chamado variacoes que dentro dele tem arrays com chave descricao, valor e sku.
@Atualização:
Não está adicionando novos campos como esperado, está atualizando os campos existentes:

        <button (click)="addVariacao()" type="button" class="btn btn-primary waves-effect">Adicionar variação</button>

      <form [formGroup]="categoriaForm">
        <ng-container *ngFor="let item of variacoes.controls; let i = index;">

            {{i}}    descricao
            <input type="text" class="form-control" formControlName="descricao">
              {{i}}    valor
            <input type="text" class="form-control" formControlName="valor">
            <input type="text" class="form-control" formControlName="sku">
            {{i}}    Sku

        </ng-container>
      </form>

  ngOnInit() {
    this.categoriaForm = this.fb.group({

    variacoes: this.fb.array([this.createFormGroup()])

    });

  get variacoes(): FormArray {
    return this.categoriaForm.get('variacoes') as FormArray;
  }

  addVariacao(){
    this.categoriaForm = this.fb.group({
      variacoes: this.fb.array([this.createFormGroup()])
    });;
  }

  createFormGroup() {
    return this.fb.group({
      descricao: [''],
      valor: [''],
      sku: ['']
    });
  }

Comment: https://pt.stackoverflow.com/questions/327124/enviar-formul%C3%A1rio-angular/327190#327190
Comment: fiz isso a esses dias atras
Comment: qualquer duvida só falar
Comment: retornou ERROR Error: formGroup expects a FormGroup instance. Please pass one in
Comment: public variacoes: any = [{descricao : "descricao1", valor: "valor1", sku: 'sku1' }]
  categoriaForm: FormGroup;
Comment: e no template:
Comment: Da uma olhada nesse meu stackblitz que eu fiz na resposta do willian
Comment: editei a pergunta com atualização, se puder dar uma olhada...
Comment: entao seguinte esse campo e dinamico? vem de uma db? se for da uma add no array variacoes.controls que ele vai fica dinamico com um push
Comment: tenho la em casa isso feito... se não conseguir te passo assim que chegar la
Comment: se nao me engano e isso aki https://stackoverflow.com/questions/43934396/angular-4-patchvalue-based-on-index-in-formarray , tem ate o remove
Comment: Tentei:   addVariacao(){
    this.categoriaForm.patchValue({
      variacoes: this.fb.array([this.createFormGroup()])
    });
  }

Não deu certo... value.foreach is not a function
Comment: tenta assim this.variacoes.at(index).patchValue({descricao:'teste', valor:1, sku:0}); index deria a posição do novo array da um this.variacoes?.lenght e coloca o valor no lugar do index ve se funciona
Answer:   public formulario;

public ngOnInit() {
    this.formulario = new FormGroup({
      data: new FormControl(),
      nome: new FormControl(),
      tipos: new FormBuilder().array([
        new FormGroup({
          id: new FormControl(),
          nome: new FormControl(),
        }),
      ])
    });
  }
  public adicionarForm() {
this.formulario.controls.tipos.controls.push(
  new FormGroup({
    id: new FormControl(),
    nome: new FormControl(),
  }),
);

}
Answer: Brother, sempre que você tenta adicionar mais uma variação você acaba substituindo todo o conteudo por apenas uma:
addVariacao() {
    this.categoriaForm = this.fb.group({
        variacoes: this.fb.array([this.createFormGroup()])
});

Basta apenas você adicionar mais um item no FormArray, como qualquer array, utilizando a função .push():
addVariacao() {
    this.variacoes.push(this.createFormGroup())
}

Aqui tem um exemplo do código funcionando, espero que eu tenha ajudado. xD
https://stackblitz.com/edit/simple-dynamic-form-builder-example?file=src/app/app.component.ts

Form builder com array no angular


Explicação sobre a função e aplicação da função sort do javascript

Question: Sei para que serve a função abaixo (retornar o candidato com maior números de votos), mas não entendo o funcionamento da função sort, passando um outra função.
Alguém sabe explicar e/ou onde encontrar material em português para esse forma de programação?

candidates = [
    {name: "Mr. Black", votes: 140},
    {name: "Mr. White", votes: 135},
    {name: "Mr. Pink", votes: 145},
    {name: "Mr. Brown", votes: 13}
];

var candidatesSorted = candidates.sort(function (a, b) {

    return b.votes - a.votes;
});
console.log(candidatesSorted[0]);
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: O sort() ordena os elementos de um array. Essa ordenação é de acordo com a tabela de código unicode.
Sintaxe arr.sort([funcaoComparar])
Se funcaoComparar não for informada, os elementos serão ordenados de acordo com a sua conversão para texto.
Exemplo: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort()
resultado [1, 10, 2, 3, 4, 5, 6, 7, 8, 9]

"10" veio antes do "2" porque "1", que é o primeiro caractere de "10", vem antes do "2"

No seu caso trata-se de ordenação por números

Quando o parâmetro funcaoComparar é informado, o array será ordenado de acordo com o seu valor de retorno.

Tipos de retorno:
se a comparação for menor que zero, a é posicionado antes de b
se a comparação for maior que zero, a é posicionado depois de b
se a comparação for igual a zero, a e b permanecem com as posições inalteradas

Exemplo

var arr = [5, 3, 1, 4, 2];

console.log('Array original:', arr);

arr.sort(function(a, b) {
    return a - b;
});

console.log('Array ordenado:', arr);

O que acontece é que o sort() pega o array original, compara dois valores e os muda de posição de acordo com essa comparação, logo em seguida ele pega novamente dois valores e os compara pra rearranjá-los de novo, e faz isso até que todo o array esteja ordenado.
Pegando o exemplo acima, onde usamos a - b, a ordenação acontece da seguinte forma: se o primeiro elemento comparado, no caso a, for maior que b, a subtração a - b resulta em um valor maior que zero, então a é posicionado depois de b (de acordo com as regras). Essa mesma lógica aplicada repetidamente no array, que está sendo modificado, faz que com que os valores maiores sejam posicionados mais ao fim do array, ou seja, faz a ordenação em ordem crescente!
var arr = [5, 3, 1, 4, 2];

compare(5,3); // retorna 2, 3 é posicionado na frente de 5
[3, 5, 1, 4, 2]

compare(3,1) // retorna 2, 1 é posicionado na frente de 3
[1, 3, 5, 4, 2]

compare(1,4) // retorna -3, nada muda

compare(1,2) // retorna -1, 3, nada muda

compare(3,5) retorna -2 e compare(3,4) retorna -1 nada muda

compare(3,2) // retorna 1, 2 na frente de 3
[1, 2, 3, 5, 4]

compare(5,4) // retorna 1, 4 na frente de 5
[1, 2, 3, 4, 5]

A mesma lógica se aplica para ordenação decrescente, b - a, só que agora com os valores trocados de lugar faz com que a ordenação seja ao contrário da anterior

Exemplo

var arr = [5, 3, 1, 4, 2];

console.log('Array original:', arr);

arr.sort(function(a, b) {
    return b - a;
});

console.log('Array ordenado:', arr);

mais sobre "Como o método sort() funciona"
Answer: Pensando em ordenação de maneira genérica, existem vários algoritmos diferentes (cada um com suas particularidades), mas uma coisa todos têm em comum: em algum momento, eles precisam comparar dois elementos e decidir qual será colocado antes e qual será colocado depois (afinal, "ordenar" é colocar os elementos em uma determinada ordem, seguindo alguma regra de ordenação).
É para isso que serve a função passada para o método sort. Ela recebe dois parâmetros (no caso, a e b), e decide se, no resultado final (no array ordenado), a estará antes ou depois de b. Isso é definido pelo retorno desta função:

se a deve estar antes de b, o retorno deve ser um número negativo (menor que zero)
se a deve estar depois de b, o retorno deve ser um número positivo (maior que zero)
se tanto faz a ordem entre eles, o retorno deve ser zero

Vendo a função que você usou:
function (a, b) {
    return b.votes - a.votes;
}

Supondo que a.votes seja 140 e b.votes seja 135, o retorno da função será -5 (um número negativo). Ou seja, neste caso, a estará antes de b no resultado final.
Se a.votes for 13 e b.votes for 140, o retorno da função será 127 (um número positivo). Então neste caso, a estará depois de b no resultado final.
E se os valores de a.votes e b.votes forem iguais, a função retorna zero, indicando que neste caso tanto faz a ordem entre eles.
De maneira geral, sempre que a.votes for maior que b.votes, o resultado será negativo e a estará antes de b (os elementos com os maiores valores de votes estarão antes dos elementos com valores menores).
Em outras palavras, o resultado final é um array com os candidatos em ordem decrescente de votos.

Esta função pode ter a lógica que você quiser, não se limitando a comparar um único campo.
Por exemplo, vamos supor que quero ordenar os candidatos pela ordem decrescente de votos, mas caso eles tenham o mesmo número de votos, o desempate é feito pela ordem alfabética do nome. A função ficaria assim:

// Mr. Black e Mr. Pink tem o mesmo número de votos
candidates = [
    {name: "Mr. Black", votes: 140},
    {name: "Mr. White", votes: 135},
    {name: "Mr. Pink", votes: 140},
    {name: "Mr. Brown", votes: 13}
];

var candidatesSorted = candidates.sort(function (a, b) {
    // primeiro verifica a ordem decrescente dos votos
    let result = b.votes - a.votes;

    // se os votos forem iguais, desempata pela ordem alfabética do nome
    if (result === 0) {
        result = a.name.localeCompare(b.name);
    }

    return result;
});

console.log(candidatesSorted[0]); // Mr. Black

Para comparar os nomes usei a função localeCompare, que segue a mesma lógica de retornar -1, 0 ou 1, usando a ordem alfabética como critério para definir o que vem antes e depois (para mais detalhes, ver aqui e aqui).

Um local que possui documentação em português é a MDN (Mozilla Developers Network). A documentação da função sort está aqui.
ps: muitas páginas não estão completamente traduzidas, mas no topo da página, ao lado direito, é possível mudar o idioma (e recomendo o inglês, já que não tem esses problemas de tradução).
Answer:
Array.prototype.sort()
...
Sintaxe:
arr.sort([funcaoDeComparacao])

...
Se o parametro funcaoDeComparacao é fornecido, o array será ordenado de acordo com o valor de retorno da funcaoDeComparacao. Considerando que a e b são dois elementos sendo comparados, então:

Se funcaoDeComparacao(a, b) for menos que 0, ordena a para um índice anterior a b, i.e. a vem primeiro.
Se funcaoDeComparacao(a, b) retornar 0, deixa a e b inalterados em relação um ao outro, mas ordenado em relação a todos os outros elementos. Nota: O padrão ECMAscript não garante este comportamento, e, portanto, nem todos os navegadores (e.g. Versões do Mozilla anteriores a 2003) respeitarão isto.
Se funcaoDeComparacao(a, b) é maior que 0, ordena b para um índice anterior que a.
  funcaoDeComparacao(a, b) sempre deve retornar o mesmo valor dado um par específico de elementos a e b como seus dois parametros. Se resultados inconsistentes são retornados, então a ordenação é indefinida.

...


How to use the API KEY in google shopping

Question: Im trying to execute a method of content API, so, when I test the follow URL:
<code>https://www.googleapis.com/content/v2.1/accounts/authinfo?key={YOUR_API_KEY}
</code>
The call of the service retrieves me:
<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}
</code>
But still show me the same error. Please any guide of this integration, I need call it from a C# console application, not by web site app with OAuth2.
Answer: You cant if you check the documentation for Accounts: authinfo
it clearly states that you must be authenticated with the following scope

You will need to add Oauth2 and login.  The fact that you are using a service account does not change the fact that you must have permission to access private user data.  Api keys can only be used to access public data.   If you are only accessing your own account then you may want to consider using a service account


specifying a class within this

Question: I have the following markup:

blah blah blah

footer info

mb_footer will be display:none'd on load and then I want a mouseover to cause it to show. I have:
$('.mb_post').on('mouseover',function(){
  $(this'.mb_footer').show();
});

but it's not working. How would I specify the mb_footer only existing within this?
thx in advance
Comment: And this doesn't give you any JavaScript errors?
Answer: Nearly had it...
$('.mb_footer', this).show();

The second argument of the $ function can be the context of the selector.
Alternatively, you can do $(this).find('.mb_footer').
Answer:

    blah blah blah

footer info

specifying a class within this


Is every coordinate-wise marginal of a proper joint distribution also proper?

Question: Suppose that we have a probability density function $\pi(x_1, \ldots, x_n)$ which is the density of a vector-valued random variable $X$ in $\mathbb{R}^n$. Here the density is proper, i.e., $\int_{\mathbb{R}^n} \pi(x_1, \ldots, x_n)  dx_1 \ldots dx_n = 1 < \infty$.
Without any additional restrictions on the joint density, does this imply that any coordinate-wise marginal density of the form
$$
\pi(x_i) = \int \pi(x_1, \ldots, x_n) dx_1 \ldots dx_{i-1} dx_{i+1} \ldots dx_n
$$
is also proper, i.e., that $\int_{\mathbb{R}} \pi(x_i) dx_i = 1 < \infty$ for any $1 \leq i \leq n$?
The motivation for this question is that I am considering a hierarchical Bayesian model involving an improper prior, and although I know that the posterior density over all model parameters is proper, I have seemingly found a marginal that is not proper (although this may be an error in my analytic computation). Intuitively, I would expect that any marginal of a proper joint should also be proper?
Answer: The marginal density of a probability density is again a probability density (a.s.).
The same notations should not be used for different entities, so let me define
$$\pi_i(x_i) = \int_{\mathbb R^{n-1}} \pi(x_1, \ldots, x_n) dx_1 \ldots dx_{i-1} dx_{i+1} \ldots dx_n$$
as the $i$-th marginal. Then
$$\int_{\mathbb{R}} \pi_i(x_i) dx_i = \int_{\mathbb{R}}\int_{\mathbb R^{n-1}} \pi(x_1, \ldots, x_n) dx_1 \ldots dx_{i-1} dx_{i+1} \ldots dx_n dx_i\\
=\int_{\mathbb R^{n}} \pi(x_1, \ldots, x_n) dx_1 \ldots dx_{i-1} dx_i dx_{i+1} \ldots dx_n = 1$$
by Fubini's Theorem.
This applies to the Bayesian setting in the question: if the joint posterior is proper, then any posterior marginal or conditional is equally proper (a.s.).
Comment: +1.  The "a.s." qualifier is essential, though!


Find the smallest positive integer $x$ satisfying $\gcd(x^n+a,(x+1)^n+a)>1$

Question: Given positive integers $n$ and $a$, I'd like to ask how to find the smallest positive integer $x$ satisfying $\gcd(x^n+a,(x+1)^n+a)>1$?
I try using the extended Euclidean algorithm on the two polynomials to find the greatest common divisor $\frac{p}{q}$. If $p$ is small, then we just need to check the solutions to $x^n+a \equiv 0 \ (mod \ d)$ where $d$ divides $p$. Otherwise, it seems much harder.
I also notice that $gcd(n,\phi(d))$ should be greater than $1$ in order to have a solution, which helps filter many unfavorable $d$.
Comment: Did you encounter an example that seems computationally difficult?
Comment: For example, $n=19$ and $a=2$. Both $p$ and $q$ are extremely large and cannot be factored easily. I believe the case is quite common for large $n$.
Comment: The procedure I've suggested below gives the resultant as $$1103 \cdot 87211 \cdot 31308253657 \cdot 818790224665362763936013994101920313,$$ and trying $p=1103, 87211, \ldots$ we find $x\bmod p=473, 836, \ldots$ with $473$ the solution.
Comment: Funny - for $n=19$ and $a=6$ the resultant appears to be prime, thus the smallest (!!!) solution is $$x=1578270389554680057141787800241971645032008710129107338825798$$
Answer: I don't quite understand what does $\gcd(y^n+a,(y+1)^n+a)$ give you if it is computed over $\mathbb{Z}[y]$ (if it is roughly what you do; otherwise, probably, we're talking about the same thing).
On the other hand, if $x$ is the solution, $d=\gcd(x^n+a,(x+1)^n+a)$, and $p$ is a prime divisor of $d$, then $x$ is a common root over $\mathbb{Z}/p\mathbb{Z}$ of these two polynomials, and this implies that $p$ divides their resultant, which (up to sign, depending on the definition taken) is equal to
$$\det\{r_{i,j} : 1\leqslant i,j\leqslant n\},\qquad r_{i,j}=\begin{cases}-a\binom{n}{j-i},& i < j\\ \hfill\binom{n}{i-j},& i\geqslant j\end{cases}$$
(resembling the "binomial circulant" a.k.a. Wendt's determinant).
Moreover, let $n=p^k m$ with $p\nmid m$. Then, over $\mathbb{Z}/p\mathbb{Z}$, we have
$$\gcd(y^n+a,(y+1)^n+a)=g^{p^k}(y),\quad g(y)=\gcd(y^m+a,(y+1)^m+a).$$
As we must clearly have $p\nmid a$, $x$ is a root of $g(y)$, and in fact a simple one (because $y^m+a$ has only simple roots).
This suggests the following idea. For each $p$ found, we solve $g(x)=0$ in $\mathbb{Z}/p\mathbb{Z}$ (I can only suggest general root-finding methods here, such as random splitting), and apply Hensel's lifting to get solutions in $\mathbb{Z}/p^k\mathbb{Z}$ (if needed). If $x$ exists at all, then its value modulo $p^k$ must stabilize eventually (for large enough $k$).


Which is a more serious problem in regression, regression dilution or bias?

Question: Which is a more serious problem in regression, regression dilution or bias?
Regression dilution usually causes underestimation, and bias (especially selection bias)usually causes overestimation. Which problem is more severe?
In practice, which case is more often, underestimation or overestimation?
Answer: In practice it doesn't make sense to ask for general patterns in whether dilution or "bias" [1] is more important. Some problems are subject to neither, some are subject to only one, and some are subject to both.
[1] What kind of bias? Regression dilution is a kind of bias, so how can we compare regression dilution and "bias" in general?
Comment: Do you agree that "Regression dilution usually causes underestimation, and bias (especially selection bias)usually causes overestimation. "?


Embed a View into a render array

Question: In Drupal 7, I used the following code implementing views_embed_view in a render array.
  $view_output = views_embed_view($view_name, $display_id, $uid);

  $page['profile']['bio_mobile'] = array(
    '#type' => 'markup',
    '#markup' => $view_output,
    '#prefix' => '
',
    '#suffix' => '
',
  );

How do I do that using Drupal 8?  Although the function is still documented, it return nothing more than just the array I passed in.
Answer: Indeed, #markup only allows string, but you can by using a block type
  $entityTypeManager = \Drupal::entityTypeManager();
  $viewExecutableFactory = \Drupal::service('view.executable');

  $view = $entityTypeManager->getStorage('view')->load($view_name);
  $view = $viewExecutableFactory->get($display_id);
  $view->setArguments([$uid]);
  $view->preExecute();
  $view->execute();

  $page['profile']['bio_mobile'] = [
    '#type' => 'block',
    'content' => [
      'system_main' => $view_output,
     ],
    '#cache' => $view->getCacheTags(),
    '#prefix' => '
',
    '#suffix' => '
',
  ];

Comment: Bingo!  I knew there had to be a way to digest the output from that function. I'm guessing there are existing #themes that would probably handle it as well.  I'm favoring the first answer because it gives more flexibility with the theme file that I would have had to build into the view before embedding it.
Thank you helping - I'll probably use that logic in another spot.
Answer: I don't know about using #markup but I can create a variable with a renderable View array like so:
  // Staff snippet.
  $view = Views::getView('staff');
  $view->setDisplay('user_snippet');
  $view->preExecute();
  $view->execute();

  if (count($view->result)) {
    $variables['user_snippet'] = $view->buildRenderable('user_snippet');
  }

Then in the twig file I am sending the variable to:
{% if user_snippet %}
  {{ user_snippet }}
{% endif %}

Comment: I actually think this is better. If you check the old function it just calls this code anyway. This was done in a preprocess hook for a node. It calls 'buildRenderable' to fetch a renderable array of that View. It's added to the $variables array, which is what is sent to Twig.
Comment: The `$variables` is just an array of items for a template. It can be any value and it can also be a renderable array. The `buildRenderable` method returns a renderable array for that View. The information on how to render it is inside the array, which means it works the same way as rendering content in a node like `{{ content.FIELD_NAME }}`. Any preprocess hook for Views to change how its theming or what its theming should still work. Drupal 7 worked the same way.
Comment: Thank you for the feedback.  Seems so complicated compared to the good old days of Drupal 6 and 7. However, that may be the best (only) way...

So, how do you "send the variable" to a twig file?
Comment: I'm marking this as the solution. Though the answer from noSsseat also works. It *seems* that there is more control here with the use of the template... The only thing that really bothers me is that I can not figure out *how* it is working.  We are passing the Twig Template an array... how does it "know" what to do with it?  I can pass a simple string to it (like "hello world") and it works... magic powers???   Thank you for the help!

Embed a View into a render array


Uploading to S3 from browser using signed upload URL fails

Question: I'm trying to upload a file to S3 directly from browser. For this, I'm generating a signed upload URL on my server.
When I try to upload a file to the generated url from the browser using
var xhr = new XMLHttpRequest();
xhr.open('PUT', signedUrl);
xhr.send(file);

I get the following error
<Error>

    SignatureDoesNotMatch

  <Message>
    The request signature we calculated does not match the signature you provided. Check your key and signing method.
  </Message>
  ...
</Error>

I can upload to the signed URL using curl with the following command
curl -T <file> -X PUT '<signed-url>'

The browser is sending my request as multipart-form data which is causing the problem. How do I fix the issue?
I'm generating the signed URL using the following code
var params = {
    Bucket: bucket,
    Key: s3Key,
    ACL: "authenticated-read",
    Expires: 600
};

S3.getSignedUrl('putObject', params, (err, data) => {
    const returnData = {
        url: data
    };
    reply(returnData);
});

Edit:
Just to be clear, I have allowed all origins to send PUT requests in bucket CORS configuration.
Answer: Okay, the problem was that Content-Type was being sent by the browser in the request header but the signed url wasn't being generated for the content type.
Instead of this
var params = {
    Bucket: bucket,
    Key: s3Key,
    ACL: "authenticated-read",
    Expires: 600
};
S3.getSignedUrl('putObject', params, ...);

I did this
var params = {
    Bucket: bucket,
    Key: s3Key,
    ACL: "authenticated-read",
    Expires: 600,
    ContentType: require('mime').lookup(filename)
};
S3.getSignedUrl('putObject', params, ...);

and it worked!