VBA cannot get data from HTML with .getElementsByTag() nor .getElementByID()

Question: My current project consists of retrieving data from HTML source code.
Specifically, I am looking at crash cases on this website:
https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?xsl=main.xsl&CaseID=112007272
I would like to gather all relevant data from the HTML by looking for .innertext of specific tags/IDs.
My code so far:
Sub ExtractData()

mystart:

'First I create two Internet Explorer object

Set objIE = CreateObject("InternetExplorer.Application")      'this browser contains the list of cases
objIE.Top = 0
objIE.Left = 0
objIE.Width = 1600
objIE.Height = 900
objIE.Visible = True 'We can see IE

Set objIEdata = CreateObject("InternetExplorer.Application")    'this browser opens the specific case
objIEdata.Top = 0
objIEdata.Left = 0
objIEdata.Width = 1600
objIEdata.Height = 900
objIEdata.Visible = True 'We can see IE

On Error Resume Next
objIE.navigate ("https://crashviewer.nhtsa.dot.gov/LegacyCDS/Index")        'url of website

Do
    DoEvents
    If Err.Number <> 0 Then
        objIE.Quit
        Set objIE = Nothing
        GoTo mystart:
    End If
Loop Until objIE.readystate = 4

'we define an object variable Alllinks and loop through all the links to search for

Set aAlllinks = objIE.document.getElementsByTagName("button")                'looks for Search Button
For Each Hyperlink In aAlllinks
    If Hyperlink.innertext = " Search" Then
        Hyperlink.Click
        Exit For
    Else
        MsgBox "Search Button was not found. Please improve code!"
    End If

Next

Application.Wait (Now + TimeValue("0:00:02"))

Set bAlllinks = objIE.document.getElementsByTagName("a")                     'all Hyperlinks on webpage start with Tag "a"
For Each Hyperlink In bAlllinks
    If UBound(Split(Hyperlink.innertext, "-")) = 2 And Len(Hyperlink.innertext) = 11 Then             'case specific to find the Hyperlinks which contain cases
        Debug.Print Hyperlink.innertext

        '2nd IE is used for each case

restart:
            objIEdata.navigate (Hyperlink.href)        'url of each case

            Do
                DoEvents
                If Err.Number <> 0 Then
                    objIEdata.Quit
                    Set objIE = Nothing
                    GoTo restart:
                End If
            Loop Until objIEdata.readystate = 4

            Set register = objIEdata.document.getElementByTagName("tbody")             'objIEdata.document.getElementByID("main").getElementByID("mainSection")  '.getElementByID("bodyMain").getElementsByTagName("tbody")
            For Each untermenue In register
                Debug.Print untermenue.innerHTML
            Next

            Application.Wait (Now + TimeValue("0:00:02"))

    End If
Next

objIE.Quit
objIEdata.Quit

End Sub

Note that the visibility of IE is just for debugging reasons.
The part which confuses me is
Set register = objIEdata.document.getElementByTagName("tbody").
If I look for .TagName("tbody") the variable register is returned empty and the same happens if I look for .ID("bodyMain"). Unfortunately, I am not familiar with HTML and how VBA interacts with a HTML document. I was under the impression that I could address all elements by their ID, if they happen to have one, but this does not seem to work.
Do I need to work myself through the HTML "branches" or should the code be able to find each ID, no matter the "child" it is to be found in?
Thanks a lot
Comment: What exactly are you after? Everything on the page?
Comment: Pretty much, yes. I do not need hyperlinks to XML and stuff, but basically I need all the information in the tables. In the end I would like to have a CSV or filled excel sheet, which shows all the data for each case with the property that same categories are in the same column. I also do not need the pictures.
Answer: What you are asking is a pretty big request so I am going to give some pointers and starting code. My code should write out all the tables but you will want to play around to get your desired format. There is certainly enough logic around selecting elements efficiently that this should help. * I haven't tested the use of the class to loop over all retrieved ids due time contraints but have tested the individual case and the retrieval of all ids.

To get the initial case links and ids:
I might use a function returning an array containing the links and ids. If you extract the ids they can be passed the XMLHTTP request I show below.
URL is https://crashviewer.nhtsa.dot.gov/LegacyCDS/Search
Public Function GetLinksAndIds(ByVal URL) As Variant
    Dim ie As InternetExplorer, i As Long
    Set ie = New InternetExplorer
    With ie
        .Visible = True
        .navigate2 URL

        While .Busy Or .readyState < 4: DoEvents: Wend

        .document.getElementById("btnSubmit1").Click

         While .Busy Or .readyState < 4: DoEvents: Wend

        Dim caseLinks As Object, id As String, newURL As String
        Set caseLinks = .document.querySelectorAll("[href*='CaseID=']")

        Dim linksAndIds()
        ReDim linksAndIds(1 To caseLinks.Length, 1 To 2)
        For i = 0 To caseLinks.Length - 1
           linksAndIds(i + 1, 1) = caseLinks.item(i)
           linksAndIds(i + 1, 2) = Replace$(caseLinks.item(i), "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?xsl=main.xsl&CaseID=", vbNullString)
        Next

        .Quit
    End With
    GetLinksAndIds = linksAndIds
End Function

Example return values:

For each case - using XMLHTTP:
I would be tempted to avoid IE and use XMLHTTP request (url encoded query string returning more readable page version using the print option). Although I have parsed using css selectors you can read the response into an MSXML2.DOMDocument60 and query with XPath for example. You can concatenate caseid into URL.
Option Explicit
Public Sub GetTables()
    Dim sResponse As String, html As HTMLDocument, clipboard As Object, ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?ViewPage&xsl=Case.xsl&tab=Crash&form=CaseForm&baseNode=&vehnum=-1&occnum=-1&pos=-1&pos2=-1&websrc=true&title=Crash%20Overview%20-%20Summary&caseid=112007272&year=&fullimage=false", False '<==concatenate caseid into URL
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = .responseText
    End With

    Set html = New HTMLDocument
    html.body.innerHTML = sResponse
    Dim tables As Object, i As Long
    Set tables = html.querySelectorAll("table")
    For i = 0 To tables.Length - 1
        clipboard.SetText tables.item(i).outerHTML
        clipboard.PutInClipboard
        ws.Cells(LastRow(ws) + 2, 1).PasteSpecial
    Next
End Sub

'https://www.rondebruin.nl/win/s9/win005.htm '<< Function below modified from here

Public Function LastRow(ByVal sh As Worksheet) As Long
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

What might it look like altogether (not tested) using a class to hold the xmlhttp object:
Class clsHTTP:
Option Explicit

Private http As Object

Private Sub Class_Initialize()
    Set http = CreateObject("MSXML2.XMLHTTP")
End Sub

Public Function GetString(ByVal URL As String) As String
    Dim sResponse As String
    With http
        .Open "GET", URL, False
        .send
        sResponse = .responseText
    End With
End Function

Standard module 1:
Option Explicit
Public Sub GetTables()
    Dim sResponse As String, html As HTMLDocument, clipboard As Object, ws As Worksheet
    Dim initialLinksURL As String, http As clsHTTP, i As Long, j As Long, newURL As String
    Set http = New clsHTTP
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    Set html = New HTMLDocument
    initialLinksURL = "https://crashviewer.nhtsa.dot.gov/LegacyCDS/Search"

    Dim linksAndIds()
    linksAndIds = GetLinksAndIds(initialLinksURL)

    For i = LBound(linksAndIds, 2) To UBound(linksAndIds, 2)

        newURL = "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?ViewPage&xsl=Case.xsl&tab=Crash&form=CaseForm&baseNode=&vehnum=-1&occnum=-1&pos=-1&pos2=-1&websrc=true&title=Crash%20Overview%20-%20Summary&caseid=" & linksAndIds(i, 2) & "&year=&fullimage=false"
        html.body.innerHTML = http.GetString(newURL)
        Dim tables As Object

        Set tables = html.querySelectorAll("table")

        For j = 0 To tables.Length - 1
            clipboard.SetText tables.item(j).outerHTML
            clipboard.PutInClipboard
            ws.Cells(LastRow(ws) + 2, 1).PasteSpecial
        Next
    Next
End Sub

'https://www.rondebruin.nl/win/s9/win005.htm

Public Function LastRow(ByVal sh As Worksheet) As Long
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Public Function GetLinksAndIds(ByVal URL) As Variant
    Dim ie As InternetExplorer, i As Long
    Set ie = New InternetExplorer
    With ie
        .Visible = True
        .navigate URL

        While .Busy Or .readyState < 4: DoEvents: Wend

        .document.getElementById("btnSubmit1").Click

         While .Busy Or .readyState < 4: DoEvents: Wend

        Dim caseLinks As Object, id As String, newURL As String
        Set caseLinks = .document.querySelectorAll("[href*='CaseID=']")

        Dim linksAndIds()
        ReDim linksAndIds(1 To caseLinks.Length, 1 To 2)
        For i = 0 To caseLinks.Length - 1
           linksAndIds(i + 1, 1) = caseLinks.item(i)
           linksAndIds(i + 1, 2) = Replace$(caseLinks.item(i), "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?xsl=main.xsl&CaseID=", vbNullString)
        Next

        .Quit
    End With
    GetLinksAndIds = linksAndIds
End Function

All Internet Explorer option:
Option Explicit

Public Sub GetTables()
    Dim sResponse As String, html As HTMLDocument, clipboard As Object, ws As Worksheet
    Dim initialLinksURL As String, i As Long, j As Long, newURL As String
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    Set html = New HTMLDocument
    initialLinksURL = "https://crashviewer.nhtsa.dot.gov/LegacyCDS/Search"

    Dim ie As InternetExplorer, caseLinks As Object
    Set ie = New InternetExplorer
    With ie
        .Visible = True
        .Navigate2 initialLinksURL

        While .Busy Or .readyState < 4: DoEvents: Wend

        .document.getElementById("btnSubmit1").Click

        While .Busy Or .readyState < 4: DoEvents: Wend

        Set caseLinks = .document.querySelectorAll("[href*='CaseID=']")

        Dim linksAndIds()
        ReDim linksAndIds(1 To caseLinks.Length, 1 To 2)
        For i = 0 To caseLinks.Length - 1
            linksAndIds(i + 1, 1) = caseLinks.item(i)
            linksAndIds(i + 1, 2) = Replace$(caseLinks.item(i), "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?xsl=main.xsl&CaseID=", vbNullString)
        Next

        For i = LBound(linksAndIds, 2) To 2      ' UBound(linksAndIds, 2)

            newURL = "https://crashviewer.nhtsa.dot.gov/nass-cds/CaseForm.aspx?ViewPage&xsl=Case.xsl&tab=Crash&form=CaseForm&baseNode=&vehnum=-1&occnum=-1&pos=-1&pos2=-1&websrc=true&title=Crash%20Overview%20-%20Summary&caseid=" & linksAndIds(i, 2) & "&year=&fullimage=false"
            .Navigate2 newURL

            While .Busy Or .readyState < 4: DoEvents: Wend

            Dim tables As Object

            Set tables = .document.querySelectorAll("table")

            For j = 0 To tables.Length - 1
                clipboard.SetText tables.item(j).outerHTML
                clipboard.PutInClipboard
                ws.Cells(LastRow(ws) + 2, 1).PasteSpecial
            Next
        Next

        .Quit
    End With
End Sub

'https://www.rondebruin.nl/win/s9/win005.htm

Public Function LastRow(ByVal sh As Worksheet) As Long
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Comment: Thank you. This seems to be a more elegant way to solve my problem. Unfortunately, I cannot get past the .send within the CreateObject("MSXML2.XMLHTTP") without an error.
Comment: What is the error message please? I have just tested for first two links and it works. Just annoying as tables are listed one under the other all the way through. That is where using xpath may be more useful to determine a more consistent layout going across the page but would require more thought than I can give at present.
Comment: The error code is a runtime error  '-2146697211 (800c0005)'.

https://stackoverflow.com/questions/11726661/error-from-vb-excel-macro-code-msxml3-dll-2146697211-the-system-cannot-locate

It did not help to change "Get" to "Post". Btw. I am using XML, v6.0.

