Get a list of users who are Domain Admins and have not logged in the past 30 days?

Question: How can I get a list of users from AD who are Domain Admins and have not logged in the past 30 days?
Comment: Welcome to [sf]! What have you tried so far?
Comment: If my updated answer does what you need it to, please feel free to click the up arrow next to my answer to upvote it and mark the answer as correct by clicking the checkmark next to my answer.
Answer: user360071, here is a PowerShell script that will do what you want.
Import-Module ActiveDirectory
$Age = 30
$When = ((Get-Date).AddDays(-$Age)).Date
$Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName
Foreach ($Member in $Members) {
Get-ADUser -Identity $Member -Property LastLogonDate | Where LastLogonDate -lt $When | Select SamAccountName,UserPrincipalName,LastLogonDate | Export-CSV -Path $env:USERPROFILE\Desktop\users.csv -NoTypeInformation -Append
}

You can make a small change so you can pick how long you want to look for an account that has not logged in. Here is the changed version.
Import-Module ActiveDirectory
$Age = Read-Host "Accounts that have not been logged into in the last how many days should be shown?"
$When = ((Get-Date).AddDays(-$Age)).Date
$Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName
Foreach ($Member in $Members) {
Get-ADUser -Identity $Member -Property LastLogonDate | Where LastLogonDate -lt $When | Select SamAccountName,UserPrincipalName,LastLogonDate | Export-CSV -Path $env:USERPROFILE\Desktop\users.csv -NoTypeInformation -Append
}

Updated Answer
Hello user360071. When you want to add another request to your question or need to clarify what you are trying to ask you can edit your question and save the changes.
In your addition you added that you want to be able to save the results to an Excel file.
You tried >> users.csv but the Excel file is empty. In PowerShell what you want to do is | Export-CSV users.csv. The scripts have been updated with this.
Comment: Don't forget to recourse the domain admins group just in case there are nested groups. You might also want to query the domain's "Administrators" group in case some accounts get added there as well.
Comment: @SturdyErde thanks for the idea. I added that to my answer.
Answer: To implement user5870571's suggestion with >> users.csv (in case your file is blank - mine was too) do the following:
1) save the below script to a .ps1 file. Note that I removed Export-Csv
    Import-Module ActiveDirectory
    $Age = Read-Host "Accounts that have not been logged into in the last how many days should be shown?"
    $When = ((Get-Date).AddDays(-$Age)).Date
    $Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName
    Foreach ($Member in $Members) {
    Get-ADUser -Identity $Member -Property LastLogonDate | Where LastLogonDate -lt $When | Select SamAccountName,UserPrincipalName,LastLogonDate
}

2) once you saved the file, navigate to it from an elevated powershell prompt and add >> users.csv at the end.
For example, I named my file get-dausers.ps1 and saved it on desktop, opened a powershell prompt and navigated to it, then typed .\get-dausers.ps1 >> users.csv - this will generate a .csv file on the desktop and it will not be empty anymore.
Answer: To build on user5870571's post -
I would recommend using the LastLogonTimestamp property of the ADUser account, instead of the LastLogonDate.
lastLogon vs. lastLogonTimestamp in Active Directory

Lastlogon is only updated on the domain controller that performs the authentication and is not replicated.
LastLogontimestamp is replicated, but by default only if it is 14 days or more older than the previous value.

Below is the updated code.  I also added the "sort by LastLogon" because I think it's useful.
Import-Module ActiveDirectory

$Age = Read-Host "Accounts that have not been logged into in the last how many days should be shown?"

$When = ((Get-Date).AddDays(-$Age)).Date

$Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName

Foreach ($Member in $Members) {
    Get-ADUser -Filter {DistinguishedName -eq $Member} -Property LastLogonTimestamp | Where {([datetime]::FromFileTime($_.LastLogonTimestamp)) -lt $When} |
    Select SamAccountName,UserPrincipalName,@{Name="LastLogon";Expression={[datetime]::FromFileTime($_.LastLogonTimestamp)}} | Sort-Object LastLogon |
    Export-CSV -Path $env:USERPROFILE\Desktop\users.csv -NoTypeInformation -Append
}


How to formally define the set of function that an guarantee a unique optima in constraint maximisation problem

Question: We know that a strict concave function can guarantee a unique maximum. But in a constraint maximisation problem, there can still exists a unique maximum when the function is not concave. My question is how to formally define the set of functions that can guarantee a unique optima in constraint maximisation problem?
For example, the picture below would not be in this set as there are two disjoint local maximum.One optima is at the peak and the other is at the boundary.
Answer: Without specifying anything about the function or the constraint, there is no simple condition that is both necessary and sufficient for a unique maxima, except for the trivial condition of saying that it is the set of functions with a unique maxima.
If you really want to, you could define this formally (in a trivial and unhelpful way) by formally defining the set of functions with unique maximising points.  For example, consider the set of univariate real functions of the form $f :\mathbb{R} \rightarrow \mathbb{R}$ and let $\mathscr{F} \equiv \mathbb{R}^\mathbb{R}$ denote the function-space for these functions.  Given a constraint set $\mathcal{D} \in \mathbb{R}$, the set of functions with a unique maxima on this constraint set can be defined as:
$$\hat{\mathscr{F}} (\mathcal{D}) \equiv \{ f \in \mathbb{R}^\mathbb{R} | (\exists x \in \mathcal{D}) (\forall x' \in \mathcal{D}-\{ x \}): f(x) > f(x') \}.$$


Solving recursive formula including a sum

Question: I have the following formula
$$T(1) = 1 $$
$$T(n) = \sum_{i=1}^{n-1}T(i) + n^2$$
And I have to find an iterative form of any $T(n)$ for $n>1$
One thing I have managed to accomplish so far is calculating
$$T(n+1) = 2T(n) + 2n + 1$$
but I don't really know where to go from there.
I'm really new to recursion in mathematics and all the methods seem to either include guessing or require a lot of hardcore algebra. Any help will be much appreciated.
Comment: By *, do you mean $\times$, $+$ or what? Because your recursion relation suggests it can't be $\times$.
Comment: That was a typo, sorry, and thank you for pointing out.
Comment: You could continue by, say, noting that $T(n)=2T(n-1)+2(n-1)+1$ and subtract to remove the $n$ term.  Then you can do it again to kill the constant.
Answer: Let $S(n)=\sum_{i=1}^n T(n)$. This allows you to rewrite the recurrence as
$$S(n)-S(n-1)=S(n-1)+n^2,$$  with $S(2)=1$.
As the recurrence is linear, we can first solve the homogeneous par of the equation
$$S(n)=2S(n-1)$$ and it is easy to see that
$$S(n)=c\,2^n$$ holds.
Now we have to find a particular solution of the complete equation
$$S(n)-2S(n-1)=n^2.$$ We can infer that if we plug a quadratic polynomial on the left, we will get a quadratic polynomial:
$$n^2=pn^2+qn+r-2(p(n-1)^2+q(n-1)+r)=-pn^2+(4p-q)n+2q-2p-r$$
and by identification we get the solution
$$-n^2-4n-6.$$
Finally, combining and using the initial condition,
$$S(n)=19\cdot2^{n-2}-n^2-4n-6$$
and
$$T(n)=S(n)-S(n-1).$$
Answer: hint
$$2^{n-2}T(2)=2^{n-1}T(1)+2^{n-2}.3$$
$$2^{n-3}T(3)=2^{n-2}T(2)+2^{n-3}.5$$
•••
$$2^2T(n-2)=2^3T(n-3)+2^2(2n-5)$$
$$2T(n-1)=2^2T(n-2)+2(2n-3)$$
$$T(n)=2T(n-1)+(2n-1)$$
Answer: Define $A(n):=T(n)-an-b$, where we'll choose $a,\,b$ to simplify the recursion relation$$A(n+1):=2A(n)+(a+2)n+b-a+1.$$With $a=-2,\,b=-3$, we have$$A(1)=6,\,A(n+1)=2A(n)\implies A(n)=3\cdot2^n,\,T(n)=3\cdot2^n-2n-3.$$
Answer: Actually, $$T(n+1) = 2T(n) + 2n + 1$$ is the decisive step to solving this problem: an ansatz $T(n)=an+b$ gives immediately $T(n)=-2n-3,$ and the difference of this particular solution to the actual one must  be a solution of the homogeneous equation $T(n+1)=2T(n),$ i.e. $T(n)=c\cdot2^n$. From $T(1)=1,$ we get $c=3$, so $T(n)=3\cdot2^n-2n-3.$
Comment: Could you please explain how does it give $T(n)= -2n -3$?


Can a chord contain both the C and C♯ notes? (as opposed to containing C and D♭ notes)

