What to attach event listener to in Drupal behavior

Question: I have a use case where I need to listen to the insertIntoActiveEditor event in the insertIntoActiveEditor event in the Insert module, but with this code:
<code>(function ($) {

/**
 * Custom behavior to generate image style derivatives on S3 when an image is
 * inserted into the WYSWIYG editor.
 */
Drupal.behaviors.generateDerivative = {
  attach: function(context, settings) {
    $(document).on('insertIntoActiveEditor', function(event, data) {
      var test = 'a';

    })
  }
}
})(jQuery);
</code>
I'm getting an error that says
<code>Uncaught TypeError: $(...).on is not a function
</code>
on this line
<code>$(document).on('insertIntoActiveEditor', function(event, data) {
</code>
I thought I had that syntax correct, but apparently I don't. Do I need to change my selector to be the Insert button (the same as is used in the module JS)? I"ve tried changing it to
<code>$('input[value="Insert"]').on('insertIntoActiveEditor', function(event, data) {
</code>
but I still get the same error.
Thanks.
Answer: The cause was pretty basic - this is in the admin theme, which in Drupal 7 is set to use jQuery 1.4.4, and .on() wasn't added until 1.7. I switched to using .bind(), and it works fine now.


VB.NET comparison of an array with filename values from a Outlook mail item attachment list matches only once when more should happen

Question: I am writing an Outlook Email VB.NET program that should parse an email, place it into a form for modification of individual fields, and then save the mail and any attachments, as modified, into a directory on the file system.
I need to read values into an array from a multi-line textbox containing attachments. Then I compare them to the values in the complete list of file names in the Microsoft.Office.Interop.Outlook.Application.MailItem.Attachment.FileName values. I can only match each filename once though.  Only the first value in the text box will match. It doesn't matter what the value is, as long as it is in the Microsoft.Office.Interop.Outlook.Application.MailItem.Attachment.FileName values, it matches that and nothing else.
In addition to the code I am posting, I have tried other methods like "contains" and "is" in place of the comparisons, but nothing changes except the "Is" won't match even the first time.  The code has gone through many modifications even though other methods still produced the same result.
Here is the relevant code:
    ' Dim mailAttachments As Outlook.Attachments = Mail.Attachments
    ListBoxAttachmentArray = SaveAttachment_List.Split(Environment.NewLine)
    If ListBoxAttachmentArray.Length > 0 Then
        For i As Integer = 0 To ListBoxAttachmentArray.Length - 2
            StatusBox.Text += Environment.NewLine & "A:" & ListBoxAttachmentArray(i)
            For j As Integer = 1 To mailAttachments.Count
                ' currentAttachment = mailAttachments.Item(j)
                StatusBox.Text += Environment.NewLine + ListBoxAttachmentArray(i)
                StatusBox.Text += " : " & mailAttachments.Item(j).FileName
                StatusBox.Text += Environment.NewLine + " i: " + i.ToString + " j: " + j.ToString
                If mailAttachments.Item(j).FileName = ListBoxAttachmentArray(i) Then
                    StatusBox.Text += Environment.NewLine & "MadeIt: " & mailAttachments.Item(j).FileName
                    'mailAttachments.Item(j).Save(UsedDir & mailAttachments.Item(j).FileName, True)
                End If
            Next
        Next
    End If

Here is a list of three files that are in my text box, as an example:

image001.jpg
Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx
BEV-15046A62-A_REV_17.zip

and here is the status text box I am using to trace the above code:

A:image001.jpg
image001.jpg : image001.jpg
 i: 0 j: 1
MadeIt: image001.jpg
image001.jpg : Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx
 i: 0 j: 2
image001.jpg : BEV-15046A62-A_REV_17.zip
 i: 0 j: 3
A: Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx
Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx : image001.jpg
 i: 1 j: 1
Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx : Mold RFQ 07162020 IP DriverAccent - Chinstrap.xlsx
 i: 1 j: 2
Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx : BEV-15046A62-A_REV_17.zip
 i: 1 j: 3
A: BEV-15046A62-A_REV_17.zip
BEV-15046A62-A_REV_17.zip : image001.jpg
 i: 2 j: 1
BEV-15046A62-A_REV_17.zip : Mold RFQ 07162020 IP Driver Accent - Chinstrap.xlsx
i: 2 j: 2
BEV-15046A62-A_REV_17.zip : BEV-15046A62-A_REV_17.zip
 i: 2 j: 3

Notice the "Made it" in the output.  This should happen three times, but only the first time the loops match causes it to happen.
How can I make this match each time?
Comment: Try applying `.Trim()` to the values before comparison .BTW, `For i As Integer = 0 To ListBoxAttachmentArray.Length - 2` should be `For i As Integer = 0 To ListBoxAttachmentArray.Length - 1`.
Comment: preciousbetine, Thank you so VERY MUCH.  Your answer with the .Trim() method solved this!  And, so quickly you replied!  I tried Trim, but I put the values inside the parenthesis instead of placing it at the end of the values.  As for the -2 V -1, my code needs the -2.  I am not entirely sure why this is, but I assure you it works only with the -2.  I will try to mark this correct (first post...)
Comment: What is this code actually doing? You have 3 items in your textbox and 3 attachments in your email; this entire code is unnecessary - just save the 3 attachments
Comment: The text box is editable.  Some files will not be saved, so the code does a match.  This may be ignorance, but I use the Microsoft.Office.Interop.Outlook.Application.MailItem.Attachment.SaveAsFile() method to actually save the attachments, but only on those that the end user keeps in the text box.  In the case in the example, there is a 100% match.  Perhaps in the question I should have done a partial list for your pleasure.
Answer: You should trim the string values before comparing them to get accurate results.
If mailAttachments.Item(j).FileName.Trim() = ListBoxAttachmentArray(i).Trim() Then
    StatusBox.Text += Environment.NewLine & "MadeIt: " & mailAttachments.Item(j).FileName
   'mailAttachments.Item(j).Save(UsedDir & mailAttachments.Item(j).FileName, True)
End If


How can I count the total records in a file while only displaying some?

Question: I'm using Visual Cobol to create a program that reads a file, has the user input criteria, and only displays the records in the file that meet the user's criteria. I need to display the number of records that meet the criteria, which I have done with an accumulator, but I also need to display the total number of records in the file, including the ones not displayed.
I am wondering if I can do it in a Sort statement. I have tried a few things but I'm unsure of the syntax needed.
This is my current sort statement:
<code>   B-100-PROCESS-FILE.

       PERFORM B-200-CRITERIA-CONTROL.

       SORT SORT-FILE
           ON DESCENDING KEY SR-UNIT-COST

           INPUT PROCEDURE B-210-SELECT-RECORDS
           OUTPUT PROCEDURE B-220-DISPLAY-REPORT.
</code>
New addition:
<code>   B-210-SELECT-RECORDS.

       OPEN INPUT CUSTOMER-SALES-FILE
       MOVE "N" TO SW-END-OF-FILE.

       READ CUSTOMER-SALES-FILE INTO CUSTOMER-SALES-RECORD

          AT END MOVE "Y" TO SW-END-OF-FILE
          NOT AT END ADD 1 TO AC-RECORD-TOTAL

       PERFORM B-370-RELEASE-RECORDS
           UNTIL END-OF-FILE.

       CLOSE CUSTOMER-SALES-FILE.
</code>
almost there...
Comment: You can count the records in the `Sort input procedure`
Comment: Take a little care of the conditional clauses.  The `PERFORM B-370...` is parsed as part of the `NOT AT END` clause, not as the source indentation may make it seem.  Use `END-READ` or a full stop on the `NOT AT END` phrase.
Comment: Is the count different from AC-RECORD-TOTAL?
Comment: No, I am trying to save the total record count in that variable.
Answer: I have a possible solution:
<code>   OPEN INPUT CUSTOMER-SALES-FILE
   MOVE "N" TO SW-END-OF-FILE.

   READ CUSTOMER-SALES-FILE INTO CUSTOMER-SALES-RECORD

      AT END MOVE "Y" TO SW-END-OF-FILE
   END-READ
   IF SW-END-OF-FILE NOT= 'Y'
      ADD 1 TO WS-CONT
   END-IF

   PERFORM B-370-RELEASE-RECORDS
       UNTIL END-OF-FILE.

   CLOSE CUSTOMER-SALES-FILE.
</code>


Calcular média com exame final se for reprovado nas notas normais

Question:

Ler os valores de quatros notas escolares bimestrais de um aluno     representado as pelas variáveis N1,N2,N3,N4. Calcular a média aritmética (variável MD1) desse aluno e apresentar a mensagem "Aprovado com média' se a média obtida for maior igual a 7.0; caso contrario o programa deve solicitar a quinta nota de exame, representada por NE) e calcular uma nova media, variável (MD2) entre a nota de exame e a primeira média. Se o valor da media for maior ou igual a 5, apresentar a mensagem "Aprovado com média"; caso contrario apresente a mensagem "Reprovado com média". Apresentar o valor da média ao lado de cada uma das mensagens.

Aqui foi a solução que encontrei:
<code># mudei as variaveis e a quantidade de notas, mas a essencia é a mesma. do que foi pedido.

a = float(input('Nota 1: '))
b = float(input('Nota 2: '))
c = float(input('nota 3: '))
m1 = (a + b) / 2
if m1 >= 7:
    print('Aprovado media %f' % m1)
else:
    m2 = (m1 + c) / 2
    if m2 >= 5:
        print('Aluno aprovado media %f' % m2)
    else:
        if m2 < 4:
            print('Reprovado media %f' % m2)
enter = input('\nPressione <ENTER> para encerrar...')
</code>
Essa solução seria satisfatória?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: De cara não está certo porque o exercício manda pedir 4 notas e você pede só 3 e divide por 2 sei lá porque (não sei o que espera de melhor fazendo isso errado, se for economizar a digitação de alguns caracteres, só causou confusão), depois começa fazer algo completamente sem sentido e que não é o que o enunciado pede (deve pedir outra nota). Os nomes das variáveis realmente não importam muito.
Eu acho a fórmula para pegar a nova média não pode usar a média antiga dividindo por 2 porque passa dar mais peso para a nota nova, mas é o que o enunciado pede, então vamos lá.
Não me preocupei com um possível erro de digitação que quebraria a aplicação, o correto é tratar isto.
<code>a = float(input('Nota 1: '))
b = float(input('Nota 2: '))
c = float(input('nota 3: '))
d = float(input('nota 4: '))
m1 = (a + b + c + d) / 4
if m1 >= 7:
    print('Aprovado media %f' % m1)
else:
    e = float(input('nota exame: '))
    m2 = (m1 + e) / 2
    if m2 >= 5:
        print('Aluno aprovado media %f' % m2)
    else:
        print('Reprovado media %f' % m2)
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Sim amigo eu tenho ciencia que a resolução proposta por mim esta diferente do enunciado. E foi exatamente por isso que fiz questao de por um comentario na resolução que fiz, explicando que estava diferente mas que a ideia central era a mesma. Mas entendi. E obrigado por ajudar.
Comment: Se o aluno não passou com as notas regulares tendo uma média 7, divide-se a nota obtida por 2 e então ele vai fazer um super provão ferrado para tentar se salvar valendo metade da nota do semestre, mas aí a média é 5. Na faculdade que me formei (UFMT) era exatamente assim.
Comment: @VictorStafusa é, tem dessas, eu já vi a prova de salvação substituir tudo o que valeu no semestre, ou seja, era mais arriscado (nem tanto porque se sabia que era mais fácil), mas dava menos trabalho só fazer ela. Era uma espécie de recuperação virtual já que não tinha aula de reforço, alias nunca vi isso sério, nem em escola alemã toda certinha recuperava o aluno de verdade, era só um castigo (frequentar mais aulas e fazer muitos trabalhos em casa) pra quem não teve nota normal e outra chance de ter a nota.


how to avoid null check

Question: I have a repository class like this:
interface TodosRepository : CrudRepository<Todo, Long> {
    fun findByUid(uid: String): Todo?
}

and a method that can mark this todo as done:
fun markAsDone(uid: String): ResponseEntity<String> {
        var todo = todosRepository.findByUid(uid)
        if(todo == null){
            return ResponseEntity("Not found", HttpStatus.NOT_FOUND)
        }
        todo.status = 1
        todosRepository.save(todo)
        return ResponseEntity.ok("Saved")
    }

IntelliJ ask me to replace the todo == null with an elvis operator:
fun markAsDone(uid: String): ResponseEntity<String> {
        var todo: Todo? = todosRepository.findByUid(uid) ?: return ResponseEntity("Not found", HttpStatus.NOT_FOUND)
        todo.status = 1
        todosRepository.save(todo)

but then, it asks me to use the null check when setting the status to 1 with todo?.status = 1
the thing is that I think it shouldn't ask me, because at that point, I'm pretty sure that todo is not null anymore.
Is there any workaround or I maybe misunderstood something on Kotlin?
Answer: I believe you could make the variable non-nullable to fix this. Probably also a val.
val todo: Todo = todosRepository.findByUid(uid) ?: return ResponseEntity("Not found", HttpStatus.NOT_FOUND)

Edit: omitting the return type should also work to infer the non-nullable Todo type.
The automatic change that IntelliJ suggested would've worked smoothly if you didn't have an explicit type; it seems like it chose to keep it unmodified instead of changing it to non-nullable, which somewhat defeats the purpose of the hint.
val todo = todosRepository.findByUid(uid) ?: return ResponseEntity("Not found", HttpStatus.NOT_FOUND)

Comment: That shouldn't  be a problem if you're using `?:` after it. In fact, you can try omitting the explicit type altogether, I think you'll get `Todo` inferred.
Comment: but `findByUid` returns null if it is not found
Comment: If it returns null, then the method will immediately return by the elvis operator.
Comment: well, for some reason, the message asking me to add a null check on `todo.status = 1` is missing now, and I didn't changed anything, it is like the last snippet now, without any warning...and yes, omit the return type also works

how to avoid null check


Open interval by summation

Question: $A = \{\sum_{k=1}^{\infty} \frac{a_k}{5^k}\}$ where $ a_k = [0,1,2,3,4]$ can the set $A$ contain an open interval? How?
Answer: Hint 1: Suppose the problem said $\sum_{k=1}^{\infty} \frac{a_k}{10^k},$ and the $a_k$ all belonged to $\{0,1,2,3,4,5,6,7,8,9\}.$ Could you solve it then?
Hint 2: For your problem, use base $5$ instead of base $10.$
Comment: I want elements of base 10, how would that be achieved?
Comment: So every open interval in base 10, could be made in base 5, and that interval would still be open. It is like the whole real number line is written in base 5 form. Am I right?
Comment: Real numbers are what they are. It doesn't matter how you write them--base 10, base 5, or something else. In the same way, there's no such thing as an open interval "in base 5" or "in base 10"; an open interval is just an open interval of real numbers, and you can write those real numbers in any convenient way. (The expression $\sum_{k=1}^{\infty} \frac{a_k}{10^k}$ is basically a decimal, and the expression $\sum_{k=1}^{\infty} \frac{a_k}{5^k}$ is the same thing but in base 5. So base 5 is convenient for thinking about your problem. The sums can be viewed as just ways of writing real numbers.)
Comment: But you can't write 9 in base 5. It would be 14 in base 5.  So when one looks at the real line, is it just a collection of things, which can be represented in different ways? I am sorry, all this time I have looked at real line in only base 10.
Comment: Yes, the same point on the number line that you label as $"\!9\!"$ in base $10$ is labeled as $"\!14\!"$ in base $9.$  But those are just names; they represent the same number (essentially in different codes).  It's like writing "nine" in English, "neuf" in French, or "nueve" in Spanish; they're just different ways of writing the same number. (In your example, though, you want to look at decimals, or the equivalent in base $5$ -- numbers between $0$ and $1.)$
Comment: Thanks a lot. One last thing, the question is equivalent to whether I can write all Real numbers between 0,1 if I were to use 0-9 digits and 10 in denominator. Correct?
Comment: Yes, exactly -- those are just decimals, and your problem is essentially the same thing in that you're writing all the numbers between 0 and 1 as a "decimal" in base 5, using the digits 0 through 4.
Answer: Hint: An element of $A$ is a number (written in base $5$). Which numbers are achieved?

Open interval by summation


Projection matrix onto a subspace parallel to a complementary subspace

Question: Given an $n \times k$ matrix $A$ and an $n \times (n-k)$ matrix $B$ such that $\text{span}(A) \oplus \text{span}(B) = \mathbb{R}^n$, how to get the projection matrix on $\text{span}(A)$ parallel to $\text{span}(B)$, in terms of $A$ and $B$?

Edit:
Below it is worked out that $P=\Big(\big(^−^ (^ )^{−1}^  \big)^{−1} ^ − (^ )^{−1}^  \big(^−^(^)^{−1}^
\big)^{-1}^ \Big)$.

Does it look right?
Can we possibly simplify it?
Is the horrendous look the reason that we rarely see it fleshed out in textbooks, etc.?

Edit 2:
I have verified numerically that the formula is correct. Also, with SVD $A = U_A \Sigma_A V_A^T$, $B = U_B \Sigma_B V_B^T$ and $U_{AB} = U_A^T U_B$,
it can be simplified that $P = U_A \Big(I - U_{AB}^T U_{AB} \Big)^{-1} U_A^T - U_A U_{AB} \Big(I - U_{AB}^T U_{AB} \Big)^{-1}U_B^T$.
But I have little intuition on how to understand the expression. If anyone can provide some, that'd be great.
Comment: Hint: In a suitable basis, the matrix has the block form $\small{\left[\begin{array}{c|c}I&0\\ \hline 0&0\end{array}\right]}$.
Comment: Let $C = [A|B]$ and let $c_j$ be the $j$-th column of $C$. Let $U$ be the matrix with $Uc_j = e_j$ and denote by $\bar U$ the $k\times n$ upper part of $U$. Then $P = A\bar U$. Indeed, $A\bar Ua_j = Ae_j = a_j$ and $A\bar Ub_i = A(0) = 0$.
Comment: Can we express $P$ in terms of $A$ and $B$? (Question edited.)
Comment: Yes. See my answer below.
Comment: There is an ordering error in the $U_{AB}$ terms in the first $(\ldots)^{-1}$ subexpression. The correct projector is
$$P = U_A \Big(I - U_{AB} U_{AB}^T \Big)^{-1} U_A^T \;-\; U_A U_{AB} \Big(I - U_{AB}^T U_{AB} \Big)^{-1}U_B^T$$
Answer: Let $U = [A|B]^{-1}$ and denote by $\bar U$ the $k\times n$ upper part of $U$. Then $P = A\bar U$. Indeed, since $\bar U[A|B] = \left[\begin{matrix}I_k&0\end{matrix}\right]$, we have $A\bar Ua_j = Ae_j = a_j$ and $A\bar Ub_i = A(0) = 0$.
Comment: Yes, it's correct because $(C^TC)^{-1}C^T = C^{-1}C^{-T}C^T = C^{-1}$.
Comment: Your expression might look ugly, but when it comes to numerically computing $P$, then it is probably better because the sizes of the matrices that have to be inverted might be much smaller. Can you please check my answer?
Comment: If we work out the expression, $P = A \Big( \big( A^T A - A^T B (B^T B)^{-1} B^T A \big)^{-1} A^T - (A^T A)^{-1} A^T B \big( B^T B - B^T A (A^T A)^{-1} A^T B \big)^{-1} B^T \Big)$. Does it look right? Can we possibly simplify it? Is the horrendous look the reason that we rarely see it fleshed out in textbooks, etc.?
Comment: @Lei Duuude, how did you get to this super ugly expression? I'm curious.
Comment: I assumed $[A \; B]^{-1} = \big([A \; B]^T [A \; B]\big)^{-1} [A \; B]^T =    \begin{bmatrix} A^T A \quad A^T B \\ B^T A \quad B^T B\end{bmatrix}^{-1} \begin{bmatrix} A^T \\ B^T \end{bmatrix}$. Then I used the [formula](https://en.wikipedia.org/wiki/Invertible_matrix#Blockwise_inversion) for the inverse of block matrix. Is my first assumption correct?


Response when publish a mqtt message, QOS 0

Question: Can I have an acknowledgement of delivery when I send a MQTT message with a QOS to 0?
How can I intercept answer with javascript, node.JS ?
Answer: You won't get any acknowledgement at the MQTT protocol level from any QOS. The protocol has no concept of a end to end acknowledgement, at QOS1 or QOS2 the handshake is only between the publisher and the broker and then between the broker and the subscriber.
If you want acknowledgement then you need to implement that yourself by publishing a response message that the original publisher can see.
Answer: Instead of that you can just subscribe to your own topic and check if you've recieved the message!
Comment: That does not prove the message made it to anybody else but the client that published it.
Comment: It is just to acknowledge that the message has been recieved by the broker and published!
Comment: @AfrozeKhan not true: a simple proof is that even if the intended receiver is not online at all, your suggestion will give the impression to the sender that the message was received by the received.
Comment: @axd What i intended was. He'll know that his message got published to the broker. Where as if i'm not wrong, the broker which sends PUBACK means that the message intended was published successfully..
Comment: ok about the broker part .

but not sure about being received by the intended receiver. it's not yet clear to me what happens beyond the broker, because QoS is defined at subscription time by a receiver, am not sure if there is a way for the receiver to ACK a good reception to a sender (via broker).
Comment: It is as the name implies recieves and gives away to one who needs. You'll be subscribed only if you're connected. The protocol is mainly intended for IoT so that anybody who needs the data can recieve and take corresponding actions. It's the most light weight protocol comes with its own traits. But the ACK recieved itself is enough to know that message has been delivered. However you need to stay connected and subscribed to that topic if you need to recieve that data. https://www.hivemq.com/blog/mqtt-essentials-part-4-mqtt-publish-subscribe-unsubscribe


In what situations is this true: $P(A|B) = 1 - P(A|B^c)$?

Question: I am working on some software that uses Bayes' rule to find $P(B|A)$
It asks the user to define $P(A|B)$ but it says that $P(A|B^c)$ is optional, if the user chooses not to define it then it sets $P(A|B^c) = 1 - P(A|B)$.
This seems slightly odd to me. Is there a group of cases where $P(A|B^c) = 1 - P(A|B)$ holds true.
Related but does not answer: Does $P(A\mid B)$ determine $P(A\mid \bar{B})$?
Related: Does $P(A|B)+P(A|\bar{B}) \neq 1?$
Comment: To me, the more *natural* choice of a default expression for $P(A\mid B^c)$ would be $P(A\mid B^c)=P(A\mid B)$ (i.e., the default assumption is that $A,B$ are independent). Of course, in a context that is explicitly "aware" of Bayes rule, it would be wiser to make $P(A\mid B^c)$ a mandatory input.
Comment: The question means $P(A|B)=P(A^c|B^c)$, so for example is the probability of owning a car knowing that you live in New York equal to the probability of not owning a car knowing that you don't live in New York? A very unlikely coincidence!
Comment: @FirstNameLastName It can be true by chance. Take a group of 10 men and 5 women, of which 2 men and 4 women are married. Take a random person in the group and let A = the person is married and B = the person is a woman. Of course the result becomes false if 3 men are married instead of 2.
Comment: Harvs : I believe @Gribouillis gave answer to your question in title: it can somewhat unlikely happen. The *related* questions are perhaps not to the point.
Comment: If A is empty the statement says $1=0.$
Comment: $P(A|B^c) = 1 - P(A|B)$ holds in following two cases: (1) $A=B^c$ and (2) $A=B$. It would be cool if these were only cases.
Comment: @Gribouillis : right, I was also suspecting some special cases. Thanks for example
Answer: See Does $P(A|B)+P(A|\bar{B}) \neq 1?$
as said in this answer by @drhab
$P(A|A)+P(A|A¯)=1+0=1$
So if $P(A)=P(B)$
Comment: I agree this is a duplicate ... only ... I was confused by two notations $X¯$ and $X^c$ to mean the same: $not X$


Fitting chords to the opening phrase of the Toccata (and Fugue) in D Minor BWV 565?

Question: What are some of the acceptable ways to harmonize the first one and a half bars of BWV 565? In particular, what are some of the chords that would fit on the the opening A? Neither i nor V seems to fit the movement of the opening gesture.
Comment: @user45266 The philosophy of Stack Exchange is to answer questions rather than provide a discussion forum.
Comment: @PiedPiper Right, which is why I ask that OP rewrite the question such that the relevant information to be provided would answer the question. I'm just saying that this question has depth to it, it's just not being asked in the right way. "Discussion" may have been a poor choice of wording.
Comment: @Tim This is relatively common for music of this time; check out the notion of "Dorian key signatures."
Comment: @Tim, the Dorian key signature for BWV 565 is discussed in the Wikipedia entry. See the second paragraph of [this section](https://en.wikipedia.org/wiki/Toccata_and_Fugue_in_D_minor,_BWV_565#History).
Comment: I hear this as all Dm with brief dominants on the C#s, but I'm voting to close as opinion based because there is no 'correct' answer.
Comment: @PiedPiper Is there something out of the ordinary about this post? We routinely field posts about harmonization or interpreting harmony that are inherently opinion-based.
Comment: @Aaron The fact that other opinion-based questions weren't closed doesn't mean that new ones can't. You're welcome to vote to keep it open if you wish. The majority decides.
Comment: There's interesting discussion to be had on why this part of the music can have multiple harmonic interpretations, and what the effect of such ambiguity is. I think maybe OP could rewrite/reword it so that it's less *"what's the answer"* and more *"what is achieved by writing the music in this way"*. At the moment, personally I'm leaning away from VTC for that reason.
Comment: Interesting that it's supposed to be in key Dm, but there's nothing in the key sig. stating that.
Comment: @Richard - I considered Dorian - as in key sig. for C major, but the C# foiled that.
Answer: This passage would be harmonized primarily with alternating V and i as shown below. However, while V is the "correct" harmonization of the A octaves, it ruins the effect. Part of what makes this passage so effective is the harmonic ambiguity of the A octave.
Answer: If you want a harmonic analysis: there's an element of dominant on the first main note, tonic on the second.  That's repeated twice more.  Then there's a definite C♯dim7 (acting as a dominant) to a Dsus4 then D major, all over a tonic pedal.
But no-one in their right mind would add chords to this.  It's all about the gesture. Complete in itself.
Answer: There are many ways to harmonize these motifs:
As this is always named the toccata in dm I tend to hear a minor chord on the first note. But I also could imagine the dominant: both will work!
a) i - V - i (first half bar)
or
b) V - V7 - i
but you could also hear a) and b) combined.
In a slower tempo you could even hear a more differentiated harmonization by underlaying tonic and dominant chords to the descending scale tones.
The pedal note may be the key: the dominant (VII°7) is set over the tonic.


Azure function v4 unit tests

Question: How can i test azure function this is an example generated function:
public static class Test
{
    [Function("Test")]
    public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
        FunctionContext executionContext)
    {
        var logger = executionContext.GetLogger("BLEbLE");
        logger.LogInformation("C# HTTP trigger function processed a request.");

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

        response.WriteString("Welcome to Azure Functions!");

        return response;
    }
}

i have generated method and i tried testing it with xunit but i don't how to mock HttpRequestData , FunctionContext and HttpResponseData, these are abstract classes so should i create custom classes for them and inherit for this 3 or maybe there is other way to test it?
Answer: Tried with the below code snippet:
//Arrange
var context = Substitute.For<FunctionContext>();
var request = Substitute.For<HttpRequestData>(context);
var response = Substitute.For<HttpResponseData>(context);

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(Options.Create(new WorkerOptions{Serializer = new JsonObjectSerializer()}));

var serviceProvider = serviceCollection.BuildServiceProvider();
context.InstanceServices.ReturnsForAnyArgs(serviceProvider);

request.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Body.ReturnsForAnyArgs(new MemoryStream());
request.CreateResponse().ReturnsForAnyArgs(response);

var function = new Function();

//Act
var result = await function.Run(request);
result.Body.Position = 0;
var content = await JsonSerializer.DeserializeAsync<ErrorResponse>(result.Body);

//Assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("Error", content?.Message);

There is a documentation on migrating the Azure Functions in-process to Isolated worker process but no information on implementing the Tests like Unit, Integration Tests.
Microsoft Azure Team has taken this implementation of complete test framework for the isolated-workers process as a priority item #281 and given the above code snippet for the temporary workaround.
Comment: Wouldn't it be great if all those types like `HttpRquestData` were available and used as interfaces, to make classes or methods testable from the outset? It's not rocket-science but I guess we have to wait until it catches on at Microsoft....
Comment: Sadly, this does not work for me on functions isolated worker 1.17.2. I completely agree with @Manfred, MS code does not follow patterns to make their frameworks testable and I don't know why. It causes an enormous amount of productivity loss in our industry as their tools are so widespread. Azure/EF and other frameworks have always been difficult.
Answer: Alternatively you can create a Fake
from https://github.com/simon-k/fake-http-request-data/blob/main/FakeHttpRequestData/FakeHttpRequestData.cs
public class FakeHttpRequestData
    : HttpRequestData
{
    public FakeHttpRequestData(
        FunctionContext functionContext,
        Stream? body = null,
        string method = "GET",
        string? url = null)
        : base(functionContext)
    {
        Body = body ?? new MemoryStream();
        Headers = new HttpHeadersCollection();
        Cookies = new List<IHttpCookie>();
        Url = new Uri(url ?? "https://localhost");
        Identities = new List<ClaimsIdentity>();
        Method = method;
    }

    public override Stream Body { get; }

    public override HttpHeadersCollection Headers { get; }

    public override IReadOnlyCollection<IHttpCookie> Cookies { get; }

    public override Uri Url { get; }

    public override IEnumerable<ClaimsIdentity> Identities { get; }

    public override string Method { get; }

    public override HttpResponseData CreateResponse()
    {
        return new FakeHttpResponseData(FunctionContext, HttpStatusCode.OK);
    }
}

Azure function v4 unit tests


Nagios Wrapper Script that Checks board

Question: I am in need of a kind of automation script or program run in the Linux environment that can check my Nagios board and can display results or store it's results of the Host, Service, Description, etc in a text file. Can anyone provide me with what kind of program works well with this?
Instead of blatantly downvoting my question, can you suggest what may need to be changed in order to better word my question?!
Comment: Maybe nagstamon is something that would fit you needs?
Comment: Sorry, what are you talking about...  Product recommendations are off topic, but your question doesn't really make sense.  It isn't cleare what you want.
Comment: I am looking to see if there is a wrapper script I can run on Linux that can actively check my nagios board and display it's results
Comment: Basically I am looking to view the same results I would see on the board in a text format in Linux
Comment: cat `/var/cache/nagios3/status.dat`.
Comment: This might work, I just gotta figure out where nagios is saved on our server
Answer: There's an entire category of so-called "front end" add-ons in Nagios Exchange, including some CLI interfaces.
You also might want to look at the APIs category if you need something more granular or specific than a CLI frontend can provide.
Answer: nagiosstats might do the trick.

The utility called nagiostats is included in the Nagios distribution. It is compiled and installed along with the main Nagios daemon. The nagiostats utility allows you to obtain various information about a running Nagios process that can be very helpful in tuning performance.

http://nagios.sourceforge.net/docs/3_0/nagiostats.html
Comment: nagiosstats will give you internal stats about the performance of Nagios, which I don't think is what is really being asked here.

Nagios Wrapper Script that Checks board


What hash function should be used for passwords?

Question:
Possible Duplicate:
What's the recommended hashing algorithm to use for stored passwords?

Hello, I've recently been told that common hash functions such as SHA256 are insecure for use as a password hashing function because they are "designed to be fast"(incidentally I asked earlier for faster hashing functions over at programmers.se). So my question, what should be used for websites or other general applications?
Also, secondary question: Is SHA256 really not a good choice for hashing passwords? I kind of don't believe it, but I've heard crazier things be true.
(note: assume all other proper actions are being taken such as unique salts)
Comment: Duplicate? http://stackoverflow.com/questions/2549988/whats-the-recommended-hashing-algorithm-to-use-for-stored-passwords
Answer: You should use bcrypt.
Comment: The link provided explains why:  you define a "work factor", which will determine how fast/slow it is, and how much work a brute force attacker would have to do.
Comment: My question then is why? How much faster can you crack SHA256 than bcrypt? Especially if I do multiple iterations of SHA256?
Comment: @Earlz bcrypt lets you use a work factor. If it (argument's sake) SHA256 runs 30 times a second, and bcrypt runs once, then SHA256 will be 30 times quicker to crack (in theory, at least :D )
Answer: At the time of writing SHA256 is adequate for password protection, though it may not be in a year or so.
I'd maybe use SHA512 as I'm not too well traversed in what is really secure at the moment, and I'm not sure if anything can be really secure, with the huge increases of computing power in CPU's and GPU's.
Answer: Mike Howard's answer on the question Mark linked to is the correct best practice.
Simply using a good hash is insufficient because:

it does not protect you from rainbow table attacks.  The same password will hash to the same result, every time.  An attacker can compromise on the time vs. space tradeoff, pre-compute the most popular passwords and simply look up the answer.  To defeat, you need to add a salt.  (Mike suggests user id)
as you suggest, hashing algorithms are designed to be fast.  This is sometimes desired, (such as getting the hash of a 50MB file) but in the case of passwords it not.  Use a password-based key derivation function instead.  It will significantly slow down an attacker, but not impact your own speed.


YUM error. Is this a cert error

Question: Nov 13 13:38:57 host abrt: detected unhandled Python exception in '/usr/bin/yum'
Nov 13 13:38:57 host abrtd: New client connected
Nov 13 13:38:57 host abrt-server[3508]: Saved Python crash dump of pid 3151 to /var/spool/abrt/pyhook-2012-11-13-13:38:57-3151
Nov 13 13:38:57 host abrtd: Directory 'pyhook-2012-11-13-13:38:57-3151' creation detected
Nov 13 13:38:57 host abrtd: Can't load public GPG key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-beta
Nov 13 13:38:57 host abrtd: Can't load public GPG key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-legacy-former
Nov 13 13:38:57 host abrtd: Can't load public GPG key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-legacy-release
Nov 13 13:38:57 host abrtd: Can't load public GPG key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-legacy-rhx
Nov 13 13:38:57 host abrtd: Can't load public GPG key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
Nov 13 13:38:57 host abrtd: Package 'yum' isn't signed with proper key
Nov 13 13:38:57 host abrtd: 'post-create' on '/var/spool/abrt/pyhook-2012-11-13-13:38:57-3151' exited with 1
Nov 13 13:38:57 host abrtd: Corrupted or bad directory /var/spool/abrt/pyhook-2012-11-13-13:38:57-3151, deleting

There is also nothing in the crash dump file. Ideas?
yum update
Loaded plugins: fastestmirror, rhnplugin, security
An error has occurred:
Internal Server Error
See /var/log/up2date for more information

Is yum broken
Comment: It would be helpful to know what distro and version you are running. Do the GPG keys listed in the error messages exist on your system?
Answer: Is this (or was it) RHEL or CentOS (which you used for tag)? I hope...
RHEL:
What does rpm -qa | grep redhat-release show? rpm -V redhat-release-server-6Server (use the packge from 1st step)? If it's not installed or is corrupted, you may want to obtain the package from a secure source and reinstall it.
In case it is
CentOS:
I do not think CentOS uses redhat keys or RHN - were you trying to migrate from RHEL to CentOS or vice-versa? Or you just followed CentOS' deployment guide?\
In that case, you should disable the RHN and install centos repos instead - follow CentOS' migration guide.
You should be able to get corresponding centos-release-... package from http://mirror.centos.org/centos/YOUR_VERSION/os/x86_64/Packages/.

YUM error. Is this a cert error


testing a service that uses a third party library

Question: I have a Service that uses a library called client.
The Client class that I load is stored in the private property client of Service.
For my spec,  I can't inject mockClient in my Service like this
service = new Service(mockClient)

but I can't either do
service = new Service()
service.client = mockClient

since client is private.
What is the right practice to test a service that uses a third party library that is not injected and that you want to mock ?
Edit:
my service uses a third party lib like this
import { Client } from 'someLib';

Injectable()
export class Service {
  private client: Client;

  constructor() {
    this.client = new Client();
  }

Comment: You could refactor so that it *is* injected, then the testing will be easier.
Comment: Could you give a less abstract example? Why can't you use DI to provide a mock?
Comment: I edited my post with the service class. I can't use DI because the third party lib isn't injected.
Answer: The proper practice here is to refactor your code so that your third party library is injected.  First, you should wrap the library in a service or a factory. As a bonus, you may want to only expose the parts of the third party library that you are using. You can validate parameters in your service and transform them so that the call signatures make sense for your app.  So, it may look something like this:
app.service('theirLibraryFactory', () => {
 return {
   createClientWrapper: () => {
      let client = new Client();
      return {
        op1: (args) => client.doOp1(args),
        op2: (args) => client.doOp2(args)
        ...
      }
 };
}

With this client wrapper, you can then inject it into your classes, and then mock it.
ps- I know that angualarjs provides factories as a base type, but I prefer to use services since they do everything that factories do, but more explicitly. YMMV.


accessing iterator inside .getResultList() query

Question: situation is simple.
I have very slow DB so I decided to make progressbar of current select query.
Output is list of all rows from table.
<code>transaction.begin();
Query q = em.createQuery('some sql string');
list = q.getResultList();
transaction.commit();
</code>
I want to increment progressbar after each row gets inserted to list.
Is there any way?
Thank you
Comment: Where and how you want to show progress bar and to whom?
Comment: it doesnt matter where and how . I just need a single int output from query of current possition . Right now I cant access count (or how many selects passed), I have to wait while hibernate process every single select and after then I get a resultset. I just need to count steps somehow.
Comment: Something is wrong If Hibernate generates many SQL statements for one JPA query. You should chekc if you can work with `@BatchSize`
Comment: I have made some test with @BatchSize, its working way better now. Thx for advice.
Answer: I have done some research and I it should be done by org.hibernate.event.* listeners.
Time to study more


ASP.NET Background image

Question: I am using VS2005 C#.
I have a .aspx login page and I would like to implement a background image to it. Below is my current page screenshot:

Below is my background code:

<asp:login id="Login1" runat="server" font-size="Large" BackColor="#F7F6F3" BorderColor="#E6E2D8" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#333333" DestinationPageUrl="~/Common/Default.aspx" DisplayRememberMe="False" FailureText="Login failed" RememberMeSet="False" Height="224px" Width="384px">
    <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em" ForeColor="White" />
    <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
   <TextBoxStyle Font-Size="0.8em" />
    <LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px"
    Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
</asp:login>

I tried to put the
 tag outside, but the background image just seems stuck with the login control's width height.
May I know how can I extend the image to cover the whole background?
Thank you
Answer: 1) Use a CSS stylesheet - add <link rel="stylesheet" type="text/css" href="styles.css" /> to include it.
2) Apply the background to the body:
body {
    background-image:url('images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

See:
http://www.w3schools.com/css/css_howto.asp
http://www.w3schools.com/cssref/pr_background-position.asp
Answer: If you want to set image as background for whole page, use this:
body
{
    background-image: url('Image URL');
}

Answer: write code in body tag like this

Answer: Use this Code in code behind
Div_Card.Style["background-image"] = Page.ResolveUrl(Session["Img_Path"].ToString());

Answer: resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...
hard-size your DIV relative to your image
position your asp:login control where needed...
Answer: Just a heads up, while some of the answers posted here are correct (in a sense) one thing that you may need to do is go back to the root folder to delve down into the folder holding the image you want to set as the background.
In other words, this code is correct in accomplishing your goal:
body {
    background-image:url('images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

But you may also need to add a little more to the code, like this:
body {
    background-image:url('../images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

The difference, as you can see, is that you may need to add "../" in front of the "images/background.png" call.
This same rule also applies in HTML5 web pages. So if you are trying the first sample code listed here and you are still not getting the background image, try adding the "../" in front of "images".
Hope this helps .
Answer: You can use this if you want to assign a background image on the backend:
divContent.Attributes.Add("style"," background-image:
url('images/icon_stock.gif');");

Answer: body {
    background-image: url('../images/background.jpg');
    background-repeat: no-repeat;
    background-size: cover; /* will auto resize to fill the screen */
}

Comment: When adding an answer to an eight year old question with seven existing answers it is very important to point out what new aspect of the question your answer addresses. Code only answers can almost always be improved by adding some explanation of how and why they work. In this case be sure to point out your use of `cover` because otherwise this would be a duplicate answer.
Comment: /* will auto resize to fill the screen */ <-- that's why I added this line.

ASP.NET Background image


Finding Type I error

Question: Suppose the sample size $n=16$ is drawn from a normal distribution with mean $\mu$ and standard deviation $\sigma = 4$. Consider the testing hypothesis $H_o:\mu = 0$ vs $H_a:\mu \ne 0$. Let the rejection region be $|\bar{x}| > 2$, where $|\bar{x}|$ is the sample mean. Find the type I error.
$$P(\text{Type I error}) = P(|\bar{x}| > 2 \mid \mu = 0)$$
Since we know that the sample follows a normal distribution, then we know that $\bar{x}$ also follows a normal distribution. When $\mu = 0$, then the variance is $\frac{\sigma^2}{n} = 1$.
$$P(|\bar{x}| > 2 \mid \mu = 0)\\
=P(\bar{x} < -2 \mid \mu = 0) + P(\bar{x} > 2 \mid \mu = 0)\\
=2P(\bar{x} > 2 \mid \mu = 0)$$
At this point, I'm not sure how to get the probability of $P(\bar{x} > 2 \mid \mu = 0)$
Answer: Under $H_0$, $\bar{x}$ follows $N(0,\frac{\sigma^2}{n})=N(0,1)$. So $$P(\bar{x}>2)=1-\Phi(2)$$ where $\Phi$ is the cdf of a standard normal. There is no explicit way to compute $\Phi(2)$, so you have to look it up on a table.
Answer: Arithmetic mean of sample size follows Normal Distribution with $\mu{}, \sigma{}^2/n$.
Calculate the probability of $\bar{x} > 2$ given that $X \sim Normal(\mu = \mu, \sigma^2 = \sigma^2/n)$ (by standardizing it to standard normal).
Comment: I tried standardizing it to standard normal by doing $\frac{\bar{x} - \mu}{\sigma / \sqrt{n}} = \frac{0-2}{1} = -2$. Since it is normalized, I should be able to look at a normal distribution table for the z score of 2.0. I found 0.0228. Is this what I'm supposed to do?
Comment: yes that is correct, you are looking for $P[Z > 2]$, and if it is $0.0228$, then yes

Finding Type I error


Alguém sabe como inserir nomes em ordem alfabética em um vetor c++?

Question: Fiz esse código mas não funciona direito, insere em ordem alfabética ao contrário.
void inserirNomeNaLista(vector<string> &lista)
{
    vector<string>::iterator itr;
    string nome;
    cout << "Digite o nome para ser inserido na lista: ";
    cin >> nome;

    if (lista.size() == 0)
    {
        lista.push_back(nome);
    }
    else
    {
        for (itr = lista.begin(); itr != lista.end(); itr++)
        {
            if (*itr > nome)
            {
                lista.insert(itr, nome);
            }
            break;
        }
    }
}

Comment: Você tem certeza que ele está inserindo sempre ao contrário? O seu `break` está fora do bloco do `if (*itr > nome)` (ao invés de estar dentro dele), o que faz com que ele insira apenas se a nova string for menor ou igual à string do primeiro elemento do vetor. Por causa do `break`, o laço sempre se encerra após a primeira interação.
Answer: Se você planeja que sua lista seja ordenada, a forma mais simples de fazer isso é usar diretamente um std::set, que é ordenado e não permite duplicatas. O código fica assim:
std::set<std::string> nomes;
nomes.insert("Pedro");
nomes.insert("Amanda");
nomes.insert("Maria");

for (auto& nome : nomes)
    std::cout << nome << std::endl; // Amanda, Maria, Pedro

(coliru)
No entanto, se você quer se manter usando o std::vector, pode procurar pela posição se inserção usando o std::lower_bound. Mas note que essa função só funciona corretamente em listas já ordenadas (busca binária). Assim:
void sortedInsert(std::vector<std::string>& vec, std::string value) {
    auto it = std::lower_bound(vec.begin(), vec.end(), value);
    vec.insert(it, std::move(value));
}

std::vector<std::string> nomes;
sortedInsert(nomes, "Pedro");
sortedInsert(nomes, "Amanda");
sortedInsert(nomes, "Maria");

for (auto& nome : nomes)
    std::cout << nome << std::endl; // Amanda, Maria, Pedro

(coliru)
Com um pouco de templates a mais: (coliru)
Answer: Sugiro você dar uma estudada nos algoritmos padrão da STL. Para resolver este exato problema seu já existe o lower_bound
#include <algorithm>

void inserirNomeNaLista(std::vector<string> &lista)
{
  std::string nome;
  std::cout << "Digite o nome para ser inserido na lista: ";
  std::cin >> nome;

  typedef std::vector<std::string>::iterator VecIter;
  VecIter itr = std::lower_bound(lista.begin(), lista.end(), nome);
  lista.insert(itr, nome);
}

Ele pesquisa em um sequência (par de iteradores) o ponto onde se deve inserir um item para que a sequência fique em ordem crescente. Ele é eficiente, pois executa busca binária, mas só funciona se a sequência estiver sempre ordenada. Mas se você só usar ele para inserir elementos em um vector não há problema, pois neste caso as inserções sempre serão em ordem.

Agora se isto for um exercício, e você não puder utilizar os algoritmos padrão, acredito que seu erro seja a posição do break, como já explicado no comentário do Luiz Vieira.
Answer: Amigo, a STL já disponibiliza o método sort() pra você. Ele analisa lexicograficamente as strings e as ordena. Aí vai um exemplo.
#include <algorithm> //Para o sort()
#include <iostream> //Para o cout
#include <vector>  //Para o vector<>()
#include <string> //Para a string

int main() {
    std::vector<std::string> v;
    v.push_back("bac"); v.push_back("abc"); v.push_back("cab"); v.push_back("cba");
    std::sort(v.begin(),v.end());
    for(int i = 0; i < v.size(); i++) std::cout << v[i] << std::endl;
}

Comment: Vale notar que para vectors essa resposta é a mais eficiente se for inserir todas as string de uma única vez (sendo que a lista não estará ordenada entre as inserções). Essa é `O(nlogn)` enquanto que a outra (usando `std::lower_bound`) é `O(n²)` em worse case. No caso de usar o `std::set`, a complexidade será `O(nlogn)`, mas a lista estará sempre ordenada (melhor).
Comment: Perfeito. Obviamente é, de fato, inviável ordenar os vetores a cada inserção. Como você disse, é mais proveitoso ordenar no final das inserções ou usar um std::set.


How to interpret structure without definition?

Question: Today I started working on FUSE opensource code, there i found few lines like this:
struct fuse_session;
struct fuse_chan;

I don't know how to interpret it , as far as i knew 'struct' is followed by structure name and then the name of variable. Where as in this case there is only one named entity followed by struct ,so this fuse session is structure variable or structure name itself.It may be some really basic thing but i am not able to find it anywhere.
Answer: This is usually used for one of the following:

You want to let the user of some module to know that this struct exist, but don't want to expose it's content. For example:
in api.h:
struct bar;

void GetStruct(struct bar *);
void SetActive(struct bar *, char);

in your internal file:
struct bar {
    char is_active;
};

void GetStruct(struct bar * st) {
    st = malloc(sizeof(struct bar));
}

void SetActive(struct bar * st, char active) {
    if (st != NULL)
        st->is_active = active;
}

This way you encapsulate the implementation and may change the struct later if needed without any impact on the using module.
You want to use a structure (pointer) before declaring it. For example:
struct bar;
typedef int (*FooFuncType)(struct bar *);
struct bar {
    FooFuncType a_func;
};

One important note:
If you only have the struct declaration, as in your question, you cannot refer to the struct directly, nor you may use the sizeof operator, only declare a pointer to the structure.
Comment: @user1115935, this is also called forward declaration.
Comment: Ok, but how can I know where this struct is defined? Which library? It is just magically there.
Answer: Those are incomplete types or opaque types, and they are useful when the library interface only works with pointers to those types.  You don't need to fill in all the details of what is in the structures so no code outside the library can ever access the data in the structure (legitimately).  The code inside the library has a private header that supplies the details of what is in the structures, so the library can indeed work with the contents, but that is a detail hidden from the consumers of the library.
Incomplete types provide much better type safety than another alternative that is sometimes used, namely void pointers.  It is too easy to get confused when there are multiple different types all represented by 'void *'.  With incomplete types, you can properly distinguish between the different types, but still not reveal the details of how they are implemented.
Comment: DBus implementation in Gnome as an example: "The #GDBusConnection structure contains only private data and should only be accessed using the provided API." https://github.com/GNOME/glib/blob/master/gio/gdbusconnection.c
Answer: You should get an introduction to forward declaration in C. Please try this link.
Answer: I found such things in some library's API provided header file. Some library doesn't want to expose the member details of some structure used in library but they intend that the application may use those structures as pointers, in that case they do so as shown...
Answer: Forward Declaration this helps compiler to resolve structure references from different parts of a program.


Atribuir envio de email automático a um botão usando nodemailer

Question: Possuo um site e gostaria que quando o usuário enviasse uma mensagem através do contato, o site me enviasse essa mensagem via email... já configurei o envio e está funcionando usando o NODEMAILER
    const nodemailer = require ('nodemailer');

var assunto = 'teste';
var nome = 'teste2';
var email = 'firstname.lastname@example.com';
var msg = 'teste 2 teste 2 teste 2';

let transporter = nodemailer.createTransport({
    host: "mail.example.com",
    port: 465,
    secure: true,
    auth: {
        user:'firstname.lastname@example.com',
        pass:'****minhasenhasupersegura****'
    }
});

transporter.sendMail({
    from: '<email@example.com>',
    to: 'firstname.lastname@example.com',
    subject: assunto,
    text: 'nome: ' + nome + ' Email: ' + email + ' -- mensagem: ' +msg,

});

o form de envio onde tenho o botão de envio do formulário está assim:
<form id='contatos'>

Envie sua mensagem

      Seu nome
      <input type="text" class="form-control" id="nomeCont" placeholder="Digite aqui seu nome">

      Qual o motivo do contato ?
      <input type="text" class="form-control" id="motivoCont" placeholder="Digite aqui o motivo do seu contato">

      Seu Email
      <input type="text" class="form-control" id="emailCont" placeholder="Digite aqui seu Email">

      Digite sua mensagem
      <textarea class="form-control" id="textoCont" rows="4"></textarea>

    <button id='enviarCont' onclick="envia()">
      Enviar
    </button>
  </form>

imaginei fazer algo do tipo :
$('#enviarCont').click(function(){

})
e colar dentro disso o código q está enviando o Email... porém não funciona...
Comment: Sim, não funciona, o nodemailer deve ser configurado no backend(nodejs). Você deve expor uma rota publica que chama o envio do e-mail. (via post) para o seu backend. Assim em sua ação de clique basta chamar o endpoint com os dados do form.
Comment: MAs quando eu chamo no prompt o comando  node index.js (nome do arquivo q ta o envio) ele envia o email normalmente...
Comment: Não entendi oq vc quis dizer, será q pode me mostrar ?? estou travada nisso e parece ser algo tão simples
Answer: Para criar uma rota em seu backend para tratar envios de email, você vai precisar criar um endpoint para manipular o envio do seu email.
Para isso vamos criar os seguintes passos:

Criar um endpoint que faz o envio via o nodemailer
Chamar o endpoint em nosso frontend para o email ser enviado

Para criar o nosso servidor, vamos precisar instalar as libs express para montar o servidor que vai receber as requisições e o cors para liberar o acessso da nossa aplicação para o nosso frontend. Além do node-mailer
Para criar o endpoint no backend temos:
app.js
const express = require('express');
const cors = require('cors');
const app = express();
cors({ credentials: true, origin: true });
app.use(express.json());
app.use(cors());

app.use(require('./server/index'));
module.exports = app;

server/index.js
const nodemailer = require('nodemailer');
const router = require('express').Router();

const transporter = nodemailer.createTransport({
    host: "mail.example.com",
    port: 465,
    secure: true,
    auth: {
        user: 'email@example.com',
        pass: '****minhasenhasupersegura****'
    }
});

router.post('/enviaremail', (req, res) => {
    const mailOptions = {
        from: 'firstname.lastname@example.com',
        to: req.body.email,
        subject: req.body.assunto,
        text: `Mensagem de: ${req.body.nome}, ${req.body.mensagem}`
    }
    transporter.sendMail(mailOptions).then((trans) => {
        res.status(200).json(trans);
    }).catch((error) => {
        res.status(500).json(error);
    })
});
module.exports = router;

bin/www
#!/usr/bin/env node
const app = require('../app');
try {
    app.listen(process.env.PORT);
    console.log(`Microsservice listening at http://localhost:${process.env.PORT}`);
} catch (err) {
    throw err;
}

Após desenvolver essa aplicação no backend, basta apontar o frontend para esta rota e fazer a chamada via ajax. Este código ficaria na ação de clique do seu botão. Os dados que estou deixando hardcoded no request, devem vim do seu formulário html.
const axios = require('axios');
axios.post('http://localhost:3000/enviaremail', {
    nome: 'aaaa',
    email: 'email@example.com',
    assunto: 'assunto principal',
    mensagem: 'minha mensagem',
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Existem algumas configurações que você deve fazer afim de ter segurança, configure o cors com algum valor que faça sentido para o seu ambiente. E para os valores que estão hardcoded em meu backend, você deveria utilizar variáveis de ambiente.
Outra funcionalidade que pode implementar é validar os valores do form (no frontend) antes de fazer o submit e validar no backend (antes de fazer o envio). Sim é necessário validar no frontend e backend.


For a mixed model, does the temporal correlation should be checked for each site (random effect)?

Question: When a model fitted in a dataset with multiple time series from different sites, does the temporal correlation should check for each site? And if some sites show auto-correlation but some don't, what's that mean and how to deal with? Thanks.
Here is details. I fitted a model like:
m1 <- gam(Abundance ~ s(Temperature) + s(Temperature, by=Site, m=1) +
            s(Site, k=11, bs="re") + s(Year),
          method="REML", family=binomial(link="logit"),
          weights=Trap, data=c2)

I checked the auto-correlation plot for residuals for each site. Most of sites don't show residual problems, but some sites do. I added a residual auto-correlation structure, for example:
m2 <- gamm(Abundance ~ s(Temperature) + s(Temperature, by=Site, m=1) +
             s(Site, k=11, bs="re") + s(Year),
           correlation=corAR1(form = ~ Year|Site),
           method="REML", family = binomial(link="logit"),
           weights = Trap, data=c2)

or
m3 <- gamm(Abundance ~ s(Temperature) + s(Temperature, by=Site, m=1) +
             s(Site, k=11, bs="re"),
           correlation = corAR1(form = ~ Year|Site),
           method="REML", family = binomial(link="logit"),
           weights = Trap, data=c2)

Always have a message = iteration limit reached without convergence (10)
Any advices would be appreciate.
Answer: If there is some structure in the model residuals, even if it is at just one or two of the Sites, will lead to the test statistics being anti-conservative (p-values will be somewhat smaller than they should be, confidence intervals somewhat narrower) because they assume the observations are conditionally independent.
It doesn't matter that some Sites show no residual autocorrelation but you're estimating an AR(1) parameter for them as the parameters for those sites will most likely be very small. The only price you pay is in estimating these potentially redundant parameters but if we're being honest, the autocorrelation in those Sites is probably not exactly zero so the model is a reasonable reflection of what the data is telling you.
You might look to see if the basis size for s(Year) is sufficiently large; increase k for this smooth and refit and see if that can model the autocorrelation so you don't need the AR(1). You might also change s(Year) to s(Year, by = Site) to see if you have different trends per Site which might mean you aren't modelling all the trend in some Sites which may be showing up as residual autocorrelation.
Comment: Much appreciate @Gavin. I have tried some options as you suggested and posted the results as an answer. I want to know is the GLMM model with a random intercept and random slope I fitted in a right way (especially for the issue of correlation between the intercept and slope)? And given my results, if I could ignore the non-linear pattern of Year and use GLMM rather than GAMM. Thanks.
Answer: I tried both increase k for s(Year)(the k value is enough) and s(Year,by=Site),there still have residual autocorrelation:
E1=resid(m1)

acf(E1)

I delete the term s(Temperature, by=Site, m=1)and add AR1 as:
m2 <- gamm(Abundance ~ s(Temperature) + s(Site, k=11, bs="re") + s(Year), correlation=corAR1(form = ~ Year|Site), method="REML", family = binomial(link="logit"),weights = Trap, data=c2)

It seems works well. But given the AIC, allowing a random effect of Temperature by site fits better than only a global function. However, there always have convergence problem when fitted with a correlation structure. Then I tried a GLMM:
m4<-glmmPQL(Abundance~Tem_avg+Tem_dev+Year,random = ~1 + Tem_dev | Site,correlation = corAR1(form = ~ Year|Site),family = binomial(link="logit"),weights = Trap, data=c2)

It seems works well. I also plot the residual against all continuous covariates in the model:

It seems the resulting panels do not indicate obvious non-linear patterns (maybe a little non-linear pattern for Year,I'm not sure whether I could neglect it or not).


true is not being printed out on first run. instead false is

Question: Why does this return false, in the first run; when it's meant to return true.
I have a state with a name   const [dataFromServer] = useState({name:["john"]})
this codes checks to see if the above name is in my file, if it does it should update the state to true.
const [uploadStatus,UploadStateSetState] = useState("false")

    const  onSubmittt =   (e) => {
         e.preventDefault()
        for (let i = 0; i < selectedFile.length; i++) {
          if (dataFromServer.name.includes(selectedFile[i].people))
          {
            UploadStateSetState("true")
            break;
        }
       }

        <button onClick={onSubmittt}>submit</button>

Comment: Clearly it's not enough information because you've had to ask the same question twice.
Comment: @PatrickEvans that line was for testing purposes.i've edited the ask
Comment: And, `selectedFile` doesn't exist. You posted this same question a couple of hours ago but apparently didn't read any of the comments. You need to provide a [mcve] for us to help debug your code.
Comment: @Andy i belive thats enough info for the help. i just wanted the UploadStateSetState("true") to change the state of uploadStatus if conditions in the for is met. It only works on a second run. but i want it to run on the first run if condition is met

First Run  : False
Second Run : True
Third Run : True
Comment: Does this answer your question? [react js console.log returning false instead of true in first run](https://stackoverflow.com/questions/68881892/react-js-console-log-returning-false-instead-of-true-in-first-run)
Answer: Check the react Hooks rule guideline.
Don't call Hooks inside loops,
Rules of Hooks


How can I transition an order from fulfillment to completed?

Question: I'm running Commerce Marketplace and provide store owners a back-end portal for managing their store.
In their portal, they can view orders sitting in the "fulfillment" state with the shipping address.  Once they fulfill that order, I need to provide a button for them to move that order to the "completed" state.
How do I move an order to the "completed" state?  Do I send the user to a specific checkout route, or can I move the order itself to completed via the API?
Currently, the only way to move the order to "completed" is manually in the order under the Commerce administration.
Answer:
can I move the order itself to completed via the API?

Create button and create a new route. In that route's class you can do something like this. Example if order number is 1:
  $entity_manager = \Drupal::entityTypeManager();
  $entity_storage = $entity_manager->getStorage('commerce_order');
  $order = $entity_storage->load(1); // load order 1
  $current_state = $order->getState()->value;
  if ($current_state == 'fulfillment') {
    $order->set('state', 'completed');
    $order->save();
  }

OR alternatively if they need to be able to do this for several orders at the same time. (Checkmark several, and apply to selected items).
Instead of a button & route, create a custom View Bulk Operation action and use same code as above,
Ex:
Comment: @vintorg you bet
Comment: So, saving the new state will fire off any state-change events, hooks, etc?
Comment: @NoSssweat I am not getting the order to complete after applying the transition.
For eg: after `$order->getState()->applyTransitionById('fulfill');` I have to make the order cart to 0 to make the order to get complete. ie,
    `$order->unlock();
    $order->setPlacedTime(\Drupal::time()->getCurrentTime());
    $order->setOrderNumber($orderId);
    $order->set('cart', 0);
    $order->set('state', 'completed');
    $order->save();`. Any idea?
Answer: Perhaps one way to do this would be similar to what you can find in modules/contrib/commerce/modules/order/templates/commerce-order--admin.html.twig
{# If the order has possible transitions, render the field for transition buttons. #}
{% if order_entity.getState.getTransitions is not empty %}

  {{ order.state }}

{% endif %}

If the order is configured to pass from state fullfilled to completed the appropriate button for moving state should be available there.  Make sure your order_entity is passed to the twig template.
Read more about order workflow states
Comment: I'm not following.  Should I redirect to a route?
Comment: Just add this to your .twig template where you want the button to appear


How a browser can reach the server without doing postback?

Question: i've been asked this question and id not know the answer.
Thanks for any help!
Comment: Remove then the `master` from your nick name because is holding you back from your evolution. (do not place even the slave :)
Comment: You mean using ajax or something, your question is need more informations, how and what you like to do ?
Comment: Its theoretical question from job interview
Answer: Postback is a term used often in ASP.NET when a WebForm POSTs the single form back to the server and invokes some event in the code behind (like a click on a button for example). You could still use normal GET requests though to redirect to a given web page. For example you could use an anchor:
Go to page 2

When the user clicks on the anchor there is no postback occuring but a GET request to the target web page.
Another possibility is the user typing directly the address of the web page in his browser address bar.
Yet another possibility is to use javascript to perform an AJAX request which allows to invoke a web page without redirecting away from the current page. You could use any HTTP verb with AJAX.
Answer: If you like to categories the call to the server you can say that there are two types.
The GET and the POST
The POST is the post back and are the parameters that you send using a form
and the GET that are the parameters that you can send from the url.
More about:
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
http://catcode.com/formguide/getpost.html
but I think the interview question was about the Ajax call, and this is probably what they try to see if you know, how to use Ajax to reach the server with javascript and not make postback. But you need to know that Ajax can make POST back, but this is done with out leave the page, with out make a full page post back.
Answer: We can use javascript code to do some function without postback. This will save the time for the request and response to the server. But this client side. you can't reach the server without posting back.But my mean you can do functionality by javascript which does not postback the page.
Hope it may help.


Shrew wont connect after windows 8.1 upgrade

Question: I am using Shrew for my VPN connection on Windows 8.0 successfully but it stopped working properly after I upgraded to Windows 8.1. It connects to VPN ok but I cannot access anything on the network. After several attempts it disconnects. I tried uninstalling and reinstalling with no affect.
Any help wild be appreciated.
Thanks,
Dave
Answer: What version are you using?
When 8.1 was pushed to me here, my copy of Shrew 2.2.2 Professional stopped connecting entirely, with a "tunnel disabled" message (there were 3 messages, that's the only one I can remember). It also hosed my Virtual Machine networking.
To fix, I uninstalled my VMs (VirtualBox, etc.), rebooted, re-installed Shrew, rebooted, and then reintalled VMs. Now everything is working correctly.
HTH!
Comment: Uninstalling Shrew 2.2.2 Standard and re installing fixed my problem as well. Thanks Mike!
Comment: Same here: simply uninstalling and reinstalling 2.2.2 Standard fixed it, even without reboot.
Answer: I saw the same behaviour of Shrew on my machine; uninstalling, re-installing, manually deleting drivers and settings etc. didn't help.
As described here, I use TheGreenBow VPN Client now as an alternative, which works fine under Win 8.1.


drupal hook_update_N()

Question:
If I install all updates from site_name/update.php, and after change the system.schema_version from 7005 to 7003 using (to reinstall updates 7004 and 7005)
UPDATE system SET schema_version = 7003 WHERE name = 'test';
I then try to run site_name/update.php but it not run because the fields that hook_update_N() adds already exists. And I see when access update.php after error that 2 updates exists.
After I restore system.schema_version to its initially value (7005)

Are the updates 7004 and 7005 now installed or not?
Answer: What are you trying to do, and why are you trying to do this? To be honest, it makes no sense. First off, schema numbers should start at 7000 (in Drupal 7), and you should never be resetting them, particularly within hook_update_N(), as you're just going to cause the same code to be run every time the update process is run.
Comment: Ok, your initial post was a little confusing. But I understand what you are saying no1.

After step 1:

At this point, the updates in 7004 and 7005 are installed. However, Drupal thinks they are not, since you have set the version to earlier than these two updates.

After step 2: The updates are still installed. However, Drupal will not be able to perform updates because there will be errors due to the fields already existing.

After step 3: The updates in 7004 and 7005 are installed.
Comment: If you want to re-run updates, you shouldn't actually re-run them. What you should do add more updates to reverse what you have previously done. Example:

    hook_update_7006() {
      // Remove the fields you created in 7004 and 7005
    }

    hook_update_7007() {
      // Add your fields again
      // Do whatever it is you forgot.
    }
Comment: it start with 7000 and end with 7212, I simplify example. Ok I change
Answer:
Are the updates 7004 and 7005 now installed or not?

Were they both installed prior to your intentionally trying to break it?
If so, then yes.
If not, then no.
Comment: Nope, if you're trying to install/update modules like that you've done something wrong on the way. An update is only to take an old version of a module up to its current state. There's no reinstalling of updates as you put it. If you make a mistake in one update, you'll need another update to rectify that mistake (unless the operation you performed first time round happened to be one that can just be run again with no other interference; obviously creating a field doesn't apply)
Comment: For fields though, you can wrap the creation code in `if (!field_info_field('field_foo')) {` and same for the instance. You should only, ideally, be messing with this stuff if you're confident of what you're doing...mistakes in update hooks can end up being difficult to recover from
Comment: It was installed, and after i change the system.schema_version from 7005 to 7003 to reinstall it, but I forgot that the fields will remain and I can't reinstall until I not drop that fields from DB.
Comment: I can install from few only one update by it number from drush for example?

drupal hook_update_N()


Tilt location iOS app

Question: How can I determine the tilt location in the y direction on my iOS app? First I tried playing with the accelerometer. But the accelerometer values change even if the iPhone isn't tilting. Then I tried playing around with the gyroscope. But that only senses the rate of the tilt, not the position of the tilt.
Here is specifically what I am trying to do:
If you place an iPhone on a table in landscape position with the home button on the top. Then you slowly proceed to flip it in a manner such that the display is now facing down (you see the back of the phone) and the home button is still on the left. That tilt motion that is needed to do that is what I'm trying to measure.
Answer: The accelerometer is what you want. If your acceleration vector is a = (x, y, z), then the angles between this vector and the three axes are given by:
cos (angleXaxis) = x / sqrt(x^2 + y^2 + z^2)

cos (angleYaxis) = y / sqrt(x^2 + y^2 + z^2)

cos (angleZaxis) = z / sqrt(x^2 + y^2 + z^2)

To get the angles themselves you'll need to use the inverse cos function.
Comment: All as that does is print out x, y, and z components. Surely, in my question I've seen x, y, and z values if I said accelerometer values change even if the iPhone isn't tilting.
Comment: In my question I explained exactly which tilt I wanted. And yes, I'd imagine the angle would be useful. But that tutorial doesn't cover this.
Comment: How so? I did the following:
float distanceFactor = sqrt((xx*xx) + (yy*yy) + (zz*zz));
float ax = acos ( xx / distanceFactor );
float ay = acos ( yy / distanceFactor );
float az = acos ( zz / distanceFactor);

where xx, yy, and zz are the accelerometer values. But when I tilt the phone in the way I said, both the ax and az angle change....
Comment: By how much? One should be changing by more than the others. You aren't doing a precise movement, so it makes sense that more than what you expect is changing.
Comment: when I begin the tilt motion and continue until the phone is perpendicular to the table, x angle goes from 1.5 to 0 and z angle goes from 3 to 1.5
Comment: and what did you expect to happen instead?
Comment: I am expecting to figure out the tilt....and I'm not. Because there are motions I can do with the phone that will change the x angle. There are motions I can do with the phone that will change the z angle. But I don't understand. How do I detect the tilt I specifically described in my question. Please answer that specifically.
Comment: You have all of that information. Unless you tell me how, specifically, you would like the information outputting, I cannot help you further. Watch the output at the start, in the middle, and at the end of the rotation you are doing. I do not know what more you want.
Comment: All as you did is give me three angles. Specifically, how do I know when the phone is being tilted in the manner I described...that's the question. if(...), then phone is being tilted in this manner.
Answer: You should consider to use the Core Motion API because it provides the values ready to use as Euler angle, quaternion or rotation rate. Have a look at
Accelerometer detection and sprite rotation
iPhone - What does the gyroscope measures? Can I get an absolute degree measurement in all axis?
iphone - core motion (relative rotation)

Tilt location iOS app


Get position in ListView

Question: I use ListView to show several items.
My row.xml as below:
<TextView android:text="text"
android:id="@+id/tvViewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<Button android:text="Click me!"
android:id="@+id/BtnToClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClick">
</Button>

And I define myClick in Activity as below:
public void myClick (View v) {
LinearLayout vwParentRow = (LinearLayout)v.getParent();
//How to get the position
}

How to know the position which buttom be clicked?
The position mean same as the method onListItemClick's.
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
}

Comment: This question has been asked before, please look up questions before posting.
Answer: Try
public void DetailClick(View v) {
ListView lv = getListView();
int position = lv.getPositionForView(v);
}

Comment: Thank you so much for that! why is that information so hidden?
Answer: You can try like this.
Step 1: In your custom adapter
@Override
public view getView(int position, View convertView, ViewGroup parent){
.......//Perform your logic
    convertView.findViewById(R.id.BtnToClick).setTag(position);
    return convertView;
}

Step 2: In onclick listener
 public void myClick (View v) {
     LinearLayout vwParentRow = (LinearLayout)v.getParent();
     position=(Integer) v.getTag();
  }

Answer: Yes the position in the onListItemClick is same as the position of the item clicked in the list.
Comment: I mean how to get the position in myClick method
Answer: If I understand your question correctly, you have a button in each row of a ListView, and you want to know which row received the button click. How are you doing an setOnClickListener() on the button? The reason I ask this is - if you are setting the OnClickListener for each button, you already know the position of that button.
Comment: I have set onClick="myClick" in xml.
Comment: and define a new method of myClick
Answer: You should also read the documentation for ListView and even look through the available methods and their sample code.
Know your documentation.

Get position in ListView


Globally configuring Javascript for notebooks on Jupyterhub

Question: I would like to replace each user's  custom.js file with a global version. The only way I can figure out how to do this currently is to overwrite ~/.ipython/profile_default/static/custom/custom.js after a user runs their first ipython notebook and their .ipython directory gets instantiated.
There must be a better way, either by providing some global version of custom.js or by replacing the default custom.js file during installation. In theory, one could also create symbolic links to a global custom.js but this didn't work for me for some reason.
I see that there is a file /srv/notebook/notebook/static/custom/custom.js on my system - but modifying it doesn't alter the custom.js that gets installed for each user.
Any suggestions?
Comment: You shouldn't have to wait for the directory to be created - creating the directory yourself and writing `custom.js` should work. `custom.js` is intended for user overrides, so if it exists in the users directory, your systemwide copy will not be loaded.
Comment: Thanks @ThomasK, that is definitely a good idea, though I'm worried that by taking this approach I could end up putting a wrong or outdated copy of other configuration files inside of .ipython.
Answer: I'm running jupyterhub with dockerspawner, and have just found a solution here.
To make the custom.js file adopted by each user, you can derivate the jupyter/base-notebook image by adding it to each user's custom directory:
ADD ./custom.js /home/$NB_USER/.jupyter/custom/custom.js

Note this path is the path defined in the jupyter notebook doc.
Hope this helps anyone having the same problem.


Issue with jQuery Tabs CSS in IE6

Question: This is the website in question: http://www.ai-ad.com/2010Cwb/insidePage.html
The issue is with the bottom left jQuery UI Tabs (there are five tabs named : 淡水、陽明山、基隆、烏來、石門水庫)
In IE 6, when I move the cursor to other tabs, the content height under the tab will change.
I don't really know why, I thought it could a problem with jQuery UI's CSS, but I had tried many way, it still the same.
Can someone helps me to fix it?
Answer:
This is the website in question:
  http://www.ai-ad.com/2010Cwb/insidePage.html
  The issue is with the bottom left jQuery UI Tabs
  (there are five tabs named : 淡水、陽明山、基隆、烏來、石門水庫)
  In IE 6, when I move the cursor to other tabs, the
  content height under the tab will change.

It seems to require a few lines of javascript in order to
"tame" the "misbehaved" way that IE6 renders certain CSS
code.
Albert in Manila
Answer: I solved this problem by setting tabs height to 100%;
<code>$(".tabs").each(function(){
    $(this).css("height","100%");
    $(this).tabs();
});
</code>
Comment: In my case the problem was specifically with IE6 and when the tabs had collapsible panels in them - IE6 was having trouble calculating the height of the tab with the collapsible stuff in it. I was about to have to disable the functionality for dear old IE6 users (most of my customers), so thanks for the fix. In my case I only have one set of tabs so I just set the CSS to 100% before tabifying it and it's done.

Issue with jQuery Tabs CSS in IE6


Can a specific function with different continuities be used to compare topologies?

Question: I am studying general topology using Munkres, currently reading part 1, chapter 2, section 19(The Product Topology). I came across an example that gives a function which is continuous w.r.t. the product topology but failed to be continuous w.r.t. to the box topology, and we know that the product topology is generally coarser than the box topology(further more, strictly coarser on infinite sets). I feel like there is a connection between them(maybe there is not, of course). I wonder if a specific function with different continuities on different topologies can be used to compare topologies. So here is the generalized statement:

Suppose $X$ is a nonempty set with 2 topologies, namely $\mathcal{T_1}$ and $\mathcal{T_2}$. $\mathcal{T_1}$ is finer than $\mathcal{T_2}$(possibly equal). If there is a function $f:A \rightarrow X$ ($A$ is an arbitrary set with topology $\mathcal{T}$) which is continuous with respect to $\mathcal{T_2}$ but failed to be continuous with respect to $\mathcal{T_1}$, can we claim that $\mathcal{T_1}$ is strictly finer than $\mathcal{T_2}$?

Is there any thorem or counterexample? Any help is appreciated. Thank you in advance.
Comment: In fact, considering well chosen functions on various spaces is exactly how mathematicians compare them. This idea appears in every subject. For example, the continuous linear functions on a $k-$dimensional vector space and an $m-$dimensional vector space, where $k\neq m,$ are different. Or in group theory when one considers symmetries of squares vs triangles, etc.
Answer: Yes, we can. Because the alternative is that $\mathcal T_1=\mathcal T_2$, in which case a function $f\colon(A,\mathcal T)\longrightarrow(X,\mathcal T_1)$ if and only if it is continuous as a function from $(A,\mathcal T)$ into $(X,\mathcal T_2)$.
Comment: Thank you, I see.


ForEach Looping over View instead of Chart Data

Question: I am trying to get the ForEach to populate the data. Obviously this just creates a new view with one dataPoint as expected. How can I inject the array?
I tried @State and a for-in loop outside of the ViewBuilder but that did not work for some reason.
struct DashboardView: View {
    @ObservedObject var scoreListVM = ScoreListViewModel()
    @State private var isPresented = false
    var body: some View {
        NavigationView {
            VStack {
                ForEach(scoreListVM.scoreCellViewModels) { scoreListVM in
                    LineView(data: [Double(scoreListVM.score.totalScore)], title: "Acft Scores")
                }
            }
            .navigationBarTitle("Dashboard")
            .navigationBarItems(trailing:
                Button(action: {
                    self.isPresented.toggle()
                }) {
                    Image(systemName: "book.circle")
                        .imageScale(.medium)
                }
                .sheet(isPresented: $isPresented) {
                    InstructionView()
                        .environmentObject(self.colorSchemes)
            })
        }
    }
}

Answer: If you want your ForEach loop to create many LineView items, you can use a dynamic ForEach (with explicit id):
ForEach(scoreListVM.scoreCellViewModels, id:\.self) { scoreCellVM in
    LineView(data: [Double(scoreCellVM.score.totalScore)], title: "Acft Scores")
}

Assuming the scoreListVM.scoreCellViewModels variable is an array of ScoreCellViewModel items.


Finding all solutions of the equation $(x^2 + y^2 + z^2 − 1)^2 + (x + y + z − 3)^2 = 0$.

Question: Find all solutions of the equation
$(x^2 + y^2 + z^2 − 1)^2 + (x + y + z − 3)^2 = 0$.

not getting any clue.can somebody help me please.thanks.
Comment: The fact that gets you started is that if $A^2 + B^2 = 0$, then $A = 0$ and $B = 0$.
Answer: I assume we are looking for real solutions. Then our equation is equivalent to the system $x^2+y^2+z^2=1$, $x+y+z=3$.
Note that because $x^2+y^2+z^2=1$, the absolute values of $x$, $y$, and $z$ are $\le 1$, and they are not all $1$.
Thus $|x+y+z|\le |x|+|y|+|z| \lt 3$.
Answer: (Assuming $x, y, z$ are real.)
How can the sum of two squares be $0$? We know that the square of anything must be positive. Therefore, they both must be zero in order to add up to zero.
$$ x^2 + y^2 + z^2 − 1 = 0 $$
$$ x^2 + y^2 + z^2 = 1 $$
We also have:
$$ x + y + z - 3 = 0 $$
$$ x + y + z = 3 $$
If you want numeric values, you cannot solve the equation (we have 2 equations and 3 variables). However, we can solve for any pair of variables.
If we restrict the range to the reals, there is no solution. You can note this by solving for $x$ and $y$ with respect to $z$, and noting that any solution will be purely imaginary.
Comment: You can't restrict to the reals at the end as an afterthought: the assumption that two squares can't sum to zero without both being zero is entirely dependent on whether $-1$ is a square in where you are working.
Comment: I think you mean the square of anything must be _non-negative_.
Answer: If $x,y,z$ are real, we can set $x=\cos A\cos B,y=\cos A\sin B,z=\sin A$
Now, $$\cos A\cos B+\cos A\sin B+\sin A=\cos A\sqrt2\cos(B-\frac\pi4)+\sin A\le \sqrt2\cos A+\sin A$$
Let $\sqrt2=R\cos C,1=R\sin C$ where $R>0\implies R^2=2+1=3,R=\sqrt3, \cos C=\sqrt\frac23$
$\implies \sqrt2\cos A+\sin A=\sqrt3\cos(A-\arccos\sqrt\frac23)\le \sqrt 3$
So, $x+y+z\le \sqrt3$ which occurs when $A-\arccos\sqrt\frac23=2n\pi\implies \cos A=\sqrt\frac23$ and $B=\frac \pi4$
So there is no real solution for $x+y+z=3$ if $x^2+y^2+z^2=1$


why this function addStuent() doesn't return what i expect in python

Question: i have a python class that called student.py where it contains attributes and methods  one of these method is called addStudent(self,name,age). it takes 2 arguments.
the problem is this function display the name and the age of the new student using the setter method.
but the console display this :
None is a new student and he/she has None years old
where None  MUST BE THE NAME AND THE AGE
student.py
class student():
    def __init__(self,name,age, grade):
        self.stdName=name
        self.stdAge = age
        self.stdGrade = grade

    def getName(self):
        print("the student name {}".format(self.stdName))

    def setName(self,Name):
        self.stdName = Name

    def getAge(self):
        print("the student age :{}".format(self.stdAge))

    def setAge(self, Age):
        self.stdAge = Age

    def getGrade(self):
        print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade))

        if self.stdGrade<2.5:
            print("you failed")
        elif self.stdGrade>2.5:
            print("good job continue")
        elif self.stdGrade == 5.0:
            print("you are a honor student")

    def setGrade(self,Grade):
        self.stdGrade = Grade

    def getTheAVG(self,initial,*grades):

        value = initial
        for item in grades:
            value+=float(item)
            return value/(len(grades)+1)

        print("Average of the student is " + str((grades)))

    def addStudent(self,name,age):
        print("{0} is a new student and he/she has {1} years old"
              .format(self.setName(name),self.setAge(age)))

std1 = student("georges", 17, 3.4)
std1.getName()
std1.getAge()
std1.getGrade()
std1.addStudent("jiji",12)

std1.getTheAVG(2.4,5.0,4.6,2.2,1.2)

Comment: because `self.setName` doesn't return anything?
Comment: It doesn't return what you expect because you have no `return` statement in your function, which therefore returns `None`
Comment: okk i got it can any one make an answer in order to make it correct answer
Comment: It is your design that is wrong. Why do you have an `addStudent` method - you should call the constructor again to add a new student object.  In your `addStudent` method you are trying to call setter methods in a `print` statement where you should call getters.

Your getter methods should just get (return) values, not `print` them - you can always use `__str__` if you need to.  If they need to be printed then that should be up to the user code.  Your setter methods should ONLY set.  Be clear that functions should do only ONE thing.
Comment: Also, your `getTheAVG` method should not be an object method since it does not use `self` anywhere.
Comment: @cdarke i have this exercise where i need to create a student CLASS and a class CLASS.

i am new to oop so i do not know what are the methods that i can added to the student and class CLASS and how to make the class conssist of the student class as a list of student objects
Comment: I suggest that a class called CLASS is horribly confusing, call it something else. like StudentGroup, for example.  A StudentGroup object can hold a list of Student (you should capitalise class names) objects.  That's where the `getTheAVG` method should be.
Answer: You function is not returning a value hence it is getting None. You can do this.
def setAge(self, Age):
        self.stdAge = Age
        return self.stdAge

But, Having said it is a setter method from a design point of view you won't expect a setter function to return any value
Answer: Your print relies on the return values of two methods that don't return anything. Either have thesetName and setAge methods return the value they set, or just use the attribute values.
Answer: check this:
class student():
    def __init__(self,name,age, grade):
        self.stdName=name
        self.stdAge = age
        self.stdGrade = grade

    def getName(self):
        print("the student name {}".format(self.stdName))

    def setName(self,Name):
        self.stdName = Name
        return self.stdName

    def getAge(self):
        print("the student age :{}".format(self.stdAge))

    def setAge(self, Age):
        self.stdAge = Age
        return self.stdAge

    def getGrade(self):
        print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade))

        if self.stdGrade<2.5:
            print("you failed")
        elif self.stdGrade>2.5:
            print("good job continue")
        elif self.stdGrade == 5.0:
            print("you are a honor student")

    def setGrade(self,Grade):
        self.stdGrade = Grade

    def getTheAVG(self,initial,*grades):

        value = initial
        for item in grades:
            value+=float(item)
            return value/(len(grades)+1)

        print("Average of the student is " + str((grades)))

    def addStudent(self, name, age):
        print("{0} is a new student and he/she has {1} years old"
              .format(self.setName(name), self.setAge(age)))

std1 = student("georges", 17, 3.4)
std1.getName()
std1.getAge()
std1.getGrade()
std1.addStudent("jiji",12)

std1.getTheAVG(2.4,5.0,4.6,2.2,1.2)

This will give you your desired output.
Note: Your function is not returning a value thats way it give you None but from a design point of view as your method is a setter method and setter methods don't return a value.
Answer: If you want your setter method to return something, do something like this
class Student:

def setName(self,Name):
    self.stdName = Name
    return self.stdName

def setAge(self, Age):
    self.stdAge = Age
    return self.stdAge

Comment: what  methods can i added to the student class ?
Comment: This is poor design, setters should set, not get as well.
Comment: @PytLeb, Please try to change the code design, as everyone is pointing and telling the same thing, you can't return some value in setter method, It's better to store your data in dictionary or list which you can print anytime whenever you add new data.


AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application:" xxx "

Question: I have a use case for a project where I need to automate the creation of Application Registration on Azure programmatically.
I have been using this sample.
error screenshot
We seem to be facing an issue with Authentication for this App Registration code. We have checked the ReplyURLs with the urls in our App Settings. They are the same. What may be another reason for this occuring?
We also found another link on microsoft documentation where this thread seems to be open but have not found a solution there either. https://learn.microsoft.com/en-us/answers/questions/54102/the-reply-url-specified-in-the-request-does-not-ma.html
Comment: If the posted answer resolves your question, please mark it as the answer by clicking the check mark. Doing so helps others find answers to their questions. See:  https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: Hi, has your problem been solved?
Answer: To deal with this kind of problem, you can try a general solution:
When you visit the application url , you will be redirected to the login page. Decode the authorization request url, you will find redirect_url, copy the value of redirect_url and paste it into the azure portal, and try again.

For the redirect URL, it should start with https, if you need to start with http, you must configure it as http://localhost.