Thank you very much for your effort!
Comment: There may even be someone who is going with transforming xml that could write something nice you could call as a sub in the loop to help with extraction in a format lending itself to writing across the page.
Comment: Yes, it stops as soon as I get there the first time. I had the same problem with the  trial code on the website of your first link https://codingislove.com/http-requests-excel-vba/ .
Comment: Then I get runtime error '-2147012889 (80072ee7)'
After the ".Open "GET", URL, False" my http object still has "unknown error" for most of its variables including responseText.
Comment: Did you say you also tried the coding is love example and same problem? I am wondering if there is some kind of security setting applied.
Comment: Yes, this one:

Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String

myurl = "http://requestb.in/15oxrjh1" //replace with your URL
3
xmlhttp.Open "GET", myurl, False

xmlhttp.Send

MsgBox(xmlhttp.responseText)

Security probably is applied since I am using this at work which also prevents me from doing it with any other programming language or tool.
Comment: Will you have a chance to test on another machine? Otherwise, as I said, you can easily re-work the above to use Internet Explorer only if that can navigate to the pages. I may quickly draft something for you now.
Comment: I will check it as soon as I get home from work and if it works it probably has something to do with the security settings here. What exactly happens when you call the .send function as it might be relevant for security settings?

Please do not invest too much time in my problems. You already did me a great favor and I am always impressed by how people like you actually seem to understand programming and do not just use it the way I do like a patch work.
Comment: .Send does as it says... it attempts to rely your GET request to the target API service.
Comment: I am pretty sure that you have given me enough advice that I can figure out a way to achieve my goal. It might not be the nicest way, but it is a good start to get a result. Thanks again!
Comment: No worries. Let me know if any further queries.


Hypothesis test for odds ratios

Question: I have two possible exposure variables (A and B) for use in a statistical model predicting a binary health outcome.  I have fitted models with each variable separately and now know that one variable is a better predictor of my outcome based on a comparison of R-squared and BIC values. However, the ORs for the two variables are quite similar with overlapping confidence intervals.  The sample composition and size is the same for each model.
I would like to comment on whether the odds ratios are significantly different from one another. How can I do this?
Best Regards.
Answer: It looks like you are trying to compare two odds ratios. Try looking at
Statistical test for difference between two odds ratios?
Comment: In this case the 2 ORs are not independent, I'd say.
Comment: Hi - yes I did see the earlier post, but as a novice I need something with bit more explanation!
Comment: As pointed out above, can you assume independence?
Comment: I'm not sure. How would I evaluate that? Exposure A and Exposure B are correlated to some extent, but rho is about 0.5.

Hypothesis test for odds ratios


Analytical expression of sum of Sines

Question: Express E and F in terms of A,B,C,D
$Asin(B+x) + Csin(D+x) = Esin(F+x)$
Can you also find a general formula for more number of terms on the left-hand side?
$A_{1}sin(B_{1}+x)+A_{2}sin(B_{2}+x)+...+A_{n}sin(B_{n}+x)=Esin(F+x)  $
Comment: What have you tried?
Comment: I actually didn't think of expanding the left-hand side until Bernard Pan said it below
Answer: Here are the hints to the first one.
For the LHS, we have $$A\sin(B+x)=A(\sin B\cos x+\cos B\sin x), $$similarly, $$C\sin(D+x)=C(\sin D\cos x+\cos D\sin x). $$Thus, $$A\sin(B+x)+C\sin(D+x)=\sin x(A\cos B+C\cos D)+\cos x(A\sin B+C\sin D). $$
Recall that $$m\sin x+n\cos x=\sqrt{m^2+n^2}\sin(x+\varphi),\quad\varphi=\arctan\frac{n}{m}.$$
Then I think it is easy to get the expressions for both $E$ and $F$. As for the generalized form, you can just take a similar approach and it is actually no more difficult than the first one.
Comment: nice one, expanding left-hand side terms and then factorising, I'll write up the general solution in a few minutes, thanks
Comment: There's a small problem here though, I'm on Desmos trying the formula for just two terms and the arctan is sometimes off by a shift of Pi
Comment: Figured that carrying over the sign of sine to the right-hand side fixes the problem actually, so I added an extra term B/abs(B)
Answer: $A_{1}sin(B_{1}+x)+A_{2}sin(B_{2}+x)+...+A_{n}sin(B_{n}+x)=Esin(F+x)$
$A_{1}sin(B_{1})cos(x)+A_{1}cos(B_{1})sin(x)+...$ so factorising $sin(x)$ and $cos(x)$  will give the coefficients:
$A_{s}=A_{1}sin(B_{1})+A_{2}sin(B_{2})+...+A_{n}sin(B_{n})$
$B_{s}=A_{1}cos(B_{1})+A_{2}cos(B_{2})+...+A_{n}cos(B_{n})$ where the LHS = $A_{s}cos(x)+B_{s}sin(x)$
since $Acos(x)+Bsin(x) = \frac{B}{|B|}\sqrt{{A}^2+{B}^2}*sin(arctan(\frac{A}{B})+x)$ then:
$Esin(F+x)=\frac{B_{s}}{|B_{s}|}\sqrt{{A_{s}}^2+{B_{s}}^2}*sin(arctan(\frac{A_{s}}{B_{s}})+x)$
so $E=\frac{B_{s}}{|B_{s}|}\sqrt{{A_{s}}^2+{B_{s}}^2}$ and $F=arctan(\frac{A_{s}}{B_{s}})$

Analytical expression of sum of Sines


How to predict float vector labels with caffe?