Question: Can a chord contain both the C and C♯ notes? Or do you always have to use D♭ rather than  C♯ in a chord that already contains the note C?
I'm guessing the answer is no, both C and C♯ should not be allowed - but I do see a lot of inconsistency on the web with what enharmonic is used to describe a chord.
For instance, take the A♭m chord. I'm pretty sure it is correct that this chord contains the notes A♭, C♭ and E♭ ? In many places I look online, they say the C♭ is a B. But I don't think that is right, because in the A♭ major scale, the B is flat.
So therefor, going back to my question, a chord in the key of A♭ can never contain a "straight" B note. The B must always be one of B♭, B♯ or B♮. And if you're talking about a note that represents the 3rd, then that note must always start with 'C' - and therefor the minor third in Ab major can never be described as B.
Correct?
Comment: The diatonic third in A♭ is always going to be some kind of C, because B♭ is already the diatonic (major) second and, as mentioned, when naming chords in a diatonic scale each note must be assigned a different name. A♭m will use the minor third, C♭ (which is *enharmonic* with B), while A♭M will use the major third, C.
Comment: This question shows an example of such a clash between two notes in the same octave. https://music.stackexchange.com/questions/24030/what-does-this-split-stem-notation-mean?rq=1
Answer: In classical Western music theory, each diatonic scale contains seven notes, and each of the notes must be assigned a different note name. (So one also does not write CX for the D in the C major scale.)
In non-equal temperament, C# and Db may in fact be two different pitches, and a diatonic scale that contains a C must not also contain a C#.
In more modern music theory, uses of polytonality and non-diatonic scales in composition, especially the chromatic scale with 12 tones and the diminished and bebop scales with 8 tones, make it impossible for a scale to contain only notes with distinct note names. That and the widespread use of equal temperament (so that C# and Db are indeed enharmonic equivalents) makes it slightly more acceptable to refer to the third note in the ascending Ab minor scale as a B; though perhaps this practice is for the sake of players (especially piano players) less trained in music theory that thinks of sharps and flats as only modifiers to change from white keys to black keys.
I do think the vast majority of musicians performing Western music will prefer you spell Abm as Ab Cb Eb, and not Ab B Eb.
But going back to your original question: I don't see why not (theoretically). The presence of a minor second or a minor 9th is a big aesthetic no-no in a lot of chord-voicing traditions, but that rule may not be so hard and fast. In theory, the same notes may even be interpreted differently functionally by fitting them over different scales. For example, the notes C-E-G-Bb-D# spell the usual C7+9 chord. But reading the D# as an Eb, those are the root, 4th, 6th, 8th, and 3rd notes of the C diminished scale.
Comment: The question is not if a minor second or a minor 9th is a problem, because they would entail a Db in a chord with root C. The question is if an augmented prime (or an augmented octave), i.e. a C# will occur or not.
Comment: @MattL. assuming equal temperament, the two are equivalents as far as the harmonic contents go, so aesthetic objections to minor 9 apply equally to augmented octave. My third paragraph already addressed the issue of "chord spelling": in short, yes, they do occur, and for good reason. // In unequal temperament, the two notes are different, so if it is really a C# you have to spell it like that, and not as a Db.
Comment: This does not answer the question. The OP was at pains to specify "the C and C♯ notes? (as opposed to containing C and D♭ notes)". Min 9 is not the same as aug 8ve. In this OP's context we may not pretend they're equivalent, because the OP concerns harmony, NOT temperament.
Comment: @RosieF: did I not address that in the first and third paragraph? The first paragraph addresses specifically the classical western tradition of requiring different note names for tones in a scale, and the third paragraph addresses specifically the _lack_ of this need in modern music theory where a scale may contain more than 7 notes.
Comment: You don't have to have equal temperament to have enharmonic equivalence.  Any 12-tone temperament will do.
Answer: I can think of at least one example where I encountered a C and C# conjoined. In Béla Bartók's  Nine Little Piano Pieces, you'll find them in the Menuetto from measure 10 on.
It would be natural to find more of these in Bartók, especially the pieces using polytonality. Other composers using polytonality like Stravinsky should also have them. So, look for composition of the early 20th century using polytonality.
Answer: Check out Chopin's etude op 10 no. 2 in A minor. He uses this kind of device all throughout. In fact, it's just what you're taking about, a C and C# at the same time.
Answer: You are correct that Ab minor must contain a Cb, not any form of B (even though Cb and B are "enharmonically equivalent", Cb is the correct spelling here).
However, there are contexts in which two different versions (e.g. sharp and natural) of the same base note can sound together. When this occurs, it is called a "chromatic contradiction," or a False Relation. Since this won't ever occur in a single diatonic scale, the two clashing parts must come from different scales. One place this might occur is in when one is playing a descending melodic minor scale, while another is playing an ascending minor scale.
This technique isn't even limited to modern classical music. It goes back as early as the Renaissance Era. Here's what it sounds like.
I believe that "blues notes" might work like this sometimes as well, where you have a major chord in the accompaniment, but with a minor third in the melody.
This question contains a picture of an example where this occurs in Chopin: What does this split stem notation mean?
Answer: In jazz, a sharp 9 chord is often spelled with both thirds emphasizing the bluesey major/minor sound thus A7+9 = A C# E G C though the last C would technically be a B# according to the rules of western harmony.
Comment: @ReinHenrichs: correct. There is something to this answer though: you can voice A7+9 with both the b9 and the #9. There you have A, Bb, B#/C, C#. I would prefer to spell it A - C# - G - Bb - C, thus having both C and C#. This is really a sign of the limitations of our notation system, in my opinion.
Comment: A 7#9 chord doesn't have both thirds. It has a major third and a sharp 9. The sharp 9 is enharmonic with the minor third but functionally quite different.
Comment: Agreed. And having a Db instead of a C# in a A7 variant of chord feels... urk. This is what I meant with limitations of the system. You can see A7+9 as a chord with the third, the seventh, a minor ninth, and an augmented ninth, then come up with one spelling. Or you can see it as a set of tones from Bb minor melodic and come to another spelling. There are several ways to look at it, and they are not very consistent. It is even worse when you start using things such as diminished scales (on A7b9. Too many tones!) or whole tone scales (too few!).
Comment: @Gauthier: The issue is that the 7#9 chord is often considered to be constructed from the 7th mode of the (ascending) melodic minor scale, but Bb melodic minor has a Db rather than a C#.
Answer: Well, sure. As a chord is simply any number of notes defined in terms of their interval from a "root" note, a chord can have any two or more semitones in it. A lot of contemporary composers such as Eric Whitacre play around a lot with dissonant intervals and "cluster chords" involving minor-second intervals like C/C#.
More realistically, it would be rare to see both a C natural and a C# in the same chord, notated as such. This is primarily because the notes would take up the same line or space in the staff, so it would be difficult to sightread and could be impossible to notate properly if there's a D or B in the chord as well (as in the aforementioned cluster chords). However, C# and Db are enharmonic (same note on the piano keyboard), so you may see a C and Db in the same chord. In the key of Ab, an Ab major triad with the fourth added (not a suspended chord, but an add4) would have both of these tones, and in the contemporary climate of music composition it wouldn't be that odd to hear.
Answer:
For instance, take the A♭m chord. I'm pretty sure it is correct that this chord contains the notes A♭, C♭ and E♭ ? In many places I look online, they say the C♭ is a B. But I don't think that is right, because in the A♭ major scale, the B is flat.

A minor triad is a minor third then a major third. A♭ to C♭ is a minor third and C♭ to E♭ is a major third. A♭ to B is an augmented second and B to E♭ is a diminished fourth. They'll both sound the same when you play them on a piano or guitar, but if you write them down the second one would be considered wrong.
Answer: Yes. (And it's even consistent with common-practice harmony, not that you're obliged to stick to that.) For example, in D minor, you may have C# in the harmony (the third of the dominant), and also C as a melody note (the seventh degree of the descending melodic minor scale).
Here is an example. (Bizet, L'Arlesienne suite no. 1, mvt. 3 (Carillon), b.5 and 7 of the Andantino section.) The key is C# minor, with the notes being B and B#.
Answer: Neutral intervals are usually voiced with the major and the minor simultaneously on chromatic instruments that only have semitones (fretted instruments, most valved winds and keyboards without pitch bending).
Eg. an A neutral consists of an A, a C half-sharp (it's the quartertone between C and C#, for the notation imagine the # but with only one vertical instead of two) and an E. On a piano this will be voiced with A, C, C# and E. Harmonies with neutral thirds and neutral sevenths are found in music based on scales found in Africa. And if I mention neutral sevenths, of course a D neutral is another example for C and C# to be present at the same time. This would be voiced with D, F, F#, A, C and C#.
Answer: The chord could have a Chromatic non chordal note that has a C#. If say for argument sake we are G Major and we go from IV to V we may have a non chord note that forms the baseline C-C#-D
Answer: YES, but if you RE-NAME the C as B#.  Yes B# is the enharmonic equivalent of C.  But because the C is assigned to C# we have to bump up the B to take the place of the C.  It's a linguistic wordplay game but it is necessary for the rules of the game we have chosen to play.
examples:
C#maj7 = C# E# G# B#
A#m(add9) = A# C# E# B#
F#maj7#11 = F# A# C# E# B#
if you believe it is unruly or sloppy to use any letter name more than once, the answer is NO!!!
Comment: This does not answer the question. The OP was at pains to specify "the C and C♯ notes? (as opposed to containing C and D♭ notes)".
Answer: If your world view contains a system of harmony that tells you what you MAY do, you'd better follow its rules.  If it contains one that attempts to describe what IS done, work out what you mean by such a notation.  If you have a reasonable answer, it's good!


How to find result of two table as unique when count of column equal one or two?

Question: I have two table , one name of student and other one have lesson of student , I need to find student with have two or one lesson .
table 1 :(students)
id , name , family , birth , mobile

table 2 : (lessons)
id , studentID , name

and my code is
SELECT t.* FROM students AS t LEFT JOIN lessons AS tr ON t.id = tr.userID WHERE count(tr.*) = 1

Comment: you got some advance?
Comment: @AdrianCidAlmaguer no , dont work answers :(
Answer: This is your query:
SELECT students.name, COUNT(studentID) AS CANT FROM students, lessons WHERE students.id = studentID GROUP BY studentID HAVING CANT = 1 OR CANT = 2

Answer: Try this
SELECT s.id , s.name , family , birth , mobile FROM student s, lessons l WHERE s.id = l.studentID AND (SELECT COUNT(*) FROM lessons WHERE studentID = student.id) as totalLessons BETWEEN 1 AND 2 GROUP BY s.id


Sendmail still displays through telnet even though I'm using Postfix

Question: I recently installed and configured Postfix, and removed every aspect of Sendmail that I could from my Debian x86 system.
<code>telnet localhost 25
</code>
...still returns that I'm using Sendmail. I've uninstalled it, stopped it multiple times, and started/restarted Postfix multiple times as well.
Comment: Exactly what did you do?
Comment: Postfix will answer on port 25 as well as sendmail.
Answer: Post the output of:
<code> netstat -anp | grep :25
</code>
Comment: `tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      750/sendmail: MTA:` is the output I get. I also seem to not be able to stop the process from running, as /etc/init.d/sendmail stop doesn't give me any error when i continually type it. It's not on my startup list, either.
Comment: you still have sendmail running - you can do a 'ps -eaf | grep sendmail' to look at it - kill it, also you can try a 'whereis sendmail' and rename or remove it.


How many ways can $5$ marbles be placed in $7$ boxes?

Question: How many ways can $5$ marbles can be placed $7$ boxes if
(1)Marbles are different colors and marbles may share a box.
(2)Marbles are different colors and marbles may not share a box.
(3)Marbles are same color and marbles may not share a box.
(4)Marbles are same color and marbles may share a box.
My try:(1)$7^5$ (2)$7P2$ (3)? and (4)? plz Help.Thank you.
Answer: Some hints:
For 3, note that you simply need to choose 5 boxes out of the seven to put marbles in...
For 4, try using stars and bars, by thinking about the boxes as dividing lines between marbles. For example, the below arrangement would represent 2 marbles in box 1, none in box 2, 1 marble in box 3, none in box 4 and 5, and 1 marble in boxes 6 and 7. How many such arrangements are there?
<code>**||*|||*|*
</code>
Answer:
How many ways can $5$ marbles be placed in $7$ boxes if the marbles are different colors and marbles may share a box?

Your answer of $7^5$ is correct since there are seven choices for each of the five marbles.

How many ways can $5$ marbles be placed in $7$ boxes if the marbles are different colors and marbles may not share a box?

Line up the marbles in some order.  Since the marbles may not share a box, we have seven choices for the first marble, six choices for the second marble, five choices for the third marble, four choices for the fourth marble, and three choices for the fifth marble.  Hence, the number of ways the marbles can be distributed is
$$7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 = \frac{7!}{2!} = \frac{7!}{(7 - 5)!} = P(7, 5)$$
not
$$P(7, 2) = \frac{7!}{(7 - 2)!} = \frac{7!}{5!} = 7 \cdot 6$$

How many ways can $5$ marbles be placed in $7$ boxes if the marbles are the same color and may not share a box?

We must select five of the seven boxes in which to place the marbles, which can be done in

 $$\binom{7}{5}$$

ways.

How many ways can $5$ marbles be placed in $7$ boxes if the marbles are the same color and may share a box?

Let $x_k$, $1 \leq k \leq 7$, be the number of marbles placed in the $k$th box.  Then
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 = 5$$
which is an equation in the nonnegative integers.  A particular solution corresponds to the placement of six addition signs in a row of seven ones.  For instance,
$$1 + + 1 1 1 + 1 + + +$$
corresponds to $x_1 = 1$, $x_2 = 0$, $x_3 = 3$, $x_4 = 1$, $x_5 = x_6 = x_7 = 0$, while
$$+ 1 + 1 + + 1 + 1 + 1$$
corresponds to $x_1 = 0$, $x_2 = x_3 = 1$, $x_4 = 0$, $x_5 = x_6 = x_7 = 1$.  Thus, the number of ways we can distribute the marbles is the number of ways we can insert six addition signs in a row of five ones, which is

 $$\binom{5 + 6}{6} = \binom{11}{6}$$ since we must select which six of the eleven positions (five ones and six addition signs) will be filled with addition signs.


What does this function return?

Question:     rowData = []

    function something () {
    return rowData
    }

Update:
Now lets take the Array contains a lot of Objects. So we say that this would return an Array of Objects.
I am just confused a lot. Does this return an Object or Array of Object Or just an Array.
Comment: It returns `rowData` which is an array. It does not matter what is in the array. An array is an array.
Answer: It returns whatever the current value of rowData is.
That variable is initialized as an empty array. It might change by the time the function is called.
An array is a specific type of object.
Answer: It returns an empty array from your function. Please note that the value returned from this function will change if anything changes the rowData symbol in the global scope.
Answer: [] is an array literal so that function returns an empty Array. In JavaScript, arrays are really objects and they are a little different than traditional arrays.
From Douglas Crockford's JavaScript: The Good Parts

JavaScript provides an object that has
  some array-like characteristics. It
  converts array subscripts into strings
  that are used to make properties.

And...

Unlike most other languages,
  JavaScript's array length is not an
  upper bound. If you store an element
  with a subscript that is greater than
  or equal to the current length, the
  length will increase to contain the
  new element. There is not array bounds
  error.

What does this function return?


In the baroque period, did soloists play all the way through concertos?

Question: In most recordings of baroque concertos that I've heard, the soloist plays straight through without stopping, especially in the first movement. While there are marked solo sections where the soloist is more exposed, but she plays the whole time.
One exception to this that I've found:

However, is this the exception or the rule?
In Classical/Romantic concertos, there are often long orchestral introductions and many tutti sections where the soloist stops and awkwardly holds his instrument/fiddles with it/stares silently into the crowd with intense eyebrow movements. Is this also part of the style of the day?
Comment: "Is this also part of the style of the day?" - which "day" are you referring to there? At least from Beethoven onwards, there is zero doubt in the score as to where the soloist plays and rests. Before that, the relationship can get more complicated...
Comment: Related [question](https://music.stackexchange.com/q/63841/2600).
Answer: I think your observation is correct.  In the Baroque period, although the solo instrument(s) were generally scored in the tutti sections, there are a few works where they are in the habit of laying out until their featured entry.
Comment: Could you add some dates here -- historical periods where soloists were just members of the sections, and when it became more common to have separate standalone performers?
Answer: I've read that this was the practice with Vivaldi Concertos (to play through the tuttis). But I am open to the possibility that perhaps the tutti sections were written into the solo parts as cues for the soloist. I've never seen this possibility discussed. Probably there are some good reasons that I don't know about. (Especially since I haven't made a study of the subject, just had it as something I've long wondered about.)
One question that arises, at what point did the practice of including cues start, and were smaller notes used from the start, or were the smaller noteheads an innovation, and if so, when was that innovation?
As far as the modern oboe is concerned, it certainly makes sense to rest instead of play on Vivaldi concertos, and most recordings that I know of allow the oboist to rest. A baroque oboe would be better able to play both the tuttis and solo sections without fatigue issues, since the baroque oboe is not played maintaining as high a breath pressure.


$2$-capacity of a set in $\mathbb{R}^n$

Question: Let $B_r \subset \mathbb{R}^n$ denote the ball of radius $r$ centered at the origin. Consider any set $F \subset B_1$. For all sets $\Omega \subset \mathbb{R}^n$ such that $F \subset \Omega$, define $2$-capacity by
$$cap_2 (F, \Omega) = \inf_{\phi|_F = 1, \phi \in C^\infty_0(\Omega)}\int_\Omega |\nabla \phi|^2 dV$$
It is clear that $cap_2(F, B_2) \geq cap_2(F, B_3)$.
My question is, how do we prove that $cap_2(F, B_3) \geq C\; cap_2(F, B_2)$, with a constant $C$ independent of $F$?
Answer: Let $F$ be a diffeomorphism between $B_2$ and $B_3$ that is equal to the identity map on $B_1$. Such a diffeomorphism is easily constructed as a radial map $F(x)=g(|x|)x/|x|$ where $g(t) = t$ for $t\le 1$, and $g(2)=3$. Specific form doesn't matter, as long as both $F$ and $F^{-1}$ have uniformly bounded derivatives.
If $\phi$ is a function from the definition of $\operatorname{cap}_2(F,B_3)$, then $\phi\circ F$ qualifies for $\operatorname{cap}_2(F,B_2)$. The chain rule and the change of variable  formula yield
$$
\int_{B_2} |\nabla (\phi\circ F)|^2 \le C \int_{B_3} |\nabla \phi|^2
$$
where $C$ depends only on $F$. The claim follows.

$2$-capacity of a set in $\mathbb{R}^n$


Transformation. Take n out of a root

Question: Im kinda confused. If n is always > 0
$$ (n-a)^{\frac{x}{y}} = n*(1-\frac{a}{n})^{\frac{x}{y}} $$
is that true? Because there were some transformations in recent answers to my threads where I did that.
Comment: No, it's $n^{\frac{x}{y}}\cdot \left(1-\frac{a}{n}\right)^{\frac{x}{y}}$.
Comment: okay so I just missed out the first exponent
Answer: You have the right idea, but you missed one point. the $n$ inside the parentheses is also affected by the outside exponent. What we really have is:
$$
\large(n-a)^{\frac{x}{y}}\\
\large\left(n\left(1-\frac{a}{n}\right)\right)^{\frac{x}{y}}\\
\large\left(n^\frac{x}{y}\left(1-\frac{a}{n}\right)^\frac{x}{y}\right)
$$

Transformation. Take n out of a root


How to prevent a node from listing programmatically?

Question: How can I prevent a node from listing, programmatically? I want to select node by nid. Beacause of some reasons, I don't want to use hook_node_grants() and hook_node_access_records()
I tried to change the _node_access_where_sql() function in the core which creates where clause for use in fetching node listings but $node or $nid is not passed to the function so I can't select node by nid
Comment: Where do you want to stop this content being listed?  In the standard content listing?  It's a REALLY REALLY bad idea to be hacking core...
Comment: Can you tell us more about what you want to achieve?
Answer: Have you tried simply unpublishing the node with Rules? Rules will allow you to programmatically unpublish content based on a variety of factors. Once unpublished, Drupal will not list the node in content with the exception of Views that are not set to only display published content.
What are you using to determine which nodes should be processed by your code?


Orbeon - Email Properties

Question: I want to sent the document id of orbeon form to my email body, therefore I added the following property in my properties-local.xml file
<property  as="xs:string"  name="oxf.fr.resource.*.*.en.email.body"  value="{xxf:document-id()}"/> but this will just display {xxf:document-id()} in my email body, need help please.....
Answer: This is not a feature yet. There is an RFE for it.

Orbeon - Email Properties


Normal Ring and Prime Ideal whose Square is Principal

Question: Let $k$ be a field of characteristic $\neq2$ and consider $R=k[x,y]/(y^2-x^3+x)$. Then
(a) Show that $R$ is normal.
(b) Let $P=(x,y)$ be a prime ideal of $R$. Show that $P^2$ is a principal ideal.
(c) Show that $P$ is not a principal ideal.
I came across this in some commutative algebra reading recently. Here are my thoughts so far (really only for part (c)). Assume that $P$ is generated by $\alpha=f(x)+g(x)y$. Then if $\sigma$ is the nontrivial element in the Galois group, $\sigma(\alpha)$ will generate $\sigma(P)=P$, so the norm of $\alpha$ will generate $P^2$. I thought to compare this supposed generator with the one found in part (b) and then arrive at a contradiction.
Any help with this problem would be appreciated!
Answer: This answer continues the OP's thoughts for part (c).
(c) Let $\sigma:k[X,Y]\to k[X,Y]$ be the $k$-automorphism given by $\sigma(X)=X$, $\sigma(Y)=-Y$ (which is probably the automorphism mentioned by the OP in his attempt). Since $\sigma(Y^2-X^3+X)=Y^2-X^3+X$, we can "extend" $\sigma$ to a $k$-automorphism of $R$. Obviously, $\sigma(P)=P$.
Now note that the elements of $R$ can be uniquely written as $u(x)+v(x)y$ and such an element is in $P$ if and only if $ x\mid u(x)$.
If $P=(xa(x)+b(x)y)$, then $P=\sigma(P)=(\sigma(xa(x)+b(x)y))=(xa(x)-b(x)y)$. It follows $(x)=P^2=(x^2a^2(x)-b^2(x)y^2)=(x^2a^2(x)-b^2(x)(x^3-x))$ and therefore there are $u,v\in k[X]$ and $w\in k[X,Y]$ such that $$X=[u(X)+v(X)Y][X^2a^2(X)-b^2(X)(X^3-X)]+w(X,Y)(Y^2-X^3+X).$$ By taking the degree in $Y$ of both sides we get $w=0$. In the end we have $$X^2a^2(X)-b^2(X)(X^3-X)=1 \text{ or } X,$$ and both cases are clearly impossible.
Answer: a) Regular implies normal.
Okay, maybe that's too high-tech.  If $f=g+hy$ lies in the integral closure, then it satisfies the quadratic polynomial $(z-g)^2 - h^2(x^3-x)$.  If the coefficients are polynomials (which they must be, by Gauss's Lemma), then $g$ is a polynomial, and $h^2 (x^3-x)$ is a polynomial.  But $x^3-x$ is square-free (here we use that the characteristic is not $2$), so $h$ is a polynomial and $f\in R$.
b) Since $y^2,x^3 \in P^2$, it is straightforward that $x\in P^2$ and $P^2 = (x)$.
c) (Note: it is sufficient to address this problem for $R\otimes_k \overline{k}$, so we assume that $k$ is algebraically closed to avoid some technicalities.)
First of all, $X=\operatorname{Spec}k[x,y]/(y^2-x^3+x)$ is an open subset of an elliptic curve $\overline{X} = Y\cup \{\infty\}$.  This is a rather important observation, because it implies that $R=k[x,y]/(y^2-x^3+x)$ doesn't have any principal prime ideals whatsoever (except, of course, for $(0)$).
We will demonstate this, real mathematician-style, by looking at the global behavior of a hypothetical generator of $P$.  If $P=(f)$ is principal, then $f$ extends to a rational function on $\overline{X}$ with a simple pole at $\infty$.  Therefore $1/f$ is a non-constant rational function on $\overline{X}$ with only a simple pole at $P$.  This implies that $l(P) \geq 2$.
Here $l(P)$ is shorthand for the dimension of the space of rational functions on $\overline{X}$ which have at worst a simple pole at $P$, and are regular elsewhere.  In general, $l(D)$ is defined for $D$ a Weil divisor, i.e. a formal sum of points.  For example, $l(P+2Q-3R)$ counts the number of linearly independent functions which must have a triple zero at $R$, and are allowed to have a pole of order $1$ at $P$, and $2$ at $Q$.  The sum of the coefficients of $D$ is called its degree.
We will calculate $l(P)$ exactly using the Riemann-Roch theorem, which says that, for any Weil divisor $D$, $l(D)-l(K-D) = \operatorname{deg}{D} + 1 - g$, where $g$ is the genus of $\overline{X}$, and $K$ is the divisor associated to any differential form on $\overline{X}$.  For an elliptic curve, we must have $K=0$ and $g=1$, so this equation takes the simple form $l(D)-l(-D) = \operatorname{deg}{D}$.
We set $D=P$.  Since $\operatorname{deg}{P} = 1$, and $l(-P)=0$ (in fact, $l(-D)=0$ for any divisor of positive degree), we conclude that $l(P) = 1$.  Since earlier we found that $l(P)\geq 2$ for any principal maximal ideal on $X$ (in fact, the proof works for any projective curve with a single point removed), we have our contradiction.
(The above does have a nice, concrete interpretation: when you strip away the machinery, the argument is that, if $P=(f)$, then the map $k[x]\to R$ sending $x$ to $f$ is an isomorphism.  We use basic facts about divisors to avoid some difficult calculations, and genus to show that $R$ cannot be a polynomial ring.)


Calluses - are they really a necessity for guitarists?

Question: Quite a few times I read on this site about calluses. How they are an important part of being a guitarist. How they help one's playing, how they really can't be avoided.
Fair enough, when I started learning at age 11, I developed terrible things on my fretting fingertips. Due mainly to having  a guitar that had an action far too high for even slide playing, and strings far tighter than I've ever used since, but also due to pressing too hard, as most beginners do.
However, after learning how to set up guitars properly, and discovering lighter strings, although playing and teaching just about every day, haven't had a callus in 50 years. Lighter strings on guitar, but on bass, going down to low B .130s, so maybe the gauge isn't that relevant.
I feel that calluses are counter-productive, in that there's less feeling in fingertips, and hammering on and pulling off is more effectively done using real skin.
So, are they something most players get, and put up with, why do they materialise, are they useful things to have? I can't remember any of my students having them. And - are they of relevance to string bassists (or any other string players)?
Comment: I wouldn't say they are necessary but it's hard not to have them at all and they've never hindered my playing. What would you or anyone reading this do differently depending on the answer to this question? You play just fine without callouses, I play just fine with them. So it doesn't seem to matter much either way.
Comment: I've never really worked with a callous guitarist. I've seen some capricious vocalists, cruel drummers & apathetic bassists, even once an unsympathetic trombonist … but never a callous guitarist :P (Sorry, couldn't resist;)
Comment: @CarlWitthoft - having consulted learned English dictionaries, we both appear to be correct. I am writing from an British English perspective. Other nations may differ.
Comment: @Tim: Fellow Brit here: even in the UK "callus" is the normal spelling for the "hard skin" meaning (see, for example, [here](https://dictionary.cambridge.org/dictionary/english/callus), [here](https://www.collinsdictionary.com/dictionary/english/callus) - both British dictionaries.
Comment: * **callus**   -- unless you intend to be a callous performer
Comment: @Tetsujin - wondered how long it would take. Now I know! Thanks, we need levity more than ever on this site.
Comment: @Tim bastardi**z**e ;)
Comment: @user1079505 Yes, nobody's disputing that! The discussion was about the UK spelling :)
Comment: This seems to be different for everyone. Some people just end up having a bit thicker skin at fretting hand fingertips and others have to deal with callouses.
Comment: @ToddWilcox - what would anyone do differently? I'm wondering whether the strings, or styles of fingerboards, or genres, or any other factors help or hinder. I'm not saying they're good or bad for anyone else, probably not good or me, great for you, but I want to shine some light on the subject. Your dv?
Comment: Shining some light on a topic is not what I believe SE is for. I believe SE is for for finding the best answers to focused questions. I suppose the best answer to this question in one sense is "no", but as far as I can tell, the answer *doesn't matter*.
Comment: @Tim  Oh you Brits with lots of extra "ou" and "iu"  (aluminium) in your words   :-)
Comment: @CarlWitthoft - yeah, we gave the world English, only for nearly everyone to bastardise it..! (As if it wasn't already!)
Comment: I don't know what exactly you mean by 'necessary'. Either you get them or you don't. It's no sin either way. I certainly had them as a young player, as I took up the 12-string very early, and they probably lightened off as my instruments improved. Don't have any now to speak of but then I don't play much now.
Comment: As an untrained percussionist I either needed them, electrical tape, or both, otherwise they went straight to being blisters.
Comment: @psmears Merriam-Webster (American dictionary) gives "callus" for noun, and "callous" for an adjective. So if you have calluses, your fingers are callous. https://www.merriam-webster.com/dictionary/callus https://www.merriam-webster.com/dictionary/callous
Comment: @psmears - either or either will suffice. According to my dictionaries. But this isn't the site for these discussions anyway!
Comment: @Tim - you're right, it isn't the right site - which is why I'd suggest editing to use the more common "callus" spelling, even though either is acceptable, because using the less common one is only going to invite further discussion :)
Comment: Also, if you really dislike calluses, you can switch over to [nylon strings](https://en.wikipedia.org/wiki/Classical_guitar) ;)
Answer: I don't have full calluses, but my fingertips are definitely harder when I play regularly than when I go for a couple of months without playing.
I find the harder skin really helps hammer-ons be precise and sharp, and they don't seem to take away from sensitivity.
I guess it shouldn't matter much either way - you obviously do fine without any, I have harder skin, others have calluses. People seem to play fine :-)
Answer: I'm a full time guitarist.  When I was young I couldn't afford good instruments, so my guitars fought me all the time, and I had really thick calluses - if I tapped my fingertips against a glass you would have thought they were metal from the sound.
Now I have good instruments that are properly maintained, so even though I play for hours every single day my calluses are barely noticeable.
In my view, calluses are useful to a degree: your fingertips have to get a clear sound from a fretted note.  The softer your fingertips are, the harder you'll have to press to do that.  And that means more tension in your hand, and tension is counter-productive for speed and accuracy.
Having some callus can be useful if you need to play an instrument that isn't in good shape, has higher string tension, or has rougher windings - a few months ago I played bass for a night, and I ended up with blisters on two of my fingers, because I needed to use more pressure than my fingers were used to for about three hours straight.
Comment: @nick012000 The calluses form on the fingertips of the fretting hand with guitar, due to pressing down the strings and sliding over them. Not the picking hand. Although maybe if you play fingerplucking style instead of using a guitar pick you also develop calluses on that hand. With the violin you'd use the same hand for pressing down the strings as you would for guitar, while the other hand bows or picks.
Comment: @G_H Calluses on the thumb of the picking hand are relatively common, and while playing a bass guitar, I've had harder skin on my picking thumb than any of the fingers on the fretting hand. YMMV, of course :)
Comment: I find this very interesting. It might be considered a separate question but this answer comes close enough to answering it so I'll just post it as a comment: is development of pronounced calluses on the fingertips indicative of a bad setup or applying too much pressure? Or excessively long practice sessions? Specifically for electric guitar playing? I've played violin for a long time and never came close to getting calluses or even hardened fingertips from it. Violin strings have a rather low action and tension (I think) compared to guitar strings. Maybe that's desirable in a guitar as well?
Comment: @G_H Violins are played with bows rather than your fingertips, aren't they?
Comment: @G_H calluses tend to be harder for acoustic players than electric, because they use thicker strings.  To my hands violin strings seem very "soft" compared to guitar strings.
Answer: My perspective being an upright and electric bassist as well as a guitarist is this, and it is a bit more related to bass, which has been the instrument I have played most for the last 2 decades or so (4 decades, who am I kidding?):
When I was much younger I played harder and with higher action. I did have visible calluses on most if not all of my left and right hand fingers. They did not hinder my play in any way, if anything they helped since they offered some protection against the constant pressure and friction I was generating.
As I matured and realized my bass didn't need to be heard acoustically over a drum set by the back row of a venue, my playing became more refined. I dug in less and lowered my action some to facilitate fast technical and upper register playing. It is very important to me to draw sound out of an instrument and not rely on an amp for my fundamental tone so I still play physically but more controlled.
The result over the years is that my "visible" calluses have pretty much vanished. One aside which may or may not be relevant is that I put a very small amount of petroleum jelly on my fingertips when I play. This may or may not contribute to the appearance of the calluses, I have been doing it for literally decades so I can't say for sure. I can say I NEVER get cuts from dryness on my fingertips and I live in the desert.
Back to the topic at hand, the reason I say "visible" is because if one plays a string instrument there definitely will be some toughening and or hardening of the skin below the surface over time. I don't know if that fits the definition of calluses or not but I have that for sure. I believe this tough under the surface skin is absolutely necessary and is even better than calluses because it helps prevent blisters and pain but doesn't add potential friction from a thick layer of dead skin on the fingertips.
I also believe that as individuals calluses are something that some of us will get and some won't. I don't believe they either help or hurt. It is something we cannot A/B to see the difference. How way we play and how our instruments are set up will play a role but it is not something we can control without a conscious effort to change the way we play. We will either have them or we won't.
Answer: I climb rocks and play viola and guitar. No matter how much I neglect any of these things, I have little finger-tip callouses.
When I started on viola, I bled. As my geometry changed, my fingers got stronger and more nimble and I gained an intuitive sense of the (left hand) finger pressure needed for good tone.
The guitar is a different beast! Picking an electric guitar with really loose strings or strumming a classical guitar doesn't compare to finger picking a steel string acoustic with a high bridge.
When I play consistently for a month, the callouses get noticeable for a bit and then disappear except where they are needed (the callouses on my fingertips and my "Barre finger" end up a bit bigger).
I also climb. I mention this because chalk (required for most climbers) causes my callouses to get thick and painfully tear off. Everybody's hands have a different moisture level. Big, painful callouses may mean your skin is dry. I also mention this because my callous pattern changed drastically as I improved. My bad technique strained my skin.
Callouses are the skin's reaction to repeated stress. We should set young players up for success with well-adjusted instruments. Players should practice in the physically easiest way possible. Players should listen to their body to avoid injury and rest.
Callouses are as necessary as coughs. It's better to not get sick and you can clear your throat in less damaging ways, but sometimes we all breathe a little water. You'll never get rid of all callouses and it's probably not helpful to ask somebody to try.
Comment: Climbing rocks is hard enough by itself. Playing viola *and* guitar as well? Having four arms would help a bit, maybe..?
Comment: @Tim 6 by my count. But I am not good enough to do these things in parallel. :-)
Answer: You will develop what you need for the style you play.  I have been a working guitarist for several decades.  Every teacher I had would say that you should expect to develop calluses.  Clearly if you over play or have a bad set up you might develop more than you really need but that is exactly what you get for the set up you have.  I think there are certain styles and techniques that will cause callus development.  One example for me is playing blues (real blues, not bluesy jazz or rock).  If I bend high and hard those fingers will get callused.  Classical causes callus development.  Many guitarists here will assert that you don't need them but will describe their set up and style and clearly if you have gauge 8 strings with low action and use all four fingers to bend one note you are avoiding the actions that might causes callus development.  But this is a personal choice and not a matter of right or wrong, true or false.  Your question "are they really a necessity for guitarists" is not answerable.  It depends on style, set up, and technique.
I would also say that when my classical playing develops a different callus than my electric playing.  They two sometimes compete with each other.
Answer: I disagree that calluses are not necessary to play. I think it depends how strong your fingers are— if you're a guy and you have a lot of strength you may not need as much callus. sure you can go with a lighter gauge string but you may get reduced sound quality. Over the years, I found the calluses have provided me w/ significant flexibility and increased sound in terms of bending, sliding and hammer ons particularly when playing acoustic guitar.  A Strat with extra light gauge strings? Not so much but…it's still helps.
Comment: Calluses have nothing to do with muscle strength. They're patches of hardened skin. Nothing deeper than that.
Comment: Strength and calluses are not related, in any way. Making this answer inaccurate.
Answer: Sand is not required to have shoreline or a beach; it is a natural function of the passage of time and weathering.
Comment: It's saying that you don't need to worry about wether or not you should build calluses in order to be able to play the guitar, as they occur simply as a result of playing.
Comment: That's quite philosophical, but not particularly relevant.


Render multiple components in React Router

Question: I'm used to application layouts with multiple yield areas, i.e. for content area and for top bar title. I'd like to achieve something similar in React Router. For example:
<Router>
  <Route path="/" component = { AppLayout }>
    <Route path="list"
           component = { ListView }
           topBarComponent = { ListTopBar }/>
  </Route>
</Router>

AppLayout:

    { -- display ListTopBar here -- }

    { -- display ListView here -- }

Both child components should receive the same props.
How can I approach this?
Answer: To passe multiple component you can do like this :
<Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}} />
<Route path="users" components={{main: Users, sidebar: UsersSidebar}}>

See the doc here :
https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components
Comment: Link link is broken. It should be: https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components
Answer: In v4, according to the docs, you can render multiple components like this:
<Route path='/some-path' render={() =>
  <Fragment>
    <FirstChild />
    <SecondChild />
  </Fragment>
} />

Comment: Shouldn't the prop for this be `path='/popular'` instead of `to='/popular'` ?
Answer: Instead of using div's you can use Fragments.
`
<Route path='/some-path' render={props =>
  <Fragment>
    <Child 1/>
    <Child 2/>
  </Fragment>
} />

`
Answer: You can also use Array in latest versions of React-router-dom;

<Route path="groups" element={[<Component1/>,<Component2/>]} />

Will work just fine.
Answer: To render multiple components you can do this:
<Route
    path="/EditEmployee/:id"
    render={(props) =>

            <NavMenu />
            <EditEmployee {...props} />

    }
/>

Here I'm passing parameter to specific conponent.
Answer: //this is the simplest method to render multiple components and it works for me
<Router>
  <Route path="/">
       <ListView />
       <ListTopBar />
  </Route>
</Router>

Answer:

 <Route path='/' element={<> <Home /></>} />

This worked for me in the latest react router dom v6
Answer: Another method is within the render method of route multiple passed components can be created using react.createElement
<Route render ={(props)=>React.createElement(Component1, {...props}},
                     React.createElement(Component2, {...props}}/>

Answer: What worked for me was to wrap the multiple components in a <Fragment> or a
 as a parent element.

  return (
    < Router>

        <Routes>
          <Route path='/'
            element={
              <Fragment>
                  < NavBar />
                  < NewsLetterCard />
                  < TestimonialsCard />
                  < ServicesCard />
                  < ContactsCard />

              </Fragment>
            }
          />
        </Routes>

    </Router>
  );
}

Answer: For v6, where you are using Routes instead of Switch to render your components. This works:
<Router>
<Routes>
<Route path='/' element={<><Child1/> <Child2/></>} />
</Routes>
</Router>

But for v5, this works:
<Router>
<Switch>
<Route path="/">
   <Child1/>
   <Child2/>
</Route>

Answer: This seem to work for me, I needed to add canvas animation component as background under homepage ("/") only:
import Page from 'pages/Page';
import Blog from 'pages/Blog';
import Post from 'pages/Post';
import Category from 'pages/Category';
import CanvasParticles from 'components/canvas/CanvasParticles';

...
<Routes>
  {['/', '/:slug'].map((path, index) => {
  return path === '/' ? (
   <Route
    exact
    path={path}
    element={[<CanvasParticles />, <Page />]}
    key={index}
   />
  ):(
   <Route path={path} element={<Page />} key={index} />
  );
 })}
 <Route exact path="/blog" element={<Blog />}></Route>
 <Route path="/blog/:slug" element={<Post />}></Route>
 <Route path="/category/:slug" element={<Category />}></Route>
</Routes>

Answer: click on this you can view a image v6 feature :  this is the simplest method to render multiple components and it works for me
Main Concept is to you should wrap with element
<Route path="/" element={<>  </>}
or
wrap with in Fragment
<Route path="/" element={  }
Comment: https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32221645)