Question: I was wondering if it's possible to predict a 1-by-n feature associated to an input image using caffe.
In this post there is a solution to make caffe predict a binary vector such as [1 0 1 0].
Is this solution also suitable if I have a 1-by-n float vector as label (such as [0.2, 0.1, 0.3, 0.4] ? I want to predict such a vector, not a binary vector label.
Answer: You can also think about this MultiTaskData Layer. It can parse float typed label vector as you mentioned in your question.
Answer: Yes; I believe that if you simply follow the instructions in the post you referenced, but use float labels in place of the binary ones, that you'll get useful results.  Caffe is happy to support you.  :-)


Computing a limit involving Gammaharmonic series

Question: It's a well-known fact that
$$\lim_{n\to\infty} (H_n-\log(n))=\gamma.$$
If I use that $\displaystyle \Gamma \left( \displaystyle \frac{1}{ n}\right) \approx n$  when $n$ is large, then I wonder if it's possible to compute the following limit in a closed-form
$$\lim_{n\to \infty}\left(\frac{1}{ \Gamma\left(\displaystyle \frac{1}{1}\right)}+ \frac{1}{ \Gamma\left( \displaystyle \frac{1}{2}\right)}+ \cdots + \frac{ 1}{ \Gamma \left( \displaystyle \frac{1}{ n}\right) }- \log\left( \Gamma\left(\displaystyle\frac{1}{n}\right)\right)\right),$$
where I called $\displaystyle \sum_{k=1}^{\infty}\frac{ 1}{ \Gamma \left( \displaystyle \frac{1}{ k}\right) }$ as Gammaharmonic series.
I can get approximations, but I cannot get the precise limit, and I don't even know if it can be expressed in terms of known constants.
A 500 points bounty moment: I would enjoy pretty much finding a solution (containing a closed-form) for the posed limit, hence the generous bounty. It's unanswered for 3 years and 8 months, and it definitely deserves another chance. Good luck!
Comment: This is a very interesting question, indeed ! Numerically, it seems that there is a limit but how to express it, that is the question !
Comment: [Wrench (1968)](http://www.ams.org/journals/mcom/1968-22-103/S0025-5718-1968-0237078-4/S0025-5718-1968-0237078-4.pdf) has a paper concerning the series $\sum\frac{1}{\Gamma(k)}$. Some answers are already showing some promise to computing that series.
Comment: Are you sure that your question can be answered during 7 days although it's unanswered for 3 years and 8 months ? I think the answers of *Leucippus* and *Jack D'Aurizio* are well done! :-)
Comment: @user90369 no problem then. In general, one user will remain with *my legacy*, that is the bounty, and I'm sure they (those receiving such bounties) will want to continue to work on my question, maybe for months, years (if the case, of course), until they finally get the solution (at least out of curiosity). :-)
Answer: From Wolfram Gamma Function equations (35)-(37) provide
\begin{align}\tag{1}
\frac{1}{\Gamma(x)} = x + \gamma x^{2} + \sum_{k=3}^{\infty} a_{k} x^{k}
\end{align}
where, $a_{1}=1$, $a_{2}=\gamma$,
\begin{align}\tag{2}
a_{n} = n a_{1} a_{n-1} - a_{2} a_{n-2} + \sum_{k=2}^{n} (-1)^{k} \zeta(k) \, a_{n-k}.
\end{align}
Now,
\begin{align}\tag{3}
\sum_{r=1}^{n} \frac{1}{\Gamma\left(\frac{1}{r}\right)} \approx H_{n} + \gamma H_{n,2} + \sum_{k=3}^{\infty} a_{k} H_{n,k},
\end{align}
where $H_{n,r}$ are the generalized Harmonic numbers given by
\begin{align}\tag{4}
H_{n,r} = \sum_{s=1}^{n} \frac{1}{s^{r}}.
\end{align}
Since the limit is for large values of $n$, $n \rightarrow \infty$, then utilize the approximation, Wolfram Harmonic Number Approximations,
\begin{align}\tag{5}
H_{n,r} \approx \frac{(-1)^{r} \psi^{(r-1)}(1)}{(r-1)!} - \frac{1}{(r-1) \, n^{r-1} } \left( 1 + \mathcal{O}\left(\frac{1}{n}\right) \right)
\end{align}
to obtain
\begin{align}\tag{6}
\sum_{r=1}^{n} \frac{1}{\Gamma\left(\frac{1}{r}\right)} \approx H_{n} - \frac{\gamma}{n} + \sum_{k=2}^{\infty} \frac{(-1)^{k} a_{k}}{(k-1)!} \, \psi^{(k-1)}(1) + \mathcal{O}\left(\frac{1}{n^{2}} \right).
\end{align}
Since,
\begin{align}\tag{7}
- \ln \Gamma\left( \frac{1}{n} \right) \approx \frac{\gamma}{n} - \ln(n) + \mathcal{O}\left(\frac{1}{n^{2}}\right)
\end{align}
then
\begin{align}\tag{8}
\sum_{r=1}^{n} \frac{1}{\Gamma\left(\frac{1}{r}\right)} - \ln \Gamma\left( \frac{1}{n} \right) \approx  H_{n} - \ln(n) + \sum_{k=2}^{\infty} \frac{(-1)^{k} a_{k}}{(k-1)!} \, \psi^{(k-1)}(1) + \mathcal{O}\left(\frac{1}{n^{2}} \right).
\end{align}
Taking the limit as $n \rightarrow \infty$ and using
\begin{align}
\lim_{n \rightarrow \infty} \left( H_{n} - \ln(n) \right) = \gamma
\end{align}
then
\begin{align}\tag{9}
\lim_{n \rightarrow \infty} \left[ \sum_{r=1}^{n} \frac{1}{\Gamma\left(\frac{1}{r}\right)} - \ln \Gamma\left( \frac{1}{n} \right) \right] = \sum_{k=1}^{\infty} \frac{(-1)^{k} a_{k}}{(k-1)!} \, \psi^{(k-1)}(1).
\end{align}
Since
\begin{align}\tag{10}
\psi^{(m)}(x) = (-1)^{m+1} m! \zeta(m+1, x)
\end{align}
then
\begin{align}\tag{11}
\lim_{n \rightarrow \infty} \left[ \sum_{r=1}^{n} \frac{1}{\Gamma\left(\frac{1}{r}\right)} - \ln \Gamma\left( \frac{1}{n} \right) \right] = \gamma + \sum_{k=2}^{\infty} a_{k} \zeta(k).
\end{align}
Comment: So $a_k$ is the generating function of $\frac1{\Gamma(x)}$?
Comment: @Alizter $a_{k}$ are the coefficients in the "generating function" for $(\Gamma(x))^{-1}$.
Comment: (+1) for the efforts so far
Answer: From the Weierstrass product for the Gamma function we have, as $x\to+\infty$:
$$\frac{1}{\Gamma(1/x)}=\frac{1}{x}+\frac{\gamma}{x^2}+O\left(\frac{1}{x^3}\right)\tag{1}$$
and:
$$\log\Gamma(1/x)=\log x -\frac{\gamma}{x}+O\left(\frac{1}{x^2}\right)\tag{2}$$
gives that the value of the limit is:
$$\gamma+\sum_{n=1}^{+\infty}\left(\frac{1}{\Gamma(1/n)}-\frac{1}{n}\right)=0.8188638872713\ldots\tag{3}$$
Comment: (+1) for the efforts so far
Answer: $(1)\enspace$ A simplification of what Leucippus had written, for a better understanding:
$\displaystyle \lim_{n\to\infty} \left(\sum\limits_{k=1}^n \frac{1}{\Gamma(1/k)} - \ln\Gamma\left(\frac{1}{n}\right)\right) =\lim_{n\to\infty} \left(\sum\limits_{k=1}^n \frac{1}{\Gamma(1/k)} - \ln n \right) =$
$\displaystyle =\gamma + \sum\limits_{k=1}^\infty \left(\frac{1}{\Gamma(1/k)} - \frac{1}{k}\right) = \gamma + \sum\limits_{n=2}^\infty a_n \zeta(n)\enspace$ for $\displaystyle\enspace \frac{1}{\Gamma(z)}-z =: \sum\limits_{n=2}^\infty a_n z^n$
$(2)\enspace$ Let $\,\displaystyle \tau:=-\int_0^1\left\lfloor \frac{1}{t} \right\rfloor\left(1+\frac{\psi(t)}{\Gamma(t)}\right) dt \,$
with the Digamma function $\,\displaystyle\psi(x)=\frac{\Gamma'(x)}{\Gamma(x)}\,$ and Gauss's floor function $\,\lfloor x \rfloor\,$.
Then we get with $\,\Gamma(1/n)\thicksim n\,$ :
$$\lim_{n\to\infty} \left(\sum\limits_{k=1}^n \frac{1}{\Gamma(1/k)} - \ln\Gamma\left(\frac{1}{n}\right)\right)=\lim_{n\to\infty} \left(\sum\limits_{k=1}^n \frac{1}{k} - \ln\Gamma\left(\frac{1}{n}\right)\right) +\sum\limits_{k=1}^\infty \left(\frac{1}{\Gamma(1/k)} - \frac{1}{k}\right)$$
$$=\gamma+\tau \hspace{2.1cm}$$
Answer: One can show that
Lemma 1.
If $f(x)$ is analytic in $(-a,a)$, $a\geq 1$, then
$$
\sum^{M}_{n=1}f\left(\frac{1}{n}\right)=\int^{M}_{1}f\left(\frac{1}{t}\right)dt+c(f)+O\left(\frac{1}{M}\right)\textrm{, }M\rightarrow +\infty,\tag 1
$$
where $c_f$ is a constant depended from $f$ and not from $M$:
$$
c_f=f(0)+f'(0)\gamma+\sum^{\infty}_{k=2}\frac{f^{(k)}(0)}{k!}\left(\zeta(k)-\frac{1}{k-1}\right).
$$
Proof.
Expand $f$ in (1) into Taylor series, then sum and integrate. The ''infinite'' terms involving $M$ are canceled and the result will follow.
Remark. The next two known estimates are usefull in the proof of Lemma 1:
$$
\sum^{M}_{k=1}\frac{1}{k}=\log(M)+\gamma+O\left(\frac{1}{M}\right)\textrm{, }M\rightarrow \infty
$$
and
$$
\zeta_n(s)-\zeta(s)=O\left(\frac{1}{n^{s-1}}\right)\textrm{, }s>1\textrm{, }n\rightarrow\infty.
$$
Lemma 2.
If $f(x)=xg(x)$, $g(0)=1$ and $g$ analytic in $(-a,a)$, $a\geq 1$, then
$$
\int^{M}_{1}f\left(\frac{1}{t}\right)dt+\log\left(f\left(\frac{1}{M}\right)\right)=c'_f+o(1)\textrm{, }M\rightarrow +\infty,
$$
where
$$
c'_f=\sum^{\infty}_{k=1}\frac{f^{(k+1)}(0)}{k(k+1)(k)!}
$$
Proof.
We can write
$$
\int^{M}_{1}f\left(\frac{1}{t}\right)dt=\int^{1}_{1/M}\frac{f(t)}{t^2}dt=\int^{1}_{h}\frac{g(t)}{t}dt=
$$
$$
=-g(0)\log(h)+\sum^{\infty}_{k=1}\frac{g^{(k)}(0)}{k(k)!}(1-h^k).
$$
Hence
$$
\lim_{M\rightarrow \infty}\left[\int^{M}_{1}f\left(\frac{1}{t}\right)dt+\log\left(f\left(\frac{1}{M}\right)\right)\right]
=
$$
$$
=\lim_{h\rightarrow 0}\left[\int^{1}_{h}\frac{g(t)}{t}dt+\log\left(hg(h)\right)\right]=
$$
$$
=\lim_{h\rightarrow 0}\left[-g(0)\log(h)+\log(hg(h))\right]+\sum^{\infty}_{k=1}\frac{g^{(k)}(0)}{k(k)!}=\sum^{\infty}_{k=1}\frac{f^{(k+1)}(0)}{k(k+1)(k)!}
$$
QED
From the two Lemma's we have
Theorem.
If $f(x)=xg(x)$, $g(0)=1$ and $g$ analytic in $(-a,a)$, $a\geq 1$, then
$$
\sum^{M}_{k=1}f\left(\frac{1}{k}\right)+\log\left(f\left(\frac{1}{M}\right)\right)=c''_f+o(1),
$$
with constant term
$$
c''_f=f'(0)\gamma+\sum^{\infty}_{k=2}\frac{f^{(k)}(0)}{k!}\zeta(k)
$$
Note: The estimate $o(1)$ can easily replaced with $O\left(\frac{1}{M}\right)$.
Hence as one can see the problem can be generalized. In your case we have:
The function $f(z)=\frac{1}{\Gamma(z)}$ is entire and have Taylor expansion in (-1,1). Set
$$
g(x)=\frac{f(x)}{x}=\frac{1}{\Gamma(x+1)}.
$$
Then $f(0)=0$, $g(0)=1$, $f'(0)=1$ and hence holds
$$
\sum^{M}_{n=1}\frac{1}{\Gamma\left(\frac{1}{n}\right)}+\log\left(\frac{1}{\Gamma\left(\frac{1}{M}\right)}\right)=\gamma+\sum^{\infty}_{k=2}a_k\zeta(k),
$$
or equivalent
$$
\sum^{M}_{n=1}\frac{1}{\Gamma\left(\frac{1}{n}\right)}-\log\left(\Gamma\left(\frac{1}{M}\right)\right)=\gamma+\sum^{\infty}_{k=2}a_k\zeta(k)+O\left(\frac{1}{M}\right)\textrm{, }M\rightarrow\infty,
$$
where
$$
a_k=\frac{1}{k!}\left(\frac{d^k}{dx^k}\frac{1}{\Gamma(x)}\right)_{x=0}\textrm{, }k=2,3,\ldots
$$


Thailand MO $f(x)f(y)f(x-y) = x^2f(y) - y^2f(x)$

Question: This is a functional equation question from Thailand MO 2023.

Let $f: \mathbb{R} \rightarrow \mathbb{R}$ that satisfies the equation
$$f(x)f(y)f(x-y) = x^2f(y) - y^2f(x)$$
for all $x,y \in \mathbb R$. Find all $f$.

$\textbf{My attempt: }$ By letting $x=y=0$, we have that $f(0)^3 =0 \implies f(0)=0$.
Setting $y=x\neq 0$, we have that $0 = x^2f(x)$, so $f(x) = 0$ is a solution. By inspection, I also notice that $f(x) = x$ and $f(x) = -x$ are solutions. I've also tried manipulating two expressions
\begin{alignat}{2}
f(x)f(y_1)f(x-y_1) &= x^2f(y_1) - {y_1}^2f(x)\\
f(x)f(y_2)f(x-y_2) &= x^2f(y_2) - {y_2}^2f(x)\\
\implies f(y_1)\left[f(x - y_1) - f(x -y_2)\right] &= {y_2}^2-{y_1}^2
\end{alignat}
This doesn't seem helpful and I'm not sure where to go from here. I suspect these are the only solutions? Help would be greatly appreciated!
Answer: Suppose $P(x,y): f(x)f(y)f(x-y) = x^2f(y)-y^2f(x)$
As you noted, $f(0)=0$. From $P(y,x)$ and $P(x,y)$, one gets $f(x)f(y)\cdot(f(x-y)+f(y-x))=0$
Case $1$: $f(x)=0$
Case $2$: $f(x)\neq 0$.
$f(x-y)=-f(y-x)$. Taking $t \to x-y$ shows $f$ is odd, since $f(t)=-f(-t)$. Then, $P(x,-x)$ shows $f(2x)\cdot f(x) =2x^2$ and $P(2x,x)$ shows $2\cdot f(x)=f(2x)$. This gives $f^2(x)=x^2$ and that $f(x)=x$ or $f(x)=-x$. This can mean that the functions be entirely $x$, or $-x$, or perhaps be a function which is $x$ for some interval and $-x$ for some other.
But the third possibility leads to contradictions. Take $a,b \neq 0$. By way of contradiction, suppose $f(a)=a$ while $f(b)=-b$. $f(a-b)$ may be $a-b$ or $b-a$. In either case, we get from $P(a,b)$ that either $a=0$ or $b=0$, which contradicts our initial supposition. This shows the one $f$ can't be $x$ and $-x$ for different $x$. So we get two solutions $f(x)=x\ \ \forall x$ or $f(x)=-x \ \ \forall x$, where $f(x)\neq 0 \implies x\neq 0$.
Similarly, we can show that $f(x)$ can't be some function which is $0$ on some interval and non-zero (ie $\pm x$) on some other. Take $a,b\neq 0$ such that $f(a)=0$ and $f(b)=\pm b$. Then $P(a,b): a^2(\pm b) =0$ but this contradicts that $a,b$ are non-zero.
Hence, $f(x)=0 \ \forall x\lor f(x)=x\ \ \forall x \lor f(x)=-x \ \forall x$ are the solutions. Note that we can claim this for the case $2$ solutions since $f(0)$ is already known to be $0$.

NOTE: I have elaborated this post to present a better idea of the solution.
Answer: Swapping $x$ and $y$, for any $x$ and $y$ we have:
$f(y)f(x)f(y-x)=y^2f(x)-x^2f(y)=-f(x)f(y)f(x-y) \Rightarrow f(x)=0~or~f(y-x)=-f(x-y) $.
Assuming a nontrivial solution, this means that $f(x)$ is an odd function. Now set $y=-x$:
$f(x)f(-x)f\left(x-(-x)\right)=x^2f(-x)-(-x)^2f(x)\Rightarrow f^2(x)f(2x)=2x^2f(x) \Rightarrow f(x)f(2x)=2x^2$ (I).
Now, consider $x\rightarrow 2x$ and $y\rightarrow x$ in the equation. We will have
$f(2x)f(x)f(2x-x)=(2x)^2f(x)-x^2f(2x)\Rightarrow f(2x)f^2(x)=x^2\left( 4f(x)-f(2x)\right)$ (II).
From (I) we have $f(2x)=\frac{2x^2}{f(x)} \Rightarrow f(2x)f^2(x)=2x^2f(x)$. (III)
(II) & (III): $2x^2f(x) = x^2\left( 4f(x)-f(2x)\right) \Rightarrow f(2x)=2f(x)$. Plug this into equation (I): $2f^2(x)=2x^2$.
Therefore, $f(x)=\pm x$. The only thing left to show is that $f(x)$ cannot be equal to $x$ for some x and equal to $-x$ for the rest. We can prove this by contradiction. Assume $f(x) =x$ and $f(y) = -y$. Then, we have
$x(-y)f(x-y)=x^2(-y)-y^2x \Rightarrow f(x-y)=x+y$. Note that f(x-y) must be equal to either $x-y$ or $y-x$.
Case 1: $f(x-y)=x-y=x+y \Rightarrow y=0$.
Case 2: $f(x-y)=y-x=x+y \Rightarrow x=0$.
This completes the proof.
Answer: Suppose that $f(x) = 0$ for some $x \neq 0$. Then, substituting in any value of $y$ shows that $0 = x^2f(y)$, so $f(y)=0$ for all $y \in \mathbb R$. Meanwhile, letting $y=x=0$ gives $f(0)^3=0$, so $f(0)=0$.
From now on, we assume that $f(x) \neq 0$ for all $x\neq 0$. Knowing this, let's define the function $$g(x) =\begin{cases}
0 &  x=0
\\ \frac{x^2}{f(x)} & x \neq 0
\end{cases}.$$
Note that for $x,y \neq 0$, dividing both sides of the functional equation by $f(x)f(y)$, $$
f(x-y) = \frac{x^2}{f(x)} - \frac{y^2}{f(y)} = g(x)-g(y).
$$
Now we can play a game similar to that played for the Cauchy functional equation. Note that for any $x \neq 0$, $$
f(2x) = g(3x) - g(x) = (g(3x) - g(2x)) + (g(2x) - g(x)) = 2f(x).
$$
Then, note that for any $x \neq 0$, $$
g(2x) = \frac{4x^2}{f(2x)} = \frac{2x^2}{f(x)} = 2g(x).
$$
But then, $f(x) = g(2x) - g(x) = g(x)$ for all $x \neq 0$. Thus, by definition of $g$, we see that $f(x) = \pm x$ for all $x \neq 0$.
Also, this implies that $f(x-y) = g(x)-g(y) = f(x)-f(y)$ for all $x,y \neq 0$. This is in the realm of Cauchy's functional equation and similar arguments to those used in that analysis yield that

$f$ is additive i.e. $f(rx) = rf(x)$ for all positive rational numbers $r$ and $x \neq 0$.

$f$ is continuous at $0$, since $|f(x)| \leq |x|$ for all $x \neq 0$.

Under these conditions, $f$ is uniquely either $+x$ or $-x$, as is well known in that theory. Finally, both these solutions work, and we obtain the complete set of solutions as $f(x) = 0$ and $f(x) = \pm x$ for all $x \neq 0$ and a fixed choice of sign.
Answer: Leaving the discontinuous case,The function might be of Two types,Either continuous Differentiable or continuous non-Differentiable
Now either the Function is Constant function  or It is a non-constant function
For Function to be constant,substitute $f(x)=k$ in original functional equation
$k^3=k^3-k^3$
Hence $k=0$,Which means $f(x)=0$ is the only function when it is a constant Differentiable function
Now Let $f(x)$ be non-constant Differentiable function
The given functional equation is as follows
$$f(x)f(y)f(x-y) = x^2f(y) - y^2f(x)\tag1$$
Now replace $y\to x-y$ in given functional equation
$$f(x)f(x-y)f(y) = x^2f(x-y) - (x-y)^2f(x)=x^2f(x-y) - x^2f(x)+2xyf(x)-y^2f(x)\tag2$$
Hence
$$f(x)f(x-y)f(y)=x^2f(x-y) - x^2f(x)+2xyf(x)-y^2f(x)\tag3$$
From $(1)$ and $(3)$
$$x^2f(y)=x^2f(x-y)-x^2f(x)+2xyf(x)\tag4$$
Consider  $x,y \in (\mathbb R-{{0}})$
From equation $4$, It follows
$$\frac{f(y)}{y}=-\left(\frac{f(x-y)-f(x)}{y}\right)+\frac{2}{x}f(x)\tag 5$$
Let $\lim \limits_{y \to 0}\frac{f(y)}{y}=t $
Apply limit $y\to 0$ on both sides of equation $5$
$$\lim \limits_{y \to 0}\frac{f(y)}{y}=-\lim \limits_{y \to 0}\left(\frac{f(x-y)-f(x)}{y}\right)+\frac{2}{x}f(x)\tag 6$$
It follows
$$t=-f'(x)+\frac{2}{x}f(x)\tag 7$$
It is A Linear first order differential equation
Solving it yields
$$f(x)=tx+cx^2\tag 8$$
Where $c$ is constant of integration
Note that Using original functional equation and replacing $x \to 2x$ and $y \to x$
We get $f(2x)=2f(x)$
Using this condition on our solved function,We get $c=0$
Hence $$f(x)=tx$$
Now taking $y\to1$ and $x\to x$in original functional equation and using $f(x)=tx$ We get an essential condition that $t^3=t$, hence $t=1$ or $t=-1$
Hence $f(x)=0$ or $f(x)=x$ or $f(x)=-x$ are the solutions to given functional equation
Note:This is unintentionally big solution as I started Typing it on mobile before it got any other answers,Hence Thought of completing and posting it anyways


Intuition for continuity in $\Bbb R^n$

Question: I'm trying to conceptually understand continuity in $\Bbb R^n$. I understand the one-dimensional case where for a function $f: \Bbb R \to \Bbb R$, arbitrarily small deviations of the input ($\delta$) will produce arbitrarily small deviations in the output ($\epsilon$). However, this picture is muddied when I start to consider functions of multiple variables. For example, what does a continuous function $g: \Bbb R^2 \to \Bbb R^2$ look like? Is it just piecewise continuous? For example, if I have a function $g(x,y) = (x+y, 2xy)$, would I just need to consider that an arbitrarily small change in $x$ and $y$, and show that each of these individually would produce an arbitrarily small change in the output?
More generally, is there a way that I can intuitively think about it? The picture for $\Bbb R$ is clear, but I think it is less clear for higher dimensions. Also, how should I picture any general function $f:\Bbb R^2 \to \Bbb R^2$?
Comment: You need to consider small changes in every direction, not just along the $x$ and $y$-axes.
Comment: Mappings $f:\mathbb{R}^2\rightarrow\mathbb{R}^2$ can still be visualised: to every point $(x,y)$ of the plane a vector, namely $f(x,y)$, is "glued". $f$ is therefore also called "vector field".
Comment: "Every direction" means along *all* paths that lead to the point, not just along straight lines.
Comment: Well, you can't picture dimensions above 3. As for 3, look for surfaces.
Answer: It is instructive to reformulate the definition for continuity for functions $\mathbb{R} \rightarrow \mathbb{R}$. To this end, we first define some notation. Let $x \in \mathbb{R}^{n}$ be a real number and let $\epsilon \in \mathbb{R}_{>0}$ be a positive real number. Then we write
\begin{equation*}
B(x,\epsilon) = \{ y \in \mathbb{R}^{n}: \|x-y\| < \epsilon \}
\end{equation*}
for the open ball around $x$ with radius $\epsilon$.
In terms of open balls, the definition for continuity reads as follows.
Let $f: \mathbb{R} \rightarrow \mathbb{R}$. Then $f$ is continuous in $x$ if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $y \in B(x, \delta)$ it follows that $f(y) \in B(f(x), \epsilon)$.
In $\mathbb{R}$, the condition $y \in B(x, \delta)$ means precisely that $|x-y|< \delta$ and the condition $f(y) \in B(f(x), \epsilon)$ means precisely that $|f(x) - f(y)| < \epsilon$.
The definition in terms of open balls generalizes readily to functions $f: \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}$.
The idea is as follows. If $f: \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}$ is continuous, then it should not make any sudden jumps, that is, points $x, y \in \mathbb{R}^{n}$ that are close to each other, should get sent to points $f(x),f(y)\in \mathbb{R}^{m}$ that are close to each other.
We formalize this idea by saying that the ball $B(x,\delta)$ around $x$, should get sent to a set of points contained in the ball $B(f(x), \epsilon)$.
Answer: The essential point is that we can measures distances in ${\mathbb R}^n$ as well as in ${\mathbb R}$:
$$\|x-y\|:=\sqrt{(x_1-y_1)^2+(x_2-y_2)^2+\ldots+(x_n-y_n)^2}\ .$$
Continuity is explained in terms of such distances.
Consider a function $f:\>{\mathbb R}^n\to{\mathbb R}^m$ and assume $f(p)=q$. Then $f$ is continuous at $p$, if given any tolerance $\epsilon>0$ for the output error  we can exhibit an allowance $\delta>0$ such that $\|x-p\|<\delta$ guarantees $\|f(x)-q\|<\epsilon$.
If, e.g., we know beforehand that $\|f(x)-f(y)\|\leq L\|x-y\|$ for any two points $x$ and $y$ in the domain of $f$ then we can just take $\delta={\epsilon\over L}$.

Intuition for continuity in $\Bbb R^n$


What is the duration of each note in a triple which contains more than three notes or less than three notes?

Question: I am watching this video:

It says there are some triplets with more than three values or less than three values.
For instance:

In the video, it demonstrates how I calculate the total rhythmic value of that kind of triplets, but when I'm about to play the triplet, what exactly is the duration of each note? Should I just split them by the count of notes? Or should I follow some other rules?
Answer: I have always, as you say, "split them by the count of notes." It's a multi-step process of:

Ignore the triplet aspect of the rhythm and focus only on the note values themselves.
The total duration of these note values will be equal to three of some other note value.
This other note value is the basis of your triplet. The triplet will last the duration of two of these basis note values.

Let's take your first unequal example of an eighth, two sixteenths, and an eighth. Our first step is to ignore the triplet aspect of this rhythm and focus on the eighth, two sixteenths, and the eighth. The total duration of these notes will be equal to three of some note value. The eighth, two sixteenths, and eighth are equivalent to 1.5 quarter notes, or three eighth notes. The eighth note is thus the main indicator for this triplet.
A triplet consists of three note values that take place in the span of two. So this first triplet, because it's written in the duration of three eighth notes, will actually last the duration of only two eighth notes (i.e., a quarter note).
From there, it's just a question of subdividing. Practice your "regular" eighth-note triplet, then try subdividing each of the eighth notes into sixteenths. Finally, remove the extraneous sixteenths and perform the eighth, two sixteenths, eighth triplet as written.
I know how cumbersome this answer is, so let's try your second example, too. The triplet has a half followed by a quarter. Let's ignore the triplet aspect and only focus on those values: a half and a quarter. Then, we know that the total value of that half and quarter is equal to three of some single note value. The half and quarter are three quarter notes in length, so the quarter note is our main rhythmic basis.
A triplet is three note values in the place of two, so this quarter-note triplet will last the duration of two quarter notes (i.e., a half note). I recommend practicing this triplet as if it were three articulated quarter notes, and then slowly removing the articulation on the second quarter note.
One more example may be helpful: a triplet of a quarter, dotted quarter, and eighth. Determine the answer yourself, then click the spoiler text to reveal the answer.

 The quarter, dotted quarter, and eighth are equivalent to three quarter notes. This triplet will thus last the span of two quarter notes, or a half note.
Answer: Whatever values of notes, regardless of tempo, they're all relative to each other. As in - a crotchet is always twice the length of a quaver, a minim always twice the length of a crotchet, and so on, in the same piece, at the same tempo.
So the same concept will occur within tuplets, whatever they're made up of. Your example of a minim and a crotchet within a triplet mark: the minim will always be twice as long as the crotchet, just that the both notes together will have the same timing as one minim. It's as simple as that. That's if the music keeps absolute, strict time. Which some music does, some doesn't. But as a start point, keep it mathematically straightforward, as I indicate, and you won't go far wrong.
Quaver= 1/8, crotchet= 1/4 and minim =1/2 notes, for those unfamiliar with the terminology! And that probably helps - 1/2 is twice as big as 1/4, etc...


custom WP REST API not showing for non-logged in users

Question: I have his custom post type
function wp_post_types() {
    // Nicknames post type
    register_post_type('subscription', array(
    'supports' => array('title'),
    'public' => true,
    'show_ui' => true,
    'labels' => array(
      'name' => 'Subscription',
      'add_new_item' => 'Add New Subscription',
      'edit_item' => 'Edit Subscriptions',
      'all_items' => 'All Subscriptions',
      'singular_name' => 'Subscription'
    ),
    'menu_icon' => 'dashicons-universal-access-alt'
  ));
}
add_action('init', 'wp_post_types');

and here is my code in function.php to register the custom REST API
    add_action('rest_api_init', 'searchSubscription');
    function searchSubscription() {
        register_rest_route('CustomAPI/v3', 'search', array(
            'methods' => WP_REST_SERVER::READABLE,
            'callback' => 'getSubscription'
        ));
    }

    function getSubscription() {
        $subscriptions = new WP_Query(array(
            'perm' => 'readable',
            'post_type' => 'subscription',
            'posts_per_page' => '5'
        ));

        $subscriptionResults = array();

        while($subscriptions->have_posts()) {
            $subscriptions->the_post();
            array_push($subscriptionResults, array(
                'title' => get_the_title(),
                'region' => get_field('regi'),
                'country' => get_field('country'),
                'activity' => get_field('activity'),
                'time' => get_field('time')
            ));
        }
        return $subscriptionResults;
    }