Pass ethernet interface to iptables rule in ansible playbook

Question: I'm writing a pretty simple ansible playbook for setting up our iptables firewall in centos.  Here is the playbook I wrote:
<code>---
- hosts: test
  remote_user: deploy
  sudo: True
  tasks:
  - name: Get iptables rules
    shell: /sbin/iptables -L
    register: iptablesrules
    always_run: yes
  - name: Add nginx iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Nginx_HTTP"
    when: iptablesrules.stdout.find("Nginx_HTTP") == -1
  - name: Add nginx ssl iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 443 -j ACCEPT -m comment --comment "Nginx_SSL"
    when: iptablesrules.stdout.find("Nginx_SSL") == -1
  - name: Add postgres rule on ham0 interface
    command: /sbin/iptables -I INPUT -p tcp -s 0/0 --sport 1024:65535 -d 0.0.0.0/0 --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT -m comment --comment "Postgres"
    when: iptablesrules.stdout.find("Postgres") == -1
  - name: save iptables
    command: service iptables save
  - name: ensure iptables is set to start at boot
    action: command /sbin/chkconfig iptables on
</code>
Everything works as expected although I'm sure it can be better.  But my question is regarding the Postgres rule.  I want to dynamically replace the destination address of 0.0.0.0/0 with the IP of a specific interface (ham0) on the target box.  I'm assuming I can do something like ansible_ham0.ipv4.address to get the IP address.  But I'm not sure how to pass that into the Postgress rule as a variable.
I'm reading the documentation and having a bit of a hard time with it.  I'll keep researching but in the interim if anyone has an idea of how to do this, I'd really appreciate the help.
Comment: Make your life simpler, and use firewalld (on C7).
Comment: @MichaelHampton Thanks for the tip!  We are on 6.5 but I will definitely look into it. :)
Answer: Sorry for the quick Q&A, but I figured this out with a little tinkering.
Here is my updated playbook.  Hopefully it helps someone else!
<code>---
- hosts: test
  remote_user: deploy
  sudo: True
  tasks:
  - name: Get iptables rules
    shell: /sbin/iptables -L
    register: iptablesrules
    always_run: yes
  - name: Add nginx iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Nginx_HTTP"
    when: iptablesrules.stdout.find("Nginx_HTTP") == -1
  - name: Add nginx ssl iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 443 -j ACCEPT -m comment --comment "Nginx_SSL"
    when: iptablesrules.stdout.find("Nginx_SSL") == -1
  - name: Add postgres rule on ham0 interface
    command: /sbin/iptables -I INPUT -p tcp -s 0/0 --sport 1024:65535 -d {{ansible_ham0.ipv4.address }}  --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT -m comment --comment "Postgres"
    when: iptablesrules.stdout.find("Postgres") == -1
  - name: save iptables
    command: service iptables save
  - name: ensure iptables is set to start at boot
    action: command /sbin/chkconfig iptables on