Problem: It does not display any results for non-logged users. error:
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}

It works for admin user. I can see the json data from: http://localhost/wp-json/CustomAPI/v1/subscription/
[{"title":"Matt","region":"Central Visayas","country":"PH","activity":"2 months premium membership","time":"2018-01-31 06:36:53"},{"title":"Johnmark","region":"Central Visayas","country":"PH","activity":"Life time membership","time":"2018-01-31 06:29:52"}]

Any ideas what's wrong with my code why its not showing for non-logged in users?
Comment: My first thought, would be to set the post type, to public true
Comment: @Stender I did, register_post_type is now using     'public' => true , still not showing for non-logged users
Answer: Add the 'show_in_rest' parameter to your register_post_type() function.
function wp_post_types() {
    // Nicknames post type
    register_post_type('subscription', array(
    'supports' => array('title'),
    'public' => true,
    'show_ui' => true,
    'show_in_rest' => true,
    'labels' => array(
      'name' => 'Subscription',
      'add_new_item' => 'Add New Subscription',
      'edit_item' => 'Edit Subscriptions',
      'all_items' => 'All Subscriptions',
      'singular_name' => 'Subscription'
    ),
    'menu_icon' => 'dashicons-universal-access-alt'
  ));
}
add_action('init', 'wp_post_types');

https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/
Answer: Try removing the 'perm' parameter.
Answer: Try this code
add_action('rest_api_init', 'searchSubscription');
function searchSubscription() {
    register_rest_route('CustomAPI/v1', 'subscription', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'getSubscription'
    ));
}

function getSubscription() {
    $subscriptions = new WP_Query(array(
        'perm' => 'readable',
        'post_type' => 'subscription',
        'posts_per_page' => '5'
    ));

    $subscriptionResults = array();

    while($subscriptions->have_posts()) {
        $subscriptions->the_post();
        array_push($subscriptionResults, array(
            'title' => get_the_title(),
            'region' => get_field('regi'),
            'country' => get_field('country'),
            'activity' => get_field('activity'),
            'time' => get_field('time')
        ));
    }
    return $subscriptionResults;
}

Comment: I changed from 'CustomAPI/v1', '/search/' TO  'CustomAPI/v1', '/search/'  but still no results for non-logged users. the admin can view the json data


How to show that $pm/pn=m/n$ and that $pm \bmod pn = p(m \bmod n)$?

Question: I'm sure I'm overly thinking this but I'm stuck and I need help just starting the following problem:
Show that for any natural number $m$, any positive natural number $n$ & any positive natural number $p$, it is the case that $pm/pn=m/n$ and that $pm \bmod pn = p(m \bmod n)$?
Comment: Does $m/n$ designate a rational number, or does it denote the integer quotient (dropping the remainder)?
Answer: Supposing you are talking about Euclidean division. Then $m/n=q$ and $m\bmod n=r$ mean exactly that $m=qn+r$ and $0\leq r<n$. Multiplying by $p$ one deduces that $pm=qpn+pr$ and $0\leq pr<pn$, which can be read as $pm/pn=q$ and $pn\bmod pn=pr$, which is what you wanted to prove.
Comment: Ok that's what I pretty much did but thought it was missing steps or too short! Thank you for clarifying!


Como implementar IClonable em um tipo no C#?

Question: Quando queremos que um objeto seja facilmente copiado podemos implementar a interface IClonable e o método Clone(). Esta cópia pode ser feita com profundidade ou não, já que a documentação diz que não tem uma forma certa.
Então como saber qual é a forma certa? Quais critérios devem ser adotados para decidir como implementar corretamente para cada tipo?
Answer: A interface IClonable acabou sendo uma má ideia e deve ser evitada. Justamente porque não se sabe como será feito, e para algo universal deveria ter uma forma específica. O que torna inviável porque nem todos os objetos podem ser feitos da mesma forma. Em alguns casos a cópia profunda pode ser problemática, e a cópia rasa pode dar resultados indesejáveis, para dizer o mínimo. Quem vai chamar o Clone() precisa saber como foi implementada.
Considere essa interface obsoleta e não a use.
O que fazer então?
Crie um método Copy() para evitar confusão e estabeleça um critério e o chame sabendo desse critério. Como ele não faz parte de algo usado universalmente não tem problema, só vai chamar onde sabe qual é o critério usado para copiar o objeto. O ideal é adotar um critério único, por exemplo que seja shallow copy.
Um record faz uma cópia rasa quando usa o with.
Todo objeto tem o método MemberWiseClone() que copia o objeto de forma rasa sempre.
Você pode até criar uma interface sua para usar universalmente, mas tenha certeza que está documentado "proibindo" o uso de critério que não seja a cópia rasa, e avise que isso pode trazer problemas em alguns objetos, portanto eles não deveriam usar isso.
O mais comum é fazer esse tipo de cópia. Não tem problemas quando são objetos por valor ou imutáveis por referência. Os mutáveis por referência precisa cuidado porque alterando de um objeto altera do outro copiado também, mesmo sem mexer nele, nem sempre é o que deseja.
Por outro lado, pode ser o que deseja e precisa colocar tudo e torne completamente independente.
Algumas pessoas adotam o critério de deep copy apenas com um construtor de cópia, ou seja, um construtor que recebe um objeto do mesmo tipo para inicializar o novo objeto. Obviamente ele não participa de herança. Outra possibilidade é ter um método DeepCopy() para este fim.
Pode ser mais complicado porque pode ter campos que devem ser copiados de um jeito e outros copiados de outro. Aí não tem como você classificar o método como sendo raso ou profundo, tem que especificar cada campo, que é um vazamento de abstração. Engenharia de software pode ser bem mais complicada do que parece, por isso em muitos casos fazer o simples, até mesmo o menos robusto, é mais fácil.
Copiar objetos é algo muito mais complicado do que as pessoas imaginam. E muitas cópias ocorrem sem ser facilmente perceptível.
Comment: Não existe exatamente o jeito certo, cada objeto pode exigir uma forma diferente, mas todas vão sendo transportar um valor por vez de um objeto para o outro. Em raríssimos casos uma cópia bruta do objeto em baixo nível é interessante.
Comment: E qual o jeito certo de copiar um objeto?


Recuperar parte de uma string (split ou indexOf)

Question: Tenho uma estrutura de pasta assim:
bco_img/3/foto_produto/
bco_img/3/foto_produto/tb/
bco_img/4/foto_produto/
bco_img/4/foto_produto/tb/
etc...

Quero recuperar a pasta /3/ depois /4/ e também o nome das fotos que estão dentro de cada pasta, ex: pasta: /3/  foto: xyz.jpg
Fiz algo assim:
string url_Fonte = Server.MapPath("BCO_IMG");