</code>


How to make GtkMenuToolButton open the same menu when 'clicked' signal is emitted?

Question: I am using GtkMenuToolButton and it has a button and a menu. When you click on the arrow the menu is opened. I'd like to make the button open that same menu as well. Simply emitting "show-menu" in the "clicked" callback did not work. Please help how to make this work.
Answer: When you create the menu, save a reference to it as self.tool_button_menu or something; then in the clicked callback, call
self.tool_button_menu.popup(None, None, None, None, 0, Gtk.get_current_event_time())

The first two Nones are the parent menu and the parent menu item (not applicable). The second two Nones are a positioning callback function (more on that in a minute) and data to pass to it. 0 is the mouse button if the menu was initiated by a mouse button press (but you should pass 0, because I think in your case it's either a mouse button release or a key press.) And the last parameter is the timestamp to give to the menu popup event.
Now the positioning function. It takes two parameters and returns three:
def positioning_function(menu, data=None):
    # ...magic...
    return x, y, push_in

push_in should be True if you want the menu to be repositioned so that it always fits on the screen. Seems like a good idea. You can get good values for x and y by looking at the tool button's get_allocation(); read the x, y, width and height attributes of that object and calculate a nice place to put the menu.
Comment: well the actual parameters to popup would be nice, as I can't seem to get them right. Also the menu needs to be below the button not in the random mouse position (think about activating the button with keyboard, not mouse). The existing snippets with popup that I found on the internet did not work with py-gi bindings and gtk3. Please elaborate =)
Comment: Ha, you caught me there. I was too lazy to look up the parameters. I'll edit my answer.
Comment: That's better. I went with "my solution" below =) but thanks for explaining the "magic" parameters for this stuff.
Answer: I have currently ended up doing this:

Instead of GtkMenuToolButton I have GtkToolItem with custom content
In custom content I have GtkMenuButton
Inside that one, I delete the default GtkArrow and replace it with 1x2 GtkGrid which has a Label + GtkArrow

As a whole it does what I want =)


What's the advantage of using express' session over the HTML5 global sessionStorage object?

Question: My understanding is that, in apps using express on top of node, the session object can be accessed through req.session, which can have any number of key/value pairs set on it.
What's the advantage of using this method over storing key/value pairs on the global sessionStorage object in the DOM?
Answer: There are several advantages:

express.session stays on your server, so you can store things there that won't be accessible to the client
express sessions don't have storage limits
Storing things in the DOM mean you'll have to transmit everything over the wire, incurring extra bandwidth costs.


What is the fastest way to check if two given numbers are coprime?

Question: One way is to calculate their gcd and check if it is 1.
Is there some faster way?
Answer: The Euclidean algorithm (computes gcd) is very fast. When two numbers are drawn uniformly at random from [1, n], the average number of steps to compute their gcd is O(log n). The average computation time required for each step is quadratic in the number of digits.
There are alternatives that perform somewhat better (i.e., each step is subquadratic in the number of digits), but they are only effective on very large integers. See, for example, On Schönhage's algorithm and subquadratic integer gcd computation.
Comment: I'd like to comment that it's a bit coarse to measure complexity of arithmetic algorithms without taking costs of arithmetic operations into account.
Comment: The worstcase # of steps is O(log n) as well, when two numbers are successive entries in the Fibonacci sequence.
Comment: @Pavel Shved: I did take the cost into consideration. cf. the sentence "The average computation time required for each step is quadratic in the number of digits."
Answer: if you're running on a machine for which division/remainder is significantly more expensive than shifts, consider binary GCD.
Comment: Just implemented this in f# and its more than 2x faster than traditional Euclid's GCD, cannot give exact numbers as there is other code poluting my measurements, however its > 2x faster.  Good find Jason.
Comment: Update: Did better numbers in isolation:  Iterations: 100000, Euclid Took: 27ms, Binary GCD Tool: 11ms (so that's about 40%  of Euclid). Awesome!
Comment: @gatapia Care to do a `gist` of your F# ?
Comment: @javadba check out [here](https://github.com/gatapia/guidos_proj_euler/blob/b1eff7cfc7da6c2a895a782163411f2999763b0b/ProjEuler/Utils.fs) last function called binGcd


Append() Ajax not working

Question: I'm trying to append content to an Element with append(load()), but it's not working.
$('#id').append(load('page.html'));

Is there any other way to do this? Or is there any mistake in this code?
Comment: Use only .load('page.html')
Answer: Your usage of the .load() method is not correct, also .load() method doesn't append the loaded contents, it overwrites the previous contents, you should use $.get() or $.ajax() function instead:
$.get('page.html', function(data) {
   $('#id').append(data);
});

Answer: The load function actually inserts the content into the matched element. You don't have to manually append the content.
All you'll have to do is specify the element you want to populate and call the load method on it:
$( '#id' ).load( 'page.html' );

References:

.load()
Answer: The load method doesn't return elements that you can append, it loads content into an element. If want to append the content, append an empty element that you can load the content into:
var e = $('
');
$('#id').append(e);
e.load('page.html');

If the element is initially empty, so that it doesn't matter if you append or replace the content, you can just load the content into the element:
$('#id').load('page.html');

Answer: You need to call load() on jQuery object, call $(selector).load() The load would be undefined the way you are trying to call if it is not a user defined function.
$('#id').load('page.html');

Comment: SE management discourages people giving reasons for downvoting. (I really need to find that meta page...) @Lix: The correct response to a simple, obvious typo is to edit and fix it.
Comment: Well that was a typo.
Comment: It would be better if down voter have given the reason
Comment: @adil - in some cases yes. But in the case where someone posted an answer without proof reading the content - I'm not sure...
Comment: @Lix, I have added the description about the possible problem.
Comment: @T.J.Crowder - I don't want to encourage the FGINW problem. One should proof read their answers before posting. A spelling mistake would have been fixed - but not a code error (no matter how small).
Comment: @Lix, If one tell about the typo in code in the answer then would it be good or bad?
Comment: @Adil - the code you posted was so small - less than one line if you ask me... I think you would have seen it had you re-read the post before submitting...
Comment: @Lix, Do you mean for big code pointing typo is right and for small code pointing typo is wrong?
Comment: @Adil - with a bigger code sample, it is conceivable that someone might overlook something while considering the logic behind the code. So yes.. for more code I think I would have said something... the code you posted was so small I really didn't feel that much effort was put into the answer (hence my initial downvote - which has since been removed).
Comment: I was expecting yes or no for my question. "for small code pointing typo is wrong?" yes or no ?
Comment: @Adil - not everything is black and white... It all depends. As a high rep, veteran user I'll look at your content in a different way than I would look at a new users first post. I do expect better quality from more experienced users.
Comment: I agree every thing is not in black and white but we can try to make it. Do you mean "for person with high reputation having small code pointing typo is wrong?" yes or no?
Comment: @Adil - If you agree with me on that then we can leave this conversation as it is. I'm not going to give you a yes/no answer after we can see that we both agree there can be no single yes/no answer.
Comment: We can leave this but I belive this particular situation can have answer in Yes or No.

Append() Ajax not working


CSS - Como evitar conflitos de múltiplos arquivos?

Question: Situação
Eu tenho vários arquivos css, alguns meus, outros de bibliotecas.
Duvida

Qual o melhor meio de bloquear o css externo para determinados elementos?

Exemplo
Efeito Atual

/***** CSS EXTERNO *****/
form div{
  padding: 5px;
  clear:both;
}

/***** OUTRO CSS EXTERNO *****/
div div{
  margin: 10px;
}
div label{
  font-size: 20px;
}

/***** MEU CSS *****/
.content-form>div{
  border:1px solid #CCC;
  float:left;
  min-width:50px;
  min-height:10px;
  text-align:center;
}
.content-form>div>label{
  color:blue;
}

  <form class="content-form">

      Item 1

      Item 2

      Item 2

      Item 3

  </form>

Note que aqui os css externos estão interferindo no resultado que eu desejo, para o css que eu montei.
Efeito Desejado

.content-form>div{
  border:1px solid #CCC;
  float:left;
  min-width:50px;
  min-height:10px;
  text-align:center;
}
.content-form>div>label{
  color:blue;
}

  <form class="content-form">

      Item 1

      Item 2

      Item 2

      Item 3

  </form>

Nota

Eu não posso remover os arquivos, pois alguns css são usados um outros lugares
Eu não posso remover os css específicos, pois eles são usados em outros elementos, apenas quero inativá-lo para aquele elemento especifico.

Tentativa atual

/***** CSS EXTERNO *****/
form div{
  padding: 5px;
  clear:both;
}

/***** OUTRO CSS EXTERNO *****/
div div{
  margin: 10px;
}
div label{
  font-size: 20px;
}

/***** MEU CSS *****/
form.content-form div{
  padding:0;
  clear:none;
}

div .content-form div{
  margin:0;
}
div .content-form div label{
  font-size:inherit;
}

.content-form>div{
  border:1px solid #CCC;
  float:left;
  min-width:50px;
  min-height:10px;
  text-align:center;
}
.content-form>div>label{
  color:blue;
}

  <form class="content-form">

      Item 1

      Item 2

      Item 2

      Item 3

  </form>

Note que aqui eu estou basicamente sobrescrevendo todo o css externo.
Comment: Tenta trocar a posição de inclusão deles. Isso também afeta.
Comment: @WallaceMaxters sim, mas só se for a mesma sentença tipo `file1 - div div{}`, `file2 - div div`, ai o segundo sobrescreve o primeiro, o problema é que é a especificidade que cada arquivo esta dando. `file1 - div div{}`, `file2 - form div{}` ai ele interpreta como coisas diferentes e gera um "merge", o que não é desejado.
Comment: Por qual motivo você não pode remover alguns arquivos? Não é possível também gerar um único arquivo, unindo e removendo estilos? Você não pode nem modificar os nomes? Pois a especificidade de cada elemento está muito ampla, acredito que esse seja o maior ponto negativo.
Comment: @CelsomTrindade eu determinados momentos outros elementos são renderizados e usam o mesmo css e se aplicam corretamente, contudo para o elemento que estou querende renderizar ele também se aplica e não é o que desenho, desta forma estou gerando um código de sobrescrita, contudo gostaria de saber se tem algum jeito melhor.
Comment: Eu pelo menos desconheço alguma técnica que não seja de sobrescrever quando utilizamos outro arquivo `css`, a não ser a ordem de chamada dos arquivos, como já mencionado pelo @WallaceMaxters . Nesse caso, acredito que você deve realmente criar regras que sobrescrevam as propriedades desejadas.
Comment: Apesar de não ser projetado pra isso, você pode usar o operador `!important` para dar mais enfase na regra desejada
Answer: Guilherme, quando temos classes do CSS mal estruturadas e não podemos alterar a organização do mesmo, então só nos resta uma opção, criar um Shadow DOM e isolar o HTML/CSS de uma parte da pagina.

var container = document.getElementById("container");
var root = container.createShadowRoot();

while (container.lastChild) {
  root.insertBefore(container.lastChild, root.firstChild);
}
/***** CSS EXTERNO *****/
form div{
  padding: 5px;
  clear:both;
}

/***** OUTRO CSS EXTERNO *****/
div div{
  margin: 10px;
}
div label{
  font-size: 20px;
}

  <form class="content-form">

      Item 1

      Item 2

      Item 2

      Item 3

  </form>

Comment: Cara que legal essa função, isolar o css de uma parte da página... +1
Comment: Mas ao criar essa mesma regra de `css` dentro de um arquivo que seja inicializado após o arquivo de `css` padrão, não daria o mesmo resultado?
Comment: Nosso nunca vi, muito interessante +1, por hora :D
Comment: Isso seria similar a um `iframe`?
Comment: @GuilhermeLautert, é um pouco mais complicado, você pode ler mais a respeito em: [Shadow DOM 101](http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/).
Comment: Mas em resumo, tanto o [`Shadow DOM`](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM), quanto o [`Template`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) são recursos do HTML5, você pode combinar os dois para criar `Web Components`


Show the following is a group $a * b=a+b+ab$

Question: Let $S=\mathbb{R}\setminus \{-1\}$. Define $*$ on $S$ by $a*b=a+b+ab$.
This feels fairly straightforward but it is just the details of which approach is valid that is throwing me. My attempt:
We first check for associativity by considering $a*(b*c)$
$a*(b*c)=a+(b+c+bc)+a(b+c+bc)=a+b+c+bc+ab+c+abc=(a+b+ab)+c+(a+b+ab)c=(a*b)*c$
We now look for an inverse. Consider $(a*b)=a \Rightarrow a+b+ab=a \Rightarrow b=0$ and so $0$ is the identity element.
Now the trouble starts for me. We search for an inverse giving $(a*a^{-1})=0=a+a^{-1}+aa^{-1}$ Coming at this I am always defining an inverse in terms of itself. I have written out some integer cases but I am not sure how to apply them in general.
Searching for closure is also problematic for me. We essentially want to show that taking $x,y \in S$ then $x+y+xy\neq -1$ but I run into similar problems as above. Thanks for the help!
Comment: Instead of verifying all of the axioms you'd do better to show that this is isomorphic to a more familiar group. Hint: $1 + a + b + ab = (1 + a)(1 + b)$.
Comment: I am not yet able to use isomorphisms so I need to verify this via the axioms.
Answer: Suppose $a*b=0=ab+a+b$ then $$(a+1)b=-a$$ so that $$b=-\frac a{a+1}$$is uniquely defined, and you can see why you need to exclude the value $1$ in the definition.
Comment: I feel rather dense for missing this.
Answer: About the closure:
\begin{align}
x+y+xy = -1 &\iff 1+x+y+xy = 0 \\
& \iff (1+x)(1+y)=0 \\
& \iff 1+x=0\lor 1+y=0 \\
& \iff x=-1\lor y=-1
\end{align}


Replace corresponding rows in a column with non-missing corresponding rows from another column

Question: I want to use all non-missing rows from one column to replace corresponding rows in another column. The data set is from an Excel workbook. The data look like this, say, about 450,000 rows of data across 12 columns.
A B
a1 b1
.  b2
.  b3
a4 b4
a5 b5

Here I have lots of nonmissing values in B, and I want to use them all to replace corresponding rows in A, regardless of whether the rows in A are missing or not. The data in B also have missing values as well, which I won't use.
Imagine my data in B are updated data, and I want to "update" corresponding rows in A with such information. For any non-missing rows in column B, I want to use them to replace corresponding rows in column A.
I run this code:
data['A'][data['B'].notnull()] = data['B'][data['B'].notnull()]

There is always a memory error, together with the warning:
"SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame...".
What's the best way to get around this memory error?
Thank you very much!
Answer: New Answer
data.A.update(data.B)

demo
data

     A    B
0   a1   b1
1  NaN   b2
2  NaN   b3
3   a4  NaN
4   a5   b5

data.A.update(data.B)
data

    A    B
0  b1   b1
1  b2   b2
2  b3   b3
3  a4  NaN
4  b5   b5

setup
txt = """A B
a1 b1
.  b2
.  b3
a4 .
a5 b5"""

data = pd.read_csv(StringIO(txt), delim_whitespace=True, na_values='.')

Old Answer
You can simply use fillna if those . are truly missing.  The inplace=True will update the existing data
data.A.fillna(data.B, inplace=True)

If they are in fact '.' then you can use replace
data.A.replace('.', data.B, inplace=True)

0    a1
1    b2
2    b3
3    a4
4    a5
Name: A, dtype: object

Comment: What I want to do is to use all non-missing rows from B to replace all corresponding rows (regardless of whether they're missing or not) in A. I ran your code, but the result doesn't seem to be what I want. Thanks anyway.
Comment: Thank you so much! Your code, data.A.update(data.B), did exactly what I wanted to do.
Answer: It's easy:
data.ix[data.B.notnull(), 'A'] = data.ix[data.B.notnull(), 'B']

Comment: But it works only for missing rows of A, whereas I want to use all nonmissing rows of B to replace corresponding rows of A, regardless of whether such rows of A are missing or not. The idea is to use nonmissing rows of B as updated data to replace corresponding rows of A, which can be considered outdated data.
Comment: then its normal to have a warning. everything is OK dont worry about that


get Mutual Friends on following and followers relation table

Question: How can I get a mutual friend SQL query?
my Sql
But i can not get Mutual Friends

id | user_id
--------------
1   |  2
2   |  3
3   |  4
4   |  1

Relation Table

id  | follower_id | following_id
--------------------------------
1   | 1          | 2
2   | 2          | 1
3   | 1          | 4
4   | 4          | 3
5   | 4          | 1

Following Query
"SELECT `user_id` FROM " . T_USERS . " WHERE `user_id` IN (SELECT `following_id` FROM " . T_FOLLOWERS . " WHERE `follower_id` = {$user_id} AND `following_id` <> {$user_id} AND `active` = '1') AND `active` = '1' ";

Follower Query
" SELECT `user_id` FROM " . T_USERS . " WHERE `user_id` IN (SELECT `follower_id` FROM " . T_FOLLOWERS . " WHERE `follower_id` <> {$user_id} AND `following_id` = {$user_id} AND `active` = '1') AND `active` = '1'";

Comment: Edit your question and provide sample data *and* desired results.  What does "mutual friend" mean?  Is "friend" somehow related to the concept of "following" or "follower"?
Answer: SELECT `user_id` FROM " . T_USERS . "
 WHERE `user_id` IN (SELECT CASE WHEN `following_id`={$user_id} THEN `follower_id` ELSE `following_id` END user
                       FROM " . T_FOLLOWERS . "
                      WHERE `active` = '1'
                        AND ((`follower_id` = {$user_id} AND `following_id` <> {$user_id})
                          OR (`follower_id` <> {$user_id} AND `following_id` = {$user_id}))
                      GROUP BY user
                     HAVING count(*)=2
                    )
   AND `active` = '1'

Comment: this means all friends bt i need mutual friend between 2 user


Product of varieties in is a variety?

Question: I know that the question may look similar to this: Is fibre product of varieties irreducible (integral)?, but I am forced by the context to use a different definition for variety.
Definition. Let $K$ be a field (not necessarly algebraically closed), and $X$ a scheme over $K$. Then $X$ is a variety if it is separated, of finite type, and geometrically integral.
Assume that $X$ and $Y$ are two varieties. Is it true that $X\times_K Y$ (the scheme-theoretical fiber product) is a variety? (Of course in the sense of the previous definition).
If you are able to find a clear reference for this, it would be better than an explicit argument.
Comment: Yes – crucially we need $X$ and $Y$ to be _geometrically_ integral. That allows us to reduce to the case where the base field is algebraically closed.
Answer: Here is a reference: on page 136 of the book of Görtz-Wedhorn, Proposition 5.51 (ii) says that a $k$-scheme $X$ is geometrically integral over $k$ if and only if for every integral $k$-scheme $Y$, $X\times_kY$ is integral. This doesn't quite give you what you want immediately, in that there is still an argument to be made, but this is the key ingredient. The fact that $X\times_kY$ is separated and of finite type over $k$ is standard, and presumably not the main point of your question. By the aforementioned result, it is integral. Why is it geometrically integral? Remember we are assuming $Y$ as well as $X$ is geometrically integral over $k$. For any extension $K/k$, $(X\times_kY)\times_k\mathrm{Spec}(K)=(X\times_k\mathrm{Spec}(K))\times_k(Y\times_k\mathrm{Spec}(K))$. Since $X$ is geometrically integral, $X\times_k\mathrm{Spec}(K)$ is as well (geometric integrality is a definition which is obviously insensitive to an extension of the base field), and since $Y$ is geometrically integral, $Y\times_k\mathrm{Spec}(K)$ is in particular integral, so, invoking the result again, we get that $(X\times_kY)\times_k\mathrm{Spec}(K)$ is integral. As $K$ was arbitrary, we win: $X\times_kY$ is geometrically integral, and hence a variety in the sense given.

Product of varieties in is a variety?


Are random forests Bayesian?

Question: Hopefully my naivety doesn't shine through in this question: Are random forests Bayesian?
Comment: I had the same question.
Answer: Not really.
Random Forests are closer to bootstrapping (there is a bootstrapping piece in the random forest fit).
Bootstrapping can be seen as a Bayes analysis with a very specific prior and only looking at summaries of the posterior, but using a specific prior (that matches frequentist output) and not looking at the whole posterior does not really follow the philosophy of Bayesian analysis.

Are random forests Bayesian?


Serialize DetachedCriteria with nHibernate

Question: I am trying to serialize a DetachedCriteria so I can save it in a database and reuse the same criteria at a later date. When I run the code below I get "NHibernate.Criterion.DetachedCriteria cannot be serialized because it does not have a parameterless constructor".
DetachedCriteria criteria1 = DetachedCriteria.For<SecurityObjectDTO>("so")
    .Add(Expression.Eq("ObjectCode", "1234"));

XmlSerializer s = new XmlSerializer(typeof(DetachedCriteria));
TextWriter writer = new StringWriter();
s.Serialize(writer, criteria1);
writer.Close();

Is there any good way to serialize a DetachedCriteria?
Comment: So the user can create a criteria which I can then save in the database for later reuse.
Answer: I've run into something similar before.  My first thought was to subclass DetachedCriteria so you could provide a default constructor yourself.  However, after digging through the DetachedCriteria class, I don't think this will work.  The reason is the CriteriaImpl class, used internally by DetachedCriteria, is also lacking a default constructor.
Looking at XmlSerializer, it doesn't look like it will work if your object doesn't have a default constructor.
I ran into this post, however:
How do I serialize an NHibernate DetachedCriteria object?
Based on that, this might work (I haven't tested it, however):
// Convert the DetachedCriteria to a byte array
MemoryStream ms = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, detachedCriteria);

// Serialize the byte array
XmlSerializer s = new XmlSerializer(typeof(byte[]));
TextWriter writer = new StringWriter();
s.Serialize(writer, ms.Buffer);
writer.Close();

Comment: As an aside, I'd think about finding an alternate way to represent your criteria.  If you could represent it as a string or XML value, then you could greatly simplify your serialization process.
Comment: What about deserializing to DetachedCriteria?


Where are the docker daemon logs stored on ubuntu 16.04 xenial xerus?

Question: I expected to find the logs in /var/log/upstart or /var/lib/docker but had no such luck. I'm trying to debug a docker-compose issue and it'd be extremely helpful to know what API calls are being made behind the scenes.
Comment: Ubuntu 16.04 is systemd and not upstart. You can view logs with `docker` commands or `systemd` commands like `journalctl`.
Comment: I'm voting to close this question as off-topic because it doesn't directly relate to programming. It be appropriate on the Ask Ubuntu or Unix & Linux StackExchange sites.
Answer: You can check these places:

journalctl -u docker for docker logs in the systemd journal
journalctl | grep docker for system logs that mention docker
docker logs CONTAINER for logs of a container named CONTAINER
Comment: Although useful, this doesn't answer the question. Where are they stored?
Answer: And to tail it you can use the following :
journalctl -u docker -n -f

Comment: I don't have enough reputation.
Comment: This is not an answer to the original question.  It should be added as a comment against the question.


Visual Studio Form Design

Question: I received an error page on my form design view and don't know what to do with it. I've included a .jpg of the error page. I went to the Help link on the page, but it only took me to the start page of Visual Studio. Does anyone know what to do in the case of an error like this?
I lost data when I got the error initially, and now methods used in the form design don't have a reference; for instance, the Load method no longer is valid on my code page. If anyone has an idea of what namespace I may be missing that will correct this, please let me know if that's the issue. Or if there is another solution, I'm open to your responses.VS Form Design Error Page
Comment: without seeing code it is difficult to determine what is wrong or missing. The error says the service being added already exists. Have you peeked into your ???.Designer.cs file to see if anything got corrupted? Or if there is a control that was accidentally duplicated?
Comment: Thanks Jeff. I think you're right about the corrupted file. I deleted one at a time my namespaces out of my reference list and then re-added them. Some of the errors that were listed were resolved. Unfortunately the System.Core namespace can't be deleted, so I couldn't re-add it. But it leaves me suspecting that it may have been corrupted. So I think I just need to start a fresh Project file, and copy over my code. What a pain...lol
Answer: I was not able to find a namespace solution to this problem, after deleting and re-adding namespaces in my reference list to rewrite any corrupted references. The System.Core  namespace could not be replaced. I created a new Project file and copied over my code into the new file. I had no problems with my code in the new file.

Visual Studio Form Design


How to calculate confidence interval using parametric bootstrap

Question: I was able to calculate the age-specific hazard ratio (HR) for breast cancer at age 40 and 60 years old. The HR was a continuous, piecewise linear function of age which was constant before 40 years, linear between ages 40-60 years, and constant after age 60 years.
I then calculates the age-specific cumulative risk from these HRs as 1-exp(-cumulative HR), and now want to calculate the corresponding confidence intervals. A paper "A PALB2 mutation associated with high risk of breast cancer" by Southey et al (2010)  calculated CI by using a parametric bootstrap with 5000 replications. She explained that

5000 draws were taken from the normal distribution that the parameter
  estimates would be expected to follow under asymptotic likelihood
  theory. For each age, corresponding values of the cumulative risk were
  calculated, and the 95% CI was taken to be the 2.5 and 97.5 percentile
  of this sample.

I want to do this in R. I think it has to do with the library boot. But I don't quite understand the statistics behind this. Can you please clarify these to me?
Thank you.
Additional info: Here is the code i used to calculate cumulative risk. As you can see, the cumulative risk (at column cumrr) at age 70 is 60.04%. I want to find the confidence interval of the cumrr column.
a = 3.467
b = 3.610

hr = rep(NA, 61)
inc = rep(NA, 61)
age = c(20:80)

for (i in 1:length(hr)) {
  if (age[i] < 30)
  {
    hr[i] = exp(a)
    inc[i] = hr[i]*3.347955/100000
  }
  else if (age[i] >= 50)
  {
    hr[i] = exp(b)
    inc[i] = hr[i]*279.0873/100000
  }
  else
  {
    hr[i] = exp(a) + (age[i] - 30)*(exp(b)-exp(a))/20
    inc[i] = hr[i]*75.91559/100000
  }
}
cum.inc = cumsum(inc)
cum.risk = 1 - exp(-cum.inc)

I would like to note that sd(a) = 0.2668 and sd(b) = 0.3814. The correlation matrix between a and b is
R = matrix(cbind(1, -0.1080, -0.1080, 1), nrow = 2)

I did try to do the following bootstrap, but I think the code was doing a nonparametric bootstrap instead.
boot.sampling.dist <- matrix(1, 5000)

R = matrix(cbind(1, -0.1080, -0.1080, 1), nrow = 2)
U = R * (c(0.2668, 0.3814) %*% t(c(0.2668, 0.3814)))
X <- rmvnorm(n=10000,mean=c(3.364,0.980),sigma=U)

for (j in 1:5000){

  a = X[j, 1]
  b = X[j, 2]

  hr = rep(NA, 61)
  inc = rep(NA, 61)
  age = c(20:80)

  for (i in 1:length(hr)) {
    if (age[i] < 30)
    {
      hr[i] = exp(a)
      inc[i] = hr[i]*3.347955/100000
    }
    else if (age[i] >= 50)
    {
      hr[i] = exp(b)
      inc[i] = hr[i]*279.0873/100000
    }
    else
    {
      hr[i] = exp(a) + (age[i] - 30)*(exp(b)-exp(a))/20
      inc[i] = hr[i]*75.91559/100000
    }
  }
  cum.inc = cumsum(inc)
  cum.risk = 1 - exp(-cum.inc)

  boot.sampling.dist[j] <- cum.risk[51]

}

my.quantiles<-quantile(boot.sampling.dist,c(.025,0.975))

Comment: Can you provide some code and demo small data set, it would be easier to provide an answer that way!
Comment: Hi Gumeo, Thanks for the answer! Please see the updated question.
Comment: I have provided an answer on how to generically perform bootstrap below. If you can calculate the cumulative risk to age 70 for you data, then that is the parameter you want to collect in the bootstrap runs. It might also be beneficial to include the title of the paper you are referring to.
Answer: Edit: Sorry about my confusion in the beginning... But I read over the article, which luckily is in open access if anyone want to chip in on this.
So I first have some general comments regarding the code that you provided, then some questions regarding the modelling.
In the article they state the following:

When testing for an age dependence of the HR, the model with a constant HR was compared to one where the HR was a continuous, piecewise linear function of age which was constant before age 40 years, linear between ages 40 and 60 years and constant after age 60 years.

So when I plot the hr column in your data frame I get the following:

So, this is not continuous! So there is something that needs to be fixed here. I think that the code that you would want to use for that is the following:
hr = rep(NA, 51) #hazard ratio
age = c(20:70)
young <- 3.364*10*1.190/100000
old <- 0.980*10*279.0873/100000
for (i in 1:length(hr)) {
  if (age[i] < 30) hr[i] = young
  else if (age[i] >= 50) hr[i] = old
  else hr[i] = hr[i-1] + (1/20)*(old-young)
}

breast.hr = as.data.frame(cbind(age = 20:70, hr,
                        cumhr= cumsum(hr), cumrr = 1 - exp(-cumsum(hr))))

plot(breast.hr$age,breast.hr$hr)
title("hr column")

That provides the following plot:

So now this is piecewise linear and continuous as stated in the article. Now the cumulative HR should look like the thick black line in Figure 3 of the article.
Now to continue I need to know exactly what the model is that they are using to be able to perform a parametric bootstrap. In the section Statistical Methods for Penetrance Analyses they state which model they use:

A mixed model was employed which incorporates an unmeasured polygenic factor to model the effect on breast cancer risk of a large number of unmeasured genes in addition to the measured major gene.[29] The polygenic part of this model was implemented via a hypergeometric polygenic model with four loci[30] and postulates a normally distributed random variable G for each person so that these variables are correlated within families (see section 8.9 of Lange et al.[31]). A woman's age at breast cancer diagnosis was modeled as a random variable whose HR was, for noncarriers, exp(G) times the Australian breast cancer incidence rate for 1992–2002[32] or, for carriers, the product of this HR multiplied by the age-specific HR. As in Antoniou et al.,[33] the variance of G was chosen to be 1.67, and the mean was chosen so that the average HR for noncarriers equaled the population incidence.

I think that we need more information about the data to be able to do a parametric bootstrap. If you think can fully specify the model, then I can try to help you!
**EDIT: ** So here I have changed the code to be able to plot the quantiles around the mean curve. You can see that it does not look exactly like Figure 3 in the paper, but that is probably because the inc variable is not continuous in age.
boot.sampling.dist <- matrix(0,5000,61)

R = matrix(cbind(1, -0.1080, -0.1080, 1), nrow = 2)
U = R * (c(0.2668, 0.3814) %*% t(c(0.2668, 0.3814)))
X <- mvrnorm(n=10000,mu=c(3.364,0.980),Sigma=U)

for (j in 1:5000){

  a = X[j, 1]
  b = X[j, 2]

  hr = rep(NA, 61)
  inc = rep(NA, 61)
  age = c(20:80)

  for (i in 1:length(hr)) {
    if (age[i] < 30)
    {
      hr[i] = exp(a)
      inc[i] = hr[i]*3.347955/100000
    }
    else if (age[i] >= 50)
    {
      hr[i] = exp(b)
      inc[i] = hr[i]*279.0873/100000
    }
    else
    {
      hr[i] = exp(a) + (age[i] - 30)*(exp(b)-exp(a))/20
      inc[i] = hr[i]*75.91559/100000
    }
  }
  cum.inc = cumsum(inc)
  cum.risk = 1 - exp(-cum.inc)

  boot.sampling.dist[j,] <- cum.risk

}

my.quantiles<-quantile(boot.sampling.dist,c(.025,0.975))

my.025Quants <- apply(boot.sampling.dist,2,quantile,c(.025))
my.975Quants <- apply(boot.sampling.dist,2,quantile,c(.975))
my.mean <- apply(boot.sampling.dist,2,mean)

plot(age,my.mean,lwd=2,type="l",ylim=c(0,1))
lines(age,my.025Quants,col="red")
lines(age,my.975Quants,col="red")
title("Cumulative Hazard Ratio")

Comment: the model they used is the Cox model λ(t)= λ_0 (t)*exp(G+P) with P being the polygenic factor.
Comment: Maybe you can explain further to me about the parametric bootstrap in here. What kind of data do we need for the parametric bootstrap here? I thought we just need the hazard ratio, which we do have. And we need the CI for the cumulative risk, which can be calculated from the hazard ratio. So I'm a bit confused. Can you elaborate on this for me? Thanks.
Comment: @Meo I'll add a simple example later today. Then you can try to apply that to your own model.
Comment: @Meo sorry I get to this so late... Can you please explain what this inc variable is? It does not look like the way you formulated the problem first. I am not sure if it is computed correctly. At least, if you plot age against your cum.risk variable, then it should like the fat black curve on Figure 3 in the paper you reference, right? If all I have to do is sample a and b from a multivariate normal to do this, then I can provide a solution, but please check if the inc variable is calculated correctly.
Comment: No problem. "hr" variable is hazard ratio; "inc" is the incidence, "cum.inc" is the cumulative incidence, and "cum.risk" is the cumulative risk. And yes, if I plot age against cum.risk, I would get Figure 3.
Comment: Because a and b correlated with each other, what i do is i would actually calculate the cum.risk for every single row of X and then take the 25% and 75% quantile as the bootstrap. What do you think? See my edited answer.
Comment: @Meo this is exactly what I was thinking about doing! Assuming that you are correctly sampling from the correct underlying model, then this is the way to do a parametric bootstrap. You might want to collect the values for all cum.risk values and plot the quantiles. At least that is a good way to verify what you are doing. I'll add some code to do it.
Comment: So, if I'm looking for the CI at age 70, I basically just made 2 models, y = ax+b, with a and b is the intervalParam1 and intervalParam2 and put x = 70. Correct?
Comment: @Meo Ok, wow, sorry, I must have completely lead you astray! This is the non-parametric bootstrap! That requires you to have data. You only have the parameters. So I will follow up on this tomorrow and try to provide an answer!
Comment: I realized that too. I think I was confused between parametric bootstrap and nonparametric bootstrap. Thank you so much Gumeo
Comment: @Meo I have changed my answer based on your update. I am not sure we can perform a parametric bootstrap without the data, because the way their model is constructed. Correct me if I am wrong! If I would read their references I might figure it out, but it would be best if you could specify the model! You need to know exactly what model they are using to be able to perform the parametric bootstrap!