DirectoryInfo diretorio = new DirectoryInfo(url_Fonte);
   FileInfo[] Arquivos = diretorio.GetFiles("*.jpg", SearchOption.AllDirectories);
      foreach (FileInfo fileinfo in Arquivos)
      {
       string nome_dir =  fileinfo.DirectoryName;
       string v1 = nome_dir.IndexOf(@"BCO_IMG\").ToString();
    // aqui qual é o melhor? fazer uma função para recuperar pelo indexOF ou criar um Array com Split() ?

      string nome_foto = fileinfo.Name;
      }

Comment: É isto que quer? http://pt.stackoverflow.com/questions/35400/como-obter-um-trecho-de-uma-string/35401#35401
Answer: Pelo jeito, o formato "url_Fonte/sua pasta/etc./nomearquivo" é fixo. Então..
string subdir = nome_dir.ToLower().Replace(url_Fonte.ToLower() + "/", "").Split('/')[0];
// ou
string subdir = nome_dir.Split('/')[1];

Depois, você pode envolver o subdir dentros das barras ("/" + subdir + "/").
Para obter o nome do arquivo:
string nomearquivo = nome_dir.Split('/').ToList().Last();
// ou
string sub = nome_dir.Split('/');
string nomearquivo = sub.IndeOf(sub.Length - 1);

Comment: não funcionou, porém o link do bigwon, levou a uma url que da uma solução parecida com a sua que acabou dando certo. Agradeço
Answer: Consegui com o link do Maniero
 string nome_dir =  fileinfo.DirectoryName;
string[] Valores = nome_dir.ToString().Split(new char[] { '\\' });
var palavra = Valores[7];

acho que com expressão regular também daria
Regex regex = new Regex("^~/BCO_IMG/(?<output>[Z0-9]+)/*/.*$");
GroupCollection capturas = regex.Match(source).Groups;
Response.Write(capturas["output"]);


Correspondence between prime ideals and Galois orbits of affine points on an elliptic curve

Question: In notes of prof. W.Stein -  http://wstein.org/edu/2010/581b/stein-algebraic_number_theory.pdf - the first paragraph of page 112 has the following told:
"When $K$ is a perfect field, the prime ideals correspond to the Galois orbits of affine points of $E(\bar{K})$."
I would be thankful if someone could elaborate what is meant here by the Galois orbits of points of $E$ and what is the implied correspondence.
Thank you!
Comment: It is the Galois group of $\overline{K}$ over $K$! Note that since $E$ is defined over $K$, there is an action of this Galois group on $E(\overline{K})$.
Comment: Do you know the Nullstellensatz?
Comment: Yes. Here, I fail to see what is the Galois group whose action on $E(\bar{K})$ the term "galois orbit" suggests; it doesn't seem to be the Gal(K(x, y)/K(x)).
Comment: Thanks! I'll have to think a bit then; wll ask here again if I won't manage to clarify the rest by myself.
Comment: Sounds good. Perhaps you'd like to take a look at the first chapter of Silverman's *Arithmetic of Elliptic Curves*.
Comment: After some thought I realized it is trivial (basically, correspondence between prime ideals and irreducible algebraic sets). Thank you anyway.
Comment: P.S. I do not mind if the question gets deleted.
Comment: You're welcome anyway. The right thing to do in this situation would be to answer your own question and accept the answer, so that other users can benefit from it.
Answer: When $K = \bar{K}$, the correspondence defined by $P \mapsto \{r \in R: r(P) = 0\}$ is the well-known bijection (as follows from the Nullstellensatz, prime ideals correspond to irreducible algebraic sets), while when $K \neq \bar{K}$, any $\sigma(P)$ gets mapped to the same prime ideal when $\sigma$ runs through $Gal(\bar{K}/K)$.


Pushing element into array inside for loop

Question: I want to dynamically generate a 50 element array from a single element, by just modifying one value on each loop.
const eventRecords = { Records: [] }
      for (let i = 0; i < 50; i++) {
        const aRecord = Object.assign({}, eventS3Chunk.Records[0])
        aRecord.s3.object.key = `F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/${i}.csv`
        eventRecords.Records.push(Object.assign({}, aRecord))
      }

eventRecords.Records end up with 50 copies of same element with s3.object.key = F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/49.csv.
Comment: Take a look into deep cloning. In your example, the s3 and/or object is being passed by reference and therefore assigning the key to one, affects all records.
Comment: Object.assign is not a deep copy, for copying nested object one method is JSON.parse(JSON.stringify(obj))
Answer: it's because you're creating a shallow copy of Records[0], use JSON.parse(JSON.stringify(eventS3Chunk.Records[0]));
 :

const eventS3Chunk = {
  Records: [{
    s3: {
      object: {
        key: "a"
      }
    }
  }]
};

const eventRecords = Array.from({
  length: 50
}, (_, i) => {
  const aRecord = JSON.parse(JSON.stringify(eventS3Chunk.Records[0]));
  aRecord.s3.object.key = `F7kdfh2Dj3j2s8/uploads/10000_users_without_password-20190102T030405Z/${i}.csv`;
  return aRecord;
});

console.log(eventRecords)


unable to extract tar file though ansible unarchive module in macOS?

Question: I have written a playbook which download the tar file & extract it to some directory in Mac.But when I run the playbook it fails with below error

"msg": "Failed to find handler for \"/Users/harmeet/.ansible/tmp/ansible-tmp-1549339698.75-251687957122076/config.tar9IXAUQ.gz\". Make sure the required command to extract the file is installed. Command \"/usr/bin/tar\" detected as tar type bsd. GNU tar required. Command \"/usr/bin/unzip\" could not handle archive.

Code for playbook
-name: Download the tar for sample config
unarchive:
 src: http://someremoteurl/config.tar.gz
dest: /Users/{{ansible_user}}/.myfolder/
remote_src: yes
creates: /Users/{{ansible_user}}/.myfolder/config

If use a zip fie on remote Server such as http://someremoteurl/config.zip then this task works but for tar files it fails .
I have also installed gnu tar such as gtar & updated path in .bash_src after reviewing this question
Comment: The proper place for the updated `$PATH` is `~/.bashrc`, not `~/.bash_src`.
Comment: Have you tried "[unarchive](https://docs.ansible.com/ansible/latest/modules/unarchive_module.html)" module
Comment: of course check my playbook file code.I have used it
Comment: Have you tried adding `environment:\n  PATH: /usr/local/bin:/usr/bin:/and/so/forth\n` to the `unarchive:` module? It actually does [prefer `gtar`](https://github.com/ansible/ansible/blob/v2.7.5/lib/ansible/modules/files/unarchive.py#L618-L619) if it can find it in your `PATH`
Answer: Actually on macOS it looks for GNU based tar archive module which was not found on mac. So if you use zip module for mac in ansible it will work but for that we may need to change the playbook file & it can create issues as i am using single playbook for both mac and linux. I used GNU based tar archive module to solve this issue.
I solved this issue by below steps

Install gtar by homebrew. brew install gnu-tar
Set path of gtar in .bashsrc file otherwise it will not able to use gtar for unarchive. Usually .bashsrc exist at $HOME path. if not exist then create it.

export PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"
      export MANPATH="/usr/local/opt/gnu-tar/libexec/gnuman:$MANPATH"

Thanks
Comment: I am glad it helped you in some way.
Comment: Assuming brew on an Intel Mac and not an M1
Answer: If your default shell is zsh, then you should put the following in ~/.zshenv:
export PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"

You can check if it's working correctly by:
ansible the-hostname -m command -a "which tar"


Identifying transactional trends

Question: I'm not sure if this is the right forum but here goes:
I have a requirement to attempt spot patterns in data , more specifically bank transaction data. There is transaction date, amount, description e.g.
<code>6/2/2017 COFFEE 5$
6/2/2017 EMPLOYER DEPOSIT 1000$
10/2/2017 GROCERIES 50$
20/2/2017 EMPLOYER DEPOSIT 1005$
20/2/2017 GROCERIES 120$
</code>
There are hundreds of other entries for general transactions and credit card entries.
So in the above example would want to determine the employee deposit trend every two weeks.
I have extensive C#/general programming experience, just need some guidance as to what to look into. I understand this probably isn't a simple solution but any suggestions what areas to focus on would be appreciated.
If this isnt' the correct forum please let me know which one to go to.
Comment: Search this site for anomaly detection, there are many posts!
Answer: One of the options is to use ARIMA model that has implemented in many languages.
A very nice introduction is here (4 parts of reading, but worth to spend the time): http://ucanalytics.com/blogs/forecasting-time-series-analysis-manufacturing-case-study-example-part-1/

Identifying transactional trends


Passing the output of a function back to the input multiple times

Question: I have a function that takes a numeric value, and produces a numeric value. My code is as follows:
p<-function(a){
  sp(bp(a))
}

The sp and bp functions take a numeric entry, and produce a numeric outcome (sp and bp follow different operations). I want to run this function many times. The following code:
sp(bp(sp(bp(sp(bp(a))))))

has the effect I want, but obviously this isn't a practical approach for high numbers of iterations. How can I repeatedly feed the output of p back in to p as the input?
Comment: Can you share your function and tell which argument should be passed back to which input?
Comment: maybe with a `for` loop? `for(i in 1:n){x <- f(x)}`
Comment: I've edited the question to provide more details on my specific problem.
Comment: What about recursive function like in n factorial?
Comment: Agree with @Liman. But what's your base case? When do you want to stop calling the fucntion on its outpu.
Answer: EDIT: After clarification
So, if it is some known (limited) number of times you would like to apply p in succession, this would be one way (I have assumed some simple functions for sp and bp for illustration):
sp <- function(x) return(x+1)
bp <- function(x) return(2*x)
p <- function(x) return(sp(bp(x)))

# Applying p 3 times in succession:
p_old <- 1
for (i in 1:3){
  p_new =  p(p_old)
  p_old = p_new
}

p_new
#> [1] 15
# Which is the same as
p(p(p(1)))
#> [1] 15

Created on 2020-09-11 by the reprex package (v0.3.0)
I am not quite sure what use case you have in mind (because that can easily lead to an infinite "loop", but here is one (admittedly contrived) example of a function which sums some numbers regardless in how many lists they can be nested which is using a call of the same function in the function definition itself:
sum_of_c_or_list <- function(x){

  if (!is.list(x)) return(sum(x))
  else {
    x = unlist(x)
    x = sum_of_c_or_list(x)
    return(x)
  }
}
sum_of_c_or_list(1:3)
#> [1] 6
sum_of_c_or_list(list(1,2,3))
#> [1] 6
sum_of_c_or_list(list(list(1,2,3)))
#> [1] 6

Created on 2020-09-11 by the reprex package (v0.3.0)
Comment: Thanks - I don't think this approach can be used for my specific problem - I've updated the description to provide more details.
Comment: Just to add here: https://stackoverflow.com/questions/53026344/purrr-how-to-apply-recursively-a-function-n-times-over-one-value can also be of interest.


What does $\propto$ mean?

Question: From this article:

$\ldots$a maximum-a-postiori "a maximum-a-posteriori
  $(MAP_{x,k}^{\,\,\,\,\,1})$ estimation, seeking a pair $(\hat{x}, \hat{k})$ maximizing:
  $$p(x, k\mid y) \propto p(y\mid x, k)p(x)p(k).$$

What does the symbol '∝' mean in this context?
Comment: I think Seyhmus Güngören's answer is vague.  It's just how this question is usually answered, and I think it bears elaboration.
Comment: $\hat x$ and $\hat k$ are the values of $x$ and $k$ that make $p(x,k\mid y)$ as large as possible.
Comment: Bernoulli used it to mean "$=$".
Comment: Another question, are "x hat" and "k hat" the normalized version of vector x and k, having length 1? And why does this make sense?
Answer: It means proportional as a function of two variables $x$ and $k$ with $y$ fixed.
You have a prior probability density as a function of $x$ and $k$, which is just a product of a function of $x$ and a function of $k$, so that the random variables involved are independent in the prior distribution.  Then new data arrives: a random variable is observed to be equal to a number $y$.  The conditional density of that random variable given that the first two were equal to $x$ and $k$, is the first factor in the expression on the right.
The expression on the left is the conditional density of the random variables corresponding to $x$ and $k$ given that observed value equal to $y$.
Since it means proportional as a function of $x$ and $k$ with $y$ fixed, you need to multiply it by a normalizing constant that may depend on $y$ but does not depend on $x$ and $k$, in order to make it a probability density function, as a function of $x$ and $k$.  "Constant" in this case would mean not depending on $x$ and $k$.
"Constant" always means not depending on something.  Usually it's clear from the context what the "something" is, but I think it should be stated explicitly more often than it is in present-day conventional practice.  Here's a favorite example of mine, involving differentiation of exponential functions:
\begin{align}
\frac{d}{dx} 2^x & = \lim_{h\to0}\frac{2^{x+h}-2^x}{h} \\[10pt]
& = 2^x\lim_{h\to0}\frac{2^h-1}{h}\tag{1} \\[10pt]
& = (2^x\cdot\text{constant})\tag{2}.
\end{align}
In $(1)$, the factor $2^x$ can be taken out of the limit because it's "constant" but "constant" means not depending on $h$.
In $(2)$, "constant" means not depending on $x$.
Some instructors in calculus classes actually present this proof without mentioning the contextual change in the meaning of "constant".
Later note in response to comments below: The linked paper uses a rather obnoxious notation, $p(x)$ and $p(k)$ for the probability density functions of two different random variables.  One should distinguish between capital $X$ and lower-case $x$ in expressions like $\Pr(X=x)$, where capital $X$ is a random variable and lower-case $x$ is a particular value that $X$ might be equal to.  Then, if one writes $p_X(x)$ for the value of the probability density function of a random variable (capital) $X$ at the point (lower-case) $x$, then one knows that $p_X(3)$ means something different from $p_Y(3)$.
But at any rate, $p(x)p(k)$ is the notation used in the linked paper for the joint density function of a pair of independent random variables, and $p(y\mid x,k)$ is the conditional density of another random variable given the values of those two.  The idea is that if you multiply those, what you get is proportional, as a function of $x$ and $k$ with $y$ fixed, to the conditional density function of the random variables corresponding to $x$ and $k$, given an observed value of the random variable corresponding to $y$.
Comment: Thanks. Oh, and btw. Could you answer my comments on your answer? http://math.stackexchange.com/questions/323000/convolution-of-integer-sequences
Comment: Since, I don't know much about statistics, I would like to ask you: Could you go through it, step-by-step, referring to which part of the formula you are talking about.
Answer: The symbol you've written means propotional. Check:
http://en.wikipedia.org/wiki/List_of_mathematical_symbols
Comment: But does it mean proportional as a function of $x$ with $k$ and $y$ fixed, or proportional as a function of $y$ with $k$ and $x$ fixed, or proportional as a function of $k$ with $x$ and $y$ fixed?  My guess is none of the above: it means proportional as a function of two variables $x$ and $k$ with $y$ fixed.
Comment: It means right and left hand side of the equation behaves similarly. Can happen that there is a simple constant factor. For each equality one can use this term. Additionally whenever this term is used, left hand side can be obtained from the right hand side by just a simple scaling. Examples: "If an object travels at a constant speed, then the distance traveled is directly proportional to the time spent traveling, with the speed being the constant of proportionality."
"The circumference of a circle is directly proportional to its diameter, with the constant of proportionality equal to $\pi$.
Comment: It is **MAP**. So the difference between **ML** is the *a priori* probabilities, which are taken As some scaling factors in **MAP**. Therefore $p(x)$ and $p(k)$ in this context are jointly the scaling factor.
Comment: It might also happen that he is indicating the independecy between $T$ and $X$.  One should see more about the content
Comment: Thanks, now, how to interpret it, if you want to write it as one sentence? So, lets say if you want to explain it to a non-mathperson.
Comment: . . . and my comment stands, for reasons that I think should be clear if you read the answer I posted.

What does $\propto$ mean?


Creating a poll inside a content type

Question: I need a poll inside my content types.
Sometimes the users create an article and like to create a poll directly into the node they created. They don't want to create an extra poll with no connection to the original article.
So how can I get the poll functionality inside a different content type?
Comment: D7 provides a Poll module by default. You can enable it.
Comment: I think I explained myself badly. I need to create multiple types of content they have in a field that allows to create a poll, as the content type module Poll.
Comment: Are you a site builder or a developer? Would you mind writing some line of code and having a lightweight module that does the job?
Answer: Possible solution 1: The Pollfield module seems to be a good starting point. This should do what you need for Drupal 6. However, it might not be a stable solution for Drupal 7.
Possible solution 2: It seems the Poll Improved module might be fit your requirements seeing that provides a field for polls. Though it also doesn't have a stable D7 release.

They don't want to create an extra poll with no connection to the original article.

You can use references (or entityreference) to have your article nodes reference a poll node. Though that would require another step for your content creators.
Comment: Here is a similar question that has some answers advising to render the poll node reference field. http://drupal.stackexchange.com/questions/28020/how-to-render-a-poll-within-a-node/28031#28031
Answer: Another solution:

Add reference field from Article node to Poll node,
Use inline entity form to allow users adding Polls when adding/editing Articles
Comment: This is not working. See https://www.drupal.org/node/2300601
Answer: Another way might be to add some fields to content-type comments and use drupal chart to render the aggregated results as a pie chart or whatever...

pros: rather simple solution, based on stable modules and core;
cons: poor management.
Answer: Creating a new content type
Make sure you installed and enabled pollfield module correctly before you try to do the following.

Go to Administer->Content Management -> Content types -> Add Content type (system path: admin/content/types/add)
Enter a name: Poll
And a type: poll
Submission form settings -> change "Title" field label to "Question"
If you like, you can also change the label of the body field
The other settings can be left as they are
Save!
On the next screen (system path: admin/content/types) locate the Poll content type and click on its edit link.
Adding the actual pollfield: Locate the "Add" area to find "New field" -> Label: Poll, fieldname: poll, field type: pollfield, widget: leave as is-> SAVE
Pollfield settings: explained at Pollfield book
IMPORTANT: "Global settings"-> required (so that you cannot accidently create a poll node without an actual poll)
SAVE!

You have just created an independent content type for polls. You may customize it by adding other fields. Do not forget that you can control the display settings at system path: admin/content/node-type/poll/display.

Creating a poll inside a content type


Drag drop jquery ui dialog box/ html / css

Question: Pessoal em uma aplicação gostaria de basicamente arrastar uma div que está dentro do dialog box e coloca-la em outra qualquer. Ao tentar fazer com meu codigo a div tende a sumir quando começo a arastar para fora. Segue link pra verificação. veja o codigo
Comment: O problema aí, que pelo menos eu percebi na documentação é que este **dialog** cria uma div própria com seu próprio **z-index** e não permite arrastar nada para fora deste espaço que ele cria, até por isso que nos exemplos lá na documentação o conteúdo destes dialogs são apenas texto, ou seja elementos estáticos.
Comment: No caso você quer tirar div "Selecionar Imagens" e colocar na div azul?
Comment: Não. Quero tira a div com a class="Tabimg" do dialog criado.
Answer: Descobri o problema. Ao fazer teste em outras div tipo janela modal, bastou colocar o overflow = false na propriedade css da div do modal. Tem nada haver o com o z-index. Obrigado pela ajuda de todos na resolução do problema.


How to open navbar ngbDropdown on hover?

Question: In Angular 2 ng-bootstrap is it possible to open a bootstrap navbar ngbDropdown on hover?
Comment: https://github.com/ng-bootstrap/ng-bootstrap/issues/1117
Answer: call the opening and closing function on mouse enter event and mouse leave event
(mouseenter)="$event.stopPropagation(); myDrop.open();"
(mouseleave)="$event.stopPropagation(); myDrop.close();"


i am looking to a max value from list of string with special characters. getting the expectedd behaviour can some one help out?

Question: Here is my code:
public class MaxValue {

    public static void main(String[] args) {

        // call the getMaxValue from the list
        // expected value is 13
        System.out.println(getMaxValue(Arrays.asList("<12.5", "5", "10", "-1", "12.5", "13")));}

       //get max value 13 and am expecting the output to be 13

    }

// I am unable to get the particular behavior can someone please help me out
    public static String getMaxValue(List<String> values){
        String result = null;
        for (String value : values) {
            //logic
        }
        return result;
    }
}

Comment: would you please explain what does the "<" character mean? and what are the valid characters?
Comment: @shekar Than post what you have tried and what was the output. Currently it looks like you want us to do it for you.
Comment: @shekar You might know what you have tried, but if you won't show you really tried it yourself no one here will help you. Go over [How do I ask a good question](https://stackoverflow.com/help/how-to-ask). Have a nice day.
Comment: Try it yourself first.
Comment: Your question is not clear. Avoid making long titles. Describe the problem, input and expected output appropriately.
Comment: @dryleaf input is Arrays.asList("<12.5", "5", "10", "-1"))  output value is String and value expected is <12.5.
Comment: @hamid ghasemi that means value can be less than 12.5  and value can be -1 . I can say the max is <12.5 since the value can be 12.49
Comment: What are the valid inputs? Strings or integers or both strings and integers? and why? Also give a clear example of `input` -> `output` with explanation.
Comment: @dryleaf the value is stored in database as string. its stored database as <11 , 10, -1 , 2.0, 5.99 so if i want to show the user the max value for that data type i need to show him the value has <11. I have read access to table so in my logic i need to show the max value has <11 on the screen
Comment: @guy If you can help me out. I have already tried and am not getting the expected behavior
Comment: Why are you using input `<` in your input (`<11 , 10, -1 , 2.0, 5.99`)?
Comment: @dryleaf that's how the value is stored in database. I don't know why you are not getting the question.
Comment: @Guy it seems like you don't know how to solve it. I know what i have tried.
Comment: what are the valid special characters ? "<" and "<=" ? or anything else exist ?
Comment: @Hamidghasemi possibility of values are "<" , "-" .
Comment: @Guy public static String getMaxValue(List values){
  double max = 0.0;
  for (String value : values) {
   //logic
   value = value.replaceAll("[^\\d-.]", "");
   double curent = Double.parseDouble(value);
   if(curent > max){
    max = curent;
   }

  }
  return String.valueOf(max);
 }
Comment: with this code i get the value has 12.5 but i want to see the output has <12.5
Comment: @Guy if i use the < character in replaceAll function i get some times number format exception or patternsyntaxexception
Comment: @Guy can you help out?
Answer: public class Main {

    public static void main(String[] args) {
        System.out.println(getMaxValue(Arrays.asList("<12.5", "5", "10", "-1")));
    }

    private static String getMaxValue(List<String> strings) {
        List<INumber> numbers = new ArrayList<>();

        for(String a : strings){
            numbers.add(new INumber(a));
        }
        Collections.sort(numbers);
        return numbers.get(0).getExactString();
    }

}

class INumber implements Comparable<INumber>{

    private String exactString;
    private float removedSpecials;

    INumber(String exactString){
        this.exactString = exactString;
        removedSpecials = Float.parseFloat(exactString.replace("<", ""));
    }

    public String getExactString(){
        return exactString;
    }

    public boolean hasSpecialChar(){
        return exactString.contains("<");
    }

    public float getExactNumber(){
        return removedSpecials;
    }

    @Override
    public int compareTo(@NotNull INumber iNumber) {
        if(iNumber.getExactNumber() > getExactNumber())
            return 0;
        else if(iNumber.getExactNumber() == getExactNumber()
              && !iNumber.hasSpecialChar() && hasSpecialChar() )
            return 0;
        else
            return 1;
    }

}

Comment: @hamidghasemi I think this should be using Float.compareTo. Testing equal (0) is a possibility, which should followed by a special characters check. Special characters "<" means less than, so <12 should test less than 12. Furthermore, why use floats instead of doubles? Might as well take the better precision.
Comment: Thanks for your solution I really appreciate your help. I just want to know how did you got the idea to solve this solution just eager to know the approach. Since i am working java6 code I can't use NotNull annotation instead i have to use iNumber != null Is it right in if condition
Comment: its not working for expected behaviour. If the value is ("<12.5", "5", "10", "-1", "12.5", "13") then the value should be 13 since the max value in list is 13
Comment: @PatrickParker can you tell me where do i need to change code so that i can implement. If possible can you explain at which line i need to change
Comment: @shekar Educate yourself. Search for "JAVA How to parse double" and "JAVA How to implement Comparable." Try, try, try. When you get stuck on a specific problem then open a specific question. This question is too broad. That is why it was closed!
Comment: @PatrickParker I don't understand what you mean. exactNumber is float and I'm comparing two floats.
Comment: @PatrickParker I had forgotten to check if a number has special character. thanks. about the doubles, I just assumed float is enough, he can change it to double if he want :)
Answer: Since this is Java, I advise you to go with an Object-Oriented approach.
First, you need to create a class representing a NumberLinePosition, which will implement the Comparable interface.
public class NumberLinePosition implements Comparable<NumberLinePosition> {
    public NumberLinePosition(String toParse) {

The members will be an double (to hold the numeric portion of the String, and another variable to hold the positional modifier. For modifier, I would recommend using an enum (LESS_THAN, NO_MOD, GREATER_THAN).
You will then need to write a compareTo method that first compares doublePart then compares modifier.
int compareTo( NumberLinePosition a ) {

Once you have completed this, it will be a simple matter to keep a list of NumberLinePositions and sort them using Collections.sort(myList);
Comment: thanks for your comment I am new to java. It is too difficult for me to understand.
Comment: I don't have teaching assistant. I am working on my own for project.So currently I am facing this challenge to solve
Comment: @shekar then you should search for related tutorials on these concepts. Or consult your teacher. StackOverflow is not suitable for extended tutoring conversations.
Comment: can you please reply to hamid code please. I am unable to get the result 13 if the list contains the max is 13


Hazard function for a growing population

Question: I want to model the expected failure rate in a growing population.
Each individual has a high infant mortality (e.g. Weibull(shape=0.5, scale=100)).
So the failure rate (or hazard function) at time t, H(t), is the density function divided by the survival function: H(t) = pdf(t)/sf(t)
The complication is that at every timestep, I have many individuals in my population. They have different age, and therefore different expected failure rates, which is given by their hazard function h(t). The expected failure rate of the population as a whole is a mix of these hazard functions. How do I compute that?
My first instinct was to sum up densities and survival functions individually, and then divide one by the other.
pdfs = numpy.zeros(max_time)
sfs = numpy.zeros(max_time)
for t in individual_start_times:
    ts = numpy.arange(max_time-t)
    pdfs[t:] += scipy.stats.weibull_min.pdf(ts, shape=0.5, scale=100)
    sfs[t:] += scipy.stats.weibull_min.sf(ts, shape=0.5, scale=100)
hazard = pdfs/sfs

Does that make sense, or is that bogus? I'm struggling to verify this.
Comment: As an epidemiologist reading "high infant mortality" is quite confusing: "high" implies that "infant mortality" which "high" intensifies is an infant mortality *rate*. However, *individuals* do not have mortality rates: they are either dead or alive (or sometimes  "kinda dead" or "mostly dead", c.f. S. Morgenstern)
Comment: @Alexis Well, an individual can be not even born yet, and still we can have expectations about their lifespan. In other words, consider an individual as a random variable, not as a particular outcome.

Suppose you know the dates at which kids will be born in an area, and you know the distribution of their lifespan. Then you have a probability of death at day t for a particular kid. But how do you get the expected death rate at day t of the entire population?
Comment: I would use "expected mortality risk" (or, if you care about life span "life expectancy").
Comment: Where you say "expected failure rate of the population as a whole" are you trying to calculate the distribution of the time to extinction (i.e. the expected time until the entire population is dead)?
Comment: No, I care about the expected failure rate. The expected number of deaths over expected number alive.
Answer: If I understood you correctly, you could fit a Weibull model to your data with Age as the covariate/predictor. And then from this model extract the estimated hazard function. The following code illustrates how this can be done in R using the survival package:
library("survival")

# Accelerated Failure Time (AFT) Weibull model
fm <- survreg(Surv(time, status) ~ age, data = lung, dist = "weibull")
summary(fm)

# transform coefficients to Proportional Hazards (PH) scale
# (Weibull only model capable of having both AFT and PH formulations)
shape <- 1 / fm$scale
X <- model.matrix(fm)
scale <-  exp(- shape * c(X %*% coef(fm)))

# function to calculate hazard function for
# every subject in the data for a set of time points
ht <- function (time, shape, scale) {
    outer(shape * time^(shape - 1), scale)
}

# A figure of the estimated hazard for the
# first 5 subjects
times <- seq(0.001, 1000, length = 500)
matplot(times, ht(times, shape, scale[1:5]), type = "l", lty = 1,
        xlab = "Follow-up Time (days)", ylab = "Estimated Hazard Function")
legend("bottomright", paste("Patients", 1:5), col = 1:5, lty = 1, bty = "n")

Comment: Thanks for your answer. This isn't what I'm looking for though. I have the fitted Weibull distribution already, and I know the hazard function of this distribution. But for any time t, I have multiple things alive, and each thing has a different age and thus a different chance of failure at that time. So I have the expected chance of failure of each instance, and what I'm looking for is the expected failure rate of the entire population at time t.
Comment: Thanks for the clarification. Then would it work if you fitted the Weibull model without age as a predictor? This would give you one hazard function for the whole sample that would be an estimate of the hazard function of the entire population.
Comment: I don't think so. I don't have a sample I'm trying to fit to. I'm doing predictions about the future, so I have a rate at which new lifetimes start, each life follows the same Weibull distribution, and I want to draw conclusions about the global failure rate at any future time.


Estou tendo problemas com o appendChild em javascript

Question: Código HTML

Product Backlog

    <button type="button" id="bto-pBacklog" class="buttonNewCard">+ Adicionar cartão</button>

O sistema deve incluir na div class containerCards uma div com um textarea dentro quando o botão "+Adicionar Cartão" for clicado, após o clique ele de ser substituído pelo botão "Criar Card" e quando o botão "Criar Card" for clicado ele deve ser substituído pelo botão "+Adicionar Cartão".
Obs. o sistema tem mais de uma estrutura com classes diferentes e estou diferenciando elas escutando o click do mouse, que retorna o id do botão clicado e através dessa informação seleciono os botões e as estruturas nas quais as automações devem acontecer!
O sistema está acusando o seguinte erro:

Uncaught TypeError: Cannot read properties of null (reading
'appendChild')
at criaCard (31)
at HTMLDivElement.selecionaBotao (13)

e não estou conseguindo remover a class invisivel do botão "+Adicionar Card"
Código Javascript
const escutaClick = document.querySelector('.workSpace');

escutaClick.addEventListener('click', function selecionaBotao(click) {
    var idBotao = click.target.id;
    var idContainer = idBotao.replace('bto-', '');
    // Remove o botão Adicionar cartão
    var btoAddCard = document.getElementById(idBotao);
    btoAddCard.classList.add("invisivel");
    //=============>Criar estrutura do card<===============
    var { criarDiv, selecionarDiv } = criaDiv(idContainer);
    criaCard(criarDiv, selecionarDiv);
    CriaBto(idContainer);
});

//Cria elemento div
function criaDiv(idContainer) {
    var selecionarDiv = document.getElementById(idContainer);
    var criarDiv = document.createElement("div");
    criarDiv.setAttribute("class", "card");
    return { criarDiv, selecionarDiv };
}

// Cria elemento textarea
function criaCard(criarDiv, selecionarDiv) {
    var textarea = document.createElement("textarea");
    textarea.setAttribute("class", "textCard");
    textarea.setAttribute("placeholder", "Descreva a atividade");
    textarea.setAttribute("onfocus", "this.selectionStart");
    criarDiv.appendChild(textarea).focus();
    selecionarDiv.appendChild(criarDiv);
}

// Criar botão Criar card
function CriaBto(idContainer) {
    var string = "criabto-";
    var criarCard = document.createElement("button");
    criarCard.setAttribute("type", "button");
    criarCard.setAttribute("id", string.concat(idContainer));
    criarCard.setAttribute("class", "criar-card");
    criarCard.appendChild(document.createTextNode('Criar Card'));
    var larguraetapa = document.querySelector("." + idContainer);
    larguraetapa.appendChild(criarCard);
}

Answer: const escutaClick = document.querySelector('.buttonNewCard');

escutaClick.addEventListener('click', function selecionaBotao(click) {
var idBotao = click.target.id;
var idContainer = idBotao.replace('bto-', '');
// Remove o botão Adicionar cartão
var btoAddCard = document.getElementById(idBotao);
btoAddCard.classList.add("invisivel");
//=============>Criar estrutura do card<===============
var { criarDiv, selecionarDiv } = criaDiv(idContainer);
criaCard(criarDiv, selecionarDiv);
CriaBto(idContainer);
});

//Cria elemento div
function criaDiv(idContainer) {
var selecionarDiv = document.getElementById(idContainer);
var criarDiv = document.createElement("div");
criarDiv.setAttribute("class", "card");
return { criarDiv, selecionarDiv };
}

// Cria elemento textarea
function criaCard(criarDiv, selecionarDiv) {
var textarea = document.createElement("textarea");
textarea.setAttribute("class", "textCard");
textarea.setAttribute("placeholder", "Descreva a atividade");
textarea.setAttribute("onfocus", "this.selectionStart");
criarDiv.appendChild(textarea).focus();
selecionarDiv.appendChild(criarDiv);
}

//Remover Elementos
function Remover(Card) {
const BotaoCriar = document.querySelector(".criar-card");
const BotaoAdicionarCartao = document.querySelector('.buttonNewCard');
Card.remove();
BotaoCriar.remove();
BotaoAdicionarCartao.classList.remove("invisivel");

}

//Posta o cartao criado
function PostarCard() {
const ContainerCards = document.querySelector('.containerCards');
const TextAreaConteudo = document.querySelector('.textCard');
const CriarCard = document.querySelector('.card');
if (TextAreaConteudo.value) {
    const p = document.createElement("p");
    p.innerText = TextAreaConteudo.value;
    ContainerCards.appendChild(p);
    Remover(CriarCard);
} else {
    alert("voce deve Adicionar algo ao card")
}
}

// Criar botão Criar card
function CriaBto(idContainer) {
var string = "criabto-";
var criarCard = document.createElement("button");
criarCard.setAttribute("type", "button");
criarCard.setAttribute("id", string.concat(idContainer));
criarCard.setAttribute("class", "criar-card");
criarCard.appendChild(document.createTextNode('Criar Card'));
var larguraetapa = document.querySelector("." + idContainer);
larguraetapa.appendChild(criarCard);
criarCard.addEventListener("click", PostarCard);
}

adicionei duas funções uma para adicionar e outra para remover, eu editei pois estava adicionando varias classes no mesmo elemento, enfim voce estava na primeira linha pegando um elemento que nao tinha Aquela classe, nao tive o exato problema que voce descreveu e no meu pc funcionou de boa mas uma dica seria substituir os 'var' por 'let' ou 'const' pois talvez seja um problema de escopo, se mesmo assim nao resolver voce pode verificar os nomes das classes e dar varios console.log pelas funções nao é tao rapido mais funciona ou debugar no chrome
Comment: Obrigado nicolas, com uma etapa o seu código funciona perfeitamente, porém o caso é que  o sistema que estou desenvolvendo tem 7 etapas e nas demais etapas nem adiciona a div quando clico no botão adicionar cartão! Mas obrigado pela ajuda!!!
Comment: é justamente por esse motivo que eu criei as variáveis idBotao e idContainer, para passar o botão da etapa em que eu quero adicionar o card e adicionar o card na etapa em que eu estou clicando em adicionar cartão!
Comment: a sim entendo, voce nao teria esse codigo completo disponivel teria? voce disse que esta usando classes, e que na primeira etapa funciona mas nas demais nao, voce pode dar uma olhada no contexto do 'this'. mas se voce tiver o codigo no git hub seria mais facil tentar ajudar


Probability of winning a dice game.

Question: There is a game with two players and they throw a pair of dice. Player 1 wins if the sum is 7 and player 2 wins if the sum is 6. The stakes are split if neither player wins. What is the expectation of each player? Suppose the game continues until someone wins. What is the probability that each will win if player 2 starts?
Comment: In the first game, do they toss simultaneously? And if so, what happens if they both "win"?
Comment: The question will presumably be answered by tomorrow. If not, I will write a solution (it is late).
Comment: What is the significance of player 2 starting (first)? Do the players plays in rounds with the property that a player can win if and only if he/she is the thrower, or do the players throw the two dice together (in which case, who "starts" doesn't matter)?
Comment: @AndréNicolas I think the game is set up so that each one follow their own turns.
Comment: @AndréNicolas Thanks. I will be eagerly waiting for solution.
Comment: @Unit They play in turns, so one after the other throw the dice until one of them get their respective sum. Meaning, player 1 throws the dice first and didn't get a 7; therefore, player 2 gets to throw the dice. The game doesn't end until one of them gets their respective sum during their turn.
Answer: Your probabilities are correct: in a given round, player 1 has probability $p = 1/6$ of winning and player $2$ has probability $q = 5/36$ of winning. The expectation of each player (assuming you mean winnings) is $pd$ for player 1 and $qd$ for player 2, where $d$ is the amount of money in the pot.
If we now let the game continue until someone wins, a third possibility arises: each round, the probability of passing to the next round is either $1-p$ or $1-q$, depending on whose turn it is.
Let $A$ mean "player 1 wins", let $B$ mean "player 2 wins",
and let $\bar{A}$ mean "player 1 loses" and let $\bar{B}$ mean "player 2 loses" (on a round-by-round basis). From your clarification in your comment, it follows that if player 2 starts, the first round's possible outcomes are $B$ or $\bar{B}$, the second round's possible outcomes are $A$ or $\bar{A}$, and so on, alternately. Thus, the possible game sequences are $\{B, \bar{B}A, \bar{B}\bar{A}B, \bar{B}\bar{A}\bar{B}A, \bar{B}\bar{A}\bar{B}\bar{A}B, \dotsc\}$.
The probability of a sequence like $\bar{B}\bar{A}\bar{B}A$ is the product of the probabilities: $$(1-q)(1-p)(1-q)p.$$
Now, player 2 wins iff the game sequence was one of the following: $\{B, \bar{B}\bar{A}B, \bar{B}\bar{A}\bar{B}\bar{A}B, \dotsc\}$.  Thus, the probability of player 2 winning is
$$\sum_{k=0}^\infty [(1-q)(1-p)]^kq = \frac{q}{1-(1-p)(1-q)} = \frac{q}{p + q - pq}$$
by the geometric series formula.
Player 1 wins iff the game sequence was one of the following: $\{\bar{B}A, \bar{B}\bar{A}\bar{B}A, \bar{B}\bar{A}\bar{B}\bar{A}\bar{B}A, \dotsc\}$.
Thus, the probability of player 1 winning is
$$(1-q)\sum_{k=0}^\infty[(1-p)(1-q)]^k p = \frac{p(1-q)}{p+q-pq}.$$
Comment: I think you're making a mistake with your $X$'s. You say in the first round possible outcomes are $B$ and $X$ and in the second round $A$ and $X$. That means these $X$'s are not the same. They're $(1-q)$ and $(1-p)$, respectively.
Comment: Yes, you're right! Let me fix that!
Comment: Yes, plugging in $p = 1/6$ and $q = 5/36$ into the above formulas yields $31/61$ for player 1 and $30/61$ for player 2.
Comment: @Unit Thanks a lot for your explanation and detail solution. Just one more question, according to the geometric series the probability of winning for player 2 is 30/61 and for player 1 is 31/61, right ?
Comment: @Unit Thanks a lot for all the help.
Answer: I know that for player 1 there are 6 ways to get a 7, so he has 6/36 = 1/6 probability of getting that combination. Player 2 has 5/36 probability of getting a combination of 6. However, how do I proceed from here? Thanks.
Answer: For the first question, I will assume that Player 1 goes first, and if she tosses a total of $7$ she has won, the game is over. So the probability she wins is $\frac{6}{36}$.
In order for Player 2 to win, Player 1 must not win, and then Player 2 must toss a total of $6$. The probability that Player 2  wins is therefore $\frac{30}{36}\cdot \frac{5}{36}$.
The game is a lot fairer if Player 2 tosses first. Then her probability of winning is $\frac{5}{36}$, and the probability Player 1 wins is $\frac{31}{36}\cdot\frac{6}{36}$.
In general, let $a$ be the probability a certain player A wins, and b the probability the other player B wins. Note that a draw is also possible, indeed quite likely.
If the players bet a dollar on the outcome, then A's expected net winnings are $(a)(1)+(b)(-1)+(1-a-b)(0)$, or simply $a-b$.
The second game is a lot more clearly specified. Let $p$ be the probability Player 2 (who goes first) ultimately wins.
She wins if she gets a sum of $6$ immediately, or if she doesn't but still ultimately wins. That happens if she strikes out on her first toss, and Player 1 also does, and Player 2 ultimately wins. Given they both struck out, the probability Player 2 ultimately wins is $p$, since in essence the game starts again. Thus
$$p=\frac{5}{36}+\frac{31}{36}\cdot\frac{30}{36}\cdot p.$$
Solve this linear equation for $p$.
Alternately, we can produce an infinite geometric series for the probability Player 2 ultimately wins. The probability Player 1 ultimately wins is $1-p$.

Probability of winning a dice game.


A problem with polynomials.

Question: This is a problem from a test in my course in analytic functions. I didn't manage to solve it. Could you please give me a hint? The problem is:
Calculate the third root of the sum of the coefficients of the polynomial whose roots are the squares of the roots of the following polynomial:
$$P(z)=z^5-z+11.$$
Answer: Let's do this for a polynomial of degree $2$, with omission of some steps that you will probably be able to fill in yourself:
$$ P(z) = (z-a)(z-b), $$
then the polynomial under investigation is
$$ Q(z) = (z-a^2)(z-b^2) $$
The sum of its coefficients is $Q(1)$:
$$ Q(1) = (1-a)(1+a)(1-b)(1+b) = P(1)P(-1) $$
So the answer would be
$$ \sqrt[3]{ P(1)P(-1)},$$
I'll leave the details and generalisation to other degrees to you. (Note that there is an extra $-1$ appearing for odd degrees!)
Comment: Eh. Difference of squares. I'm a fourth-year student in mathematics. Thank you!

A problem with polynomials.