Como obter a coordenada X se a condição de Y for cumprida com o Numpy?

Question: Eu criei uma função que me dá esta matriz como output em que cada linha corresponde a um ponto  :
array([[0.57946528, 2.        ],
      [0.35226154, 0.        ],
      [0.26088698, 0.        ],
      [0.56560726, 1.        ],
      [0.41680759, 1.        ],
      [0.55771505, 0.        ],
      [0.8501109 , 0.        ],
      [0.76229916, 1.        ],
      [0.50357436, 0.        ],
      [0.40875861, 1.        ]])

Eu pretendo agrupar os pontos pelo valor único da coordenada Y (np.unique(y)) e calcular a sua média por valor de Y (x_media para y = 0, x_media para y = 1,x_media para y = 2).
Desta forma, o novo array só teria três pontos(3 linhas e duas colunas)
array([[mean(x, y =2) , 2.        ],
      [mean(x, y = 0) / , 0.        ],
      [mean(x, y= 1),0.        ]])

Já pensei em transformar este array num dataframe com pandas mas ando à procura de fazer isto com o numpy
Comment: Dê uma olhada [nessa resposta do SOen](https://stackoverflow.com/a/38015063/664577). O pacote [numpy-indexed](https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP) parece fazer exatamente o que você quer: `npi.group_by(a[:, 0]).mean(a[:, 1])`.
Answer: Acredito que não tenha um método numpy para fazer isso. Certamente com o pandas seria mais fácil.
Mas, uma vez que vc quer fazer com numpy, acredito que o caminho seja:
>>> import numpy as np

>>> arr = np.array([[0.57946528, 2.        ],
...       [0.35226154, 0.        ],
...       [0.26088698, 0.        ],
...       [0.56560726, 1.        ],
...       [0.41680759, 1.        ],
...       [0.55771505, 0.        ],
...       [0.8501109 , 0.        ],
...       [0.76229916, 1.        ],
...       [0.50357436, 0.        ],
...       [0.40875861, 1.        ]])

>>> n = np.unique(arr[:,1])

>>> n
array([0., 1., 2.])

>>> ga = np.array( [ [i, list(arr[arr[:,1]==i,0])] for i in n], dtype=object )
>>> ga
array([[0.0,
        list([0.35226154, 0.26088698, 0.55771505, 0.8501109, 0.50357436])],
       [1.0, list([0.56560726, 0.41680759, 0.76229916, 0.40875861])],
       [2.0, list([0.57946528])]], dtype=object)

>>> final = np.array( [[i, np.mean(j) ] for i, j in ga] )
>>> final
array([[0.        , 0.50490977],
       [1.        , 0.53836816],
       [2.        , 0.57946528]])
>>>

Espero que ajude.
Answer: Os valores:
a =  np.array([
      [0.57946528, 2.        ],
      [0.35226154, 0.        ],
      [0.26088698, 0.        ],
      [0.56560726, 1.        ],
      [0.41680759, 1.        ],
      [0.55771505, 0.        ],
      [0.8501109 , 0.        ],
      [0.76229916, 1.        ],
      [0.50357436, 0.        ],
      [0.40875861, 1.        ]])

Uma alternativa com numpy:
import numpy as np

X = a[:,0] # valores de X
Y = a[:,1] # valores de Y
Y_unic = np.unique(Y) # valores únicos de Y

b = [([X[Y == y], y]) for y in Y_unic] # criando uma lista de array numpy com os valores agrupados
np.array([[np.mean(y), x] for y, x in b]) # calculando a média

Saída:
array([[0.50490977, 0.        ],
       [0.53836816, 1.        ],
       [0.57946528, 2.        ]])

Com pandas:
import pandas as pd

df = pd.DataFrame({'X':a[:,0], 'Y':a[:,1]})
df = df.groupby('Y').mean().reset_index().reindex(columns=['X','Y']).values
df

Saída:
array([[0.50490977, 0.        ],
       [0.53836816, 1.        ],
       [0.57946528, 2.        ]])


Compare One Cell vs. a Row then enter data into another cell if there is a match

Question: I'm trying to figure out a way to compare one cell in Sheet2 vs. an entire row in Sheet1. If there is a match then I'd like to mark a requested row with an "X". The row to mark the "X" with needs to change because I'm comparing for numerous users, I figure I can just set a string for input. Once the single cell has checked down the entire row, I'd need the next cell in the column to check against the entire row and mark an "X" accordingly.
The long short of this is I'm making a database of software installed on 50 computers and I have a list of all possible applications and all installed applications per computer. Not every computer has every application, so I'm trying to automate a spreadsheet that will mark which computers have which software based on the data gathered. If this doesn't make sense please let me know. I understand logic flow and program in Powershell often but I'm not too familiar with VBA commands. Thank you!
Edit: Added picture for explanation.
Edit2: Added code below that I have. It seems to run the check but the c.Value is always wrong. It just doesn't quite check out. I tested CellApp.Select to confirm the range I want is correct. The loop just isn't checking the right values I don't think. For the example picture, pretend that the "List of Machine 3's Programs" is on Sheet2 and starts at A1.

Option Explicit
Sub check()
Dim wsApplications As Worksheet, wsMachines As Worksheet
Dim CellApp As Range, CellMachine As Range
Dim listStRow As Long, listEndRow As Long, listCol As Long
Dim c As Range
Dim Counter As Integer

Set wsApplications = Sheets("Sheet2")
Set wsMachines = Sheets("Sheet1")
Counter = 3

'data start(row, col)on machines-list sheet
listStRow = 2
listCol = 1

With wsApplications
    'find last machine in list
    listEndRow = .Cells(Rows.Count, listCol).End(xlUp).Row
    'Set CellApp Range
    Set CellApp = Range("A2", Cells(listEndRow, 1))

    For Each c In CellApp.Cells
    'For each cell in the CellApp Range...
        Set CellMachine = Cells(1, Counter)
        Counter = Counter + 1
        'Defines CellMachines as Cell "1,3" then "1,4" then "1,5" etc...

        If c.Value = CellMachine.Value Then
        'If the cell in CellApp is equal to the cell that is currently CellMachine
            wsMachines.Cells(4, CellMachine.Column).Value = "X"
            'Mark an X underneath the column that matches up. Designated Row 4 for a test.
        End If
     Next c

End With

Comment: Can you show an image on what the layout looks like?
Comment: Updated with a picture.
Answer: One method outlined below.  This assumes that the mc/program data is presented as per the image below and your 'matrix' is presented as per your Q.  Adjust the sheet names and data positions in the code to suit.

Option Explicit
Sub check()
Dim wsList As Worksheet, wsMatrix As Worksheet
Dim r As Range, c As Range
Dim listStRow As Long, listEndRow As Long, listCol As Long, n As Long
Dim matHdr As Long, matCol As Long
Dim mcNo As String, progNo As String

Set wsList = Sheets("Sheet2")
Set wsMatrix = Sheets("Sheet1")

'data start(row, col)on machines-list sheet
listStRow = 2
listCol = 1

'start position of matrix (row, col) to be filled
matHdr = 1
matCol = 1

    With wsList
        'find last machine in list
        listEndRow = .Cells(Rows.Count, listCol).End(xlUp).Row
            'for each mc in list
            For n = listStRow To listEndRow
                'construct matrix intersect 'headers' for mc and program
                mcNo = "Machine " & CStr(.Cells(n, listCol).Value)
                progNo = "Program " & CStr(.Cells(n, listCol).Offset(0, 1).Value)
                    'populate matrix with "X"
                    With wsMatrix
                        Set r = .Columns(matCol).Find(mcNo, , , xlWhole)
                            If Not r Is Nothing Then
                                Set c = .Rows(matHdr).Find(progNo, , , xlWhole)
                                    If Not c Is Nothing Then
                                        Intersect(r.EntireRow, c.EntireColumn) = "X"
                                    End If
                            End If
                    End With
            Next n
    End With

End Sub

Comment: I ran this with the table you made and it doesn't do anything. What should it be doing? I'm a little confused.
Comment: Perhaps first check the data set up.  1. In the code, have you set YOUR values for the variables: listStRow, listCol, matHdr an matCol and the two worksheet names? 2. Is the format of your machine/program data in the sheet wsList and in the format I have specified in the image?  Note this is slightly different to how you have it specified at present. 3. If you select matrix sheet when you run the code, you should see the table being populated with "X"s as per the comments in the code. 4. Step through the code to check its progress.
Comment: I've just had another look at this and it is likely that you should change matHdr in the code to 2.  This means that the matrix header will be on row 2 as per your image.  In my testing I have it positioned at row 1.
Comment: Barry, I updated the initial post with some code I have worked out. I thought it would make sense but it doesn't seem to work out going across the sheets like that.
Comment: Ok, it works for me so let's make sure you understand and set the variables first.  Assuming that you revert back to the original code: set 'matHdr' to the row number of your row with Program 1, Program 2 etc..  Set 'matCol' to the column number of your column with Machine 1, Machine 2 etc.  Similarly, set  'listStRow' to be the row number on which your newly formatted machines and programs list starts, and 'listCol' to be the column number of your (newly formatted) "Machine No" column.  This new list should be in the exact format as my image, not as your original illustration.
Comment: I got this to work Barry. Thanks for your explanation and thank you for your time and patience.


What is this chord in Grande Valse Brilliante?

Question:
The chord circled in red is what I am asking about. I know that in the measure before, there is a diminished seventh chord. I'm certain that this is a dominant function chord(or at least, locally to the measure, it has dominant function(tritone is the biggest giveaway here)). This, along with 4 notes in the chord, narrows things down to:

Dominant 7th(secondary or primary)
Half Diminished 7th(secondary or primary)
Diminished 7th(secondary or primary)
Augmented Sixth
Tritone substitution

Granted, the tritone substitution is pretty much nonexistent in Chopin's era(closest you get in notation is an unusually resolved augmented sixth chord), so that is out.
What are the notes in the chord? They are these notes:

Db, G, Bb, Ab

Or at least, that is what makes the most sense to me. But if I try to form a chord from these notes that Chopin would have used, I get nothing. Closest I get is a sixth chord(in the sense that there is an added sixth). Chopin wouldn't have used a sixth chord, at least, not a major or minor sixth chord. Could this be an augmented sixth? Well, these are the sixth intervals that are possible, including the possibility of F being a chord tone:

Db-Bb - Major Sixth
Bb-G - Minor Sixth

No augmented sixths in sight. Could this be a dominant seventh chord? No. Only 1 chord seems to fit, G halfdim7. This resolves to Ab major as expected. And this becomes part of a sequence, both melodically and harmonically.
So, the chord in question would be viiø7/IV, right, with the preceding chord being vii°7/IV?
Comment: I'd treat the possibility of the F being a chord tone more seriously than you currently do. In fact, I think a reasonable argument can be made that the first 2 beats of the right hand of each bar of your excerpt after the first bar are effectively suspensions from the 3rd beat of the previous bar and should be ignored for chord analysis. The most obvious support for that analysis is the third bar, where we'd otherwise have to reconcile its C flat in the right hand with its B flat in the left hand.
Comment: As Dekkadeci suggests, each of the four bars starting with your red-circled one, begins with a suspension in the right hand. It's the left hand chords that give the basic harmony: Fm, Eb (2nd inversion), Bb, Eb. (That last Eb, lacks a G until the right hand supplies it.)
Answer: As Old Brixtonian hints at in comments, this is simply a chain of suspensions.  The primary chords in each bar are V7/IV - ii - cadential 6/4 - V7 - I in E-flat.  In the last four bars, the final resolution of the suspensions in the right hand doesn't occur until the third beat in each measure.
The first two bars effectively contain a deceptive resolution of the secondary dominant V7/IV.  Rather than going to IV, the chord resolves to ii.  In the secondary key of A♭, that would be a V-vi progression.  On the third beat of bar 2, the bass note shifts to A♭, to create a ii6 as would be expected moving into a cadence before the dominant.
So, what is happening on the downbeat of bar 2?  Well, you have three notes suspended (held over) from the previous bar.  The top B♭ resolves down to A♭.  The G resolves up to A♭.  The D♭ resolves down to C.  All of these notes resolve precisely as expected in a deceptive resolution of a dominant seventh chord.  The A♭ and F in the left hand are the actual "chord tones" at this point.  The collection of notes on the downbeat of bar 2 would not have been viewed as a separate "chord," but rather a set of mostly non-harmonic tones (suspensions, in this case) that resolve on beat 3 of bar 2.  A similar pattern repeats in each subsequent bar of the except.
As to the debate over whether the E♮ in the first bar is a chord tone, it really boils down to semantics.  The E♮ is undoubtedly a chromatic passing tone.  It can also be seen to imply a viio7/ii, which strengthens the motion to F minor.  Note that this is a very typical addition to deceptive cadence resolutions, where scale degree 5 ascends upward through ♯5 to 6 in the local key.  If we analyze this harmonic motion locally within the secondary key of A♭, this is a standard V7-vi motion with an interpolated passing tone.  Whether you want to label the E-natural as a separate "chord" is more a matter of your analytical priorities.  Chopin would undoubtedly have just thought of it as a standard chromatic passing tone ornament to a local "deceptive cadence-like" motion.  That's the way such progressions were taught in keyboard treatises of the time.
Answer: The part you circled in red isn't really the chord. It's a non-chord tone device called a suspension.
The two chords involved at that moment are E diminished seven (circled in green) and F minor (circled in blue.)

Notice how those two chords overlap in time. When the bass goes from E to F the top voices don't change and hold the tones of the E diminished seven chord. Those top voices are suspended for a moment when the bass moves. When those top voices move down to the tones of the F minor chord is called the resolution.
In written harmony analysis, the bass is usually the point where a chord is identified and then non-chord tone symbols can be added on other voices. So you could put some F minor chord symbol under the F at the beginning of the bar, but on top of the treble voices you could add a mark "sus" to indicate there is a suspension.
Answer: Chopin's harmony is more like Bach's than his immediate predecessors. In other words, it's often more counterpoint than harmony.
This is just an F minor chord with a triple appoggiatura (the Db G and Bb). That is a straight forward progression after the Eb7 in the previous bar.
FWIW the E natural in the previous bar isn't a chord tone either. There is no diminished seventh chord there. It's just a passing note.
You have to use your ears to understand music. Ticking off the notes in the score one at a time to make "chords" out of them leads nowhere useful.
Comment: I think you have to let the E♮ bass note in bar 1 have harmonic function.  It's strongly the leading note of the F that follows.   Whether you want to call it a rootless C7b9 or Eb dim7 (same thing, anyway) is up to you.
Comment: @ Laurence: You  mean e-dim7 not Eb, yes?
Comment: @ Guest: of course E is a chord tone: the root of e-dim7, secondary vii dim7 to F minor.  But the idea of an appoggiatura may be better than a pedal tone...
Comment: So for example, if Beethoven(one of Chopin's immediate predecessors) were to use this harmony, he would likely use it as a secondary diminished seventh resolving to IV or perhaps resolve it unexpectedly to say the VII, or, even use it as part of a diminished seventh chain(I see diminished seventh chains a lot in Beethoven(for example, in Rondo a Capriccio I saw this sequence: vii°7/V, vii°7, V7), whereas Chopin would treat this harmony more like Bach or Mozart would have treated it, as suspensions, is that what you are saying?
Comment: @AlbrechtHügli Um, why would an appogiatura be better than a pedal tone? All those notes that he says are appogiaturas(the Bb, Db, and G) are in the preceding diminished seventh chord in the same exact inversion. And a pedal tone is when the notes stay in place and become a non-chord tone as a result. Usually this occurs in the bass, but there is no reason you can't have a pedal tone in the melody. An appogiatura is when you leap into the non-chord tone. I see no leaps there other than in the bass.
Comment: I say "may be" .. that means I don't know .... I've edited my answer. It is a variation of the I (vii dim 7)  ii V7 progression with the suspended  E dim7 above the Fm.
Comment: All the standard elements of a suspension are there: preparation, suspension, resolution.
Answer: Just having a look without taking notice of the chords I hear the progression: Eb C7b9 Fm Bb7b9 Eb.
Analyzing the chords I agree with you that we have e-dim7 but leading to Fm and not leading to Ab:  vii°7/ii. So I think your interpretation is quite close to mine. It is Fm chord in the left hand and above it  the half notes of the right hand are suspended notes of the previous chord.


sails js production mode does not display minified assets

Question: I am using sailsjs version 0.10.5 . In my sails js application when I run sails lift --prod all css files and js files are concatenate and saved in .tmp/public/min folder as production.min.css and production.min.js. But when I view the page source of my application I can see the relevant js files and css files seperately without concatenation. Am I missing something here ? Any kind of help would be appreciated. Following is my prod.js file inside tasks/register folder.
module.exports = function (grunt) {
    grunt.registerTask('prod', [
        'compileAssets',
        'concat',
        'uglify',
        'cssmin',
        'sails-linker:prodJs',
        'sails-linker:prodStyles',
        'sails-linker:devTpl',
        'sails-linker:prodJsJade',
        'sails-linker:prodStylesJade',
        'sails-linker:devTplJade'
    ]);
};

Answer: https://github.com/balderdashy/sails-docs/blob/0.9/assets.md
Follow this link, Its explaining all about asset injection in sails js


Closed under countable union

Question: I am reading a tutorial on measure theory and it states: "Given an interval $E = [a, b]$ and a set $S$ of subsets of $E$ which is closed under countable unions, we define the following..."
I was wondering what 'closed under countable unions' meant in this case. Does it mean that $S$ contains every element of $E$?
So if $E = [0,5]$, $S$ could be something like $\{[0,2], [1,3], [2,3], [2,5]\}$ since the union of those would be $[0,5]$... but it would impossible for $S$ to be something like $\{[0,1], [1,4], [2,3]\}$ since the union of those would be $[0,4]$.
Am I correct? Thanks!
Comment: I have edited your question so that the math is played in LaTeX. You can do this yourself by writing math within \$ \$ (see the edit for example).
Comment: But $S$ is a set of subsets of $E$. So it must also include $[1,5]$.
Answer: That $S$ is closed under countable unions means that for every countable collection $(A_i)_{i\in\mathbb{N}}$ of sets from $S$, we have that $\bigcup_{i\in\mathbb{N}} A_i \in S$. In particular this must hold for every finite collection of sets, so in your case where $S=\{[0,2], [1,3],[2,3],[2,5]\}$, we have that $[1,3]\cup [2,5]=[1,5]$ which is not in $S$. So this $S$ is not closed under countable union.
Comment: Thank you for your response!!
Answer: $S$ is a collection of subsets of the interval. To say that $S$ is closed under countable unions means that whenever $A_n\in S$, for all $n\in\mathbb N$, then $\bigcup_{n} A_n\in S$ as well.
Note that $S$ does not contain any element of $E$, but rather subsets of $E$.
Comment: It should also mean that $\bigcup\emptyset =\emptyset\in S$, but many authors are not that careful.
Comment: @MichaelGreinecker: True, depends if $0\in\mathbb N$ or not.
Comment: Why does that matter. The set $\{E\}$ is closed under unions of sequences, whether the sequences are ordered with nonegative integers or positive integers.
Comment: @Michael: Oh, yeah. You can also define countable union as if $\mathcal A\in[E]^{\leq\omega}$ then $\bigcup\cal A$ is in the collection. I was thinking about that...
Comment: Ok thank you for that!!

Closed under countable union


Botão "Play/Pause" - Como reiniciar a reprodução?

Question: Eu fiz um simples botão "play/pause" para áudio, com o seguinte script:
<audio id="myAudio"
src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

Porém, na verdade gostaria que ao clicar no botão "play/pause" ao invés de pausar, reiniciasse do '0' a reprodução. Alguma luz?
Answer: Adicione myAudio.currentTime = 0; à função myAudio.onpause:

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
   if (isPlaying) {
      myAudio.pause()
   } else {
     myAudio.play();
   }
};

myAudio.onplaying = function() {
   isPlaying = true;
};
myAudio.onpause = function() {
   myAudio.currentTime = 0;
   isPlaying = false;
};
<audio id="myAudio" preload="auto" controls>
   <source src="http://www.sousound.com/music/healing/healing_01.mp3" type="audio/mpeg">
</audio>
Comment: Obrigado, implementado com sucesso!
Comment: @dib Valeu!!!!!


Link to go to and open toggle div

Question: I want a working .jquery toggle to be activated from a nav menu link. I also want the page to scroll to the opened div at the same time. This is working:
$(document).ready(function(){
$(".toggle_container3").hide();
$(".trigger3").click(function(){
    $(this).toggleClass("").next().slideToggle("slow");
    return false; //Prevent the browser jump to the link anchor
})

});

with this HTML:

Research Themes

 content

And this menu link goes to the research themes section on the page:

Research Themes

But I want the Research Themes link to go to and toggle open the research div. I tried adding the class .trigger3 to the , no luck. The #research stopped working. After researching on this forum, I tried:
$('#research').click(function (e) {
e.preventDefault();
$(this).toggleClass("").next().slideToggle("slow");
    return false;
window.location.hash = ($(e.currentTarget).attr("href"));
});

But no luck. Is there something I can add to the original .trigger3 click function, that will make it work with the  as well? Plus go to that spot on the page?
Answer: All you need is the code below, above each div you wish to show/hide add a button with class .trigger and it will toggle the div below it. This would create an accordion. If the buttons cannot be right above each div to toggle you can add a data-toggle='div name' to each button and use that tag to select the div to toggle.
$(".trigger").click(function(){
    $(this).next().slideToggle("slow"); // toggle div below button
    $('.' + $(this).data('toggle')).slideToggle('slow'); // toggle div specified in data-toggle attribute on trigger element
    return false; //Prevent the browser jump to the link anchor
})

Comment: I guess I wasn't clear. The div is working already with a "button" - the h4 is toggling the correct div. I want an additional link in a nav menu to also toggle the div (I can add unqiue id's to each div, to match up with each menu link). And I want it to go to the spot of the div on the page. Although - are you saying that I can add the data-toggle to each link and that will work?
Comment: So you want two different buttons to toggle the same div? If so then add the .trigger class to both buttons and reference the div directly by id or class. Such as $('#divid').slideToggle('slow');
Comment: What about the go to on the page part?
Comment: If it is on click then you can add href='#idofelement' to scroll to that element. If you wish to do this in jQuery you can do document.scrollTop = $('#idofelement').position.top();
Comment: Actually, I think I just had to remove the return false; from the script, that now does allow the browser to jump to the link anchor. Thanks for the help - I think its all working the way I want now.

Link to go to and open toggle div


A sequence containing all positive rational numbers.

Question: Question: Consider the following sequence $\{a_n\}_{n=1}^{\infty}$ defined as $a_1=1$ and for $n\ge1$ $a_{2n}=a_{n}+1$ and $a_{2n+1}=\dfrac{1}{a_{2n}}$. Show that the sequence has all positive rational numbers exactly once.
So far: In $a_n$ if $n$ is even $a_n>1$, and if $n>2$ is odd then $a_n<1$. If we can show that all positive rational numbers greater than $1$ are terms of the subsequence $a_{2n}$ we will be done. If $p/q$ is a positive rational in lowest form and $p>q$ then we have to show its a term of the subsequence. How can I do that?
Well I did prove the uniqueness of them, say $a_m=a_n$ and $m\neq n$ for the minimum $m+n$, its easy to see equality will hold if either both $m,n$ are even or both odd, from this we will get a contradiction to minimality assumption of $m,n$.
Please give some hints to proceed from here. If you have alternate solutions do share.  What are some other sequences like this which cover the rationals/irrationals?
Thanks a lot!
Comment: Hint: Look up "continued fractions"
Comment: Can we do it by induction on the the numerator and denominator?
Answer: Hint: Indeed, use continued fractions and also the binary expansion of the index.
Take a positive rational number. Consider its continued fraction.  Use pebbles (zeroes) for the partial quotients and reverse the fraction bars into ones. Reverse the sequence of zeroes and ones thus obtained and prepend a one. You got the binary expansion of the index of the term that equals that number
Comment: I dont know continued fractions,can you give a reference for learning it. thanks for the reply.
Answer: You can do it by induction on the denominator.
I am going to write $f(m)=a_m$, because putting complicated formulae in subscripts is ugly.
First, show that $f(m)>1$ if and only if $m$ is even.
If your rational number is $\frac{p}{1}$ for some integer $p$, then $f(2^p)=p$.
Now, assume it is true for all rationals $\frac{p}{q}$ with $q<Q$. Let $P$ be another positive integer relatively prime to $Q$.
Applying the division algorithm, write $P=Qx+r$ where $x\geq 0$ and $0\leq r<Q$. If $r=0,$ then $Q$ divides $P$, which means they are not relatively prime of unless $Q=1$, which is already covered. So we can assume $0<r<Q$.
Now, by the induction hypothesis, we know that $\frac{Q}{r}=f(m)$ for some $m$, since $0<r<Q$. Since $\frac{Q}{r}>1$, we have that $m=2n$ for some $m$.
The last step, which I'll let you fill in, is to show that:
$$f(2^x(m+1))=\frac{P}{Q}$$
Comment: Thanks I did induction on both numerator and denominator simultaneously. Anyways can you refer me some resources to learn continued fractions, sorry for off-topic question.


Calendário Android com eventos

Question: No momento só tenho este calendário.

Estou a utilizar o MaterialCalendarView
    <com.prolificinteractive.materialcalendarview.MaterialCalendarView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/calendarView"
            android:layout_centerInParent = "true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:mcv_showOtherDates="all"
            app:mcv_selectionColor="#00FFFF" />
    </android.support.constraint.ConstraintLayout>

Pretendo agendar eventos numa determinada data, afim de que essas atividades fiquem visíveis no calendário.
exemplo: Se no dia 5 de Agosto tenho um aniversário agendado, gostaria que nesse dia algo o descrevesse. Ou por imagens ou por textos. Tal como ilustro na figura seguinte.

Algumas ideias para o que pretendo?
Answer: Nokas,
Para definir eventos você pode usar o seguinte código:
calendarView.addEvent(new Event(date, "Feriado X"));

Para destacar os eventos, você precisará utilizar decorators em datas específicas, onde você define como deverá ser essa personalização de acordo com o tipo de data.
Na documentação há um exemplo de como colocar um ponto nas datas específicas:
public class EventDecorator implements DayViewDecorator {

    private final int color;
    private final HashSet<CalendarDay> dates;

    public EventDecorator(int color, Collection<CalendarDay> dates) {
        this.color = color;
        this.dates = new HashSet<>(dates);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return dates.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new DotSpan(5, color));
    }
}

Chamando o decorator:
calendarView.addDecorators(new EventDecorator(this));

Poderá definir também mais de um decorator para casos diferentes:
public class FeriadoDecorator implements DayViewDecorator{
    @Override
    public void decorate(DayView view,Context context) {
        view.setBackground(generateCircleDrawable(color));
    }
}

Adicionando decorator personalizado:
widget.addDayViewDecorator(new FeriadoDecorator (), dates);

https://github.com/prolificinteractive/material-calendarview/blob/master/docs/DECORATORS.md

Você poderá utilizar estilos personalizados para o primeiro dia do mês, por exemplo:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
          android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item android:state_checked="true" android:drawable="@drawable/selected_bg_color" />
<item android:state_pressed="true" android:drawable="@drawable/selected_bg_color" />
<item android:drawable="@drawable/red_circle" />

red_circle:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:innerRadius="0dp"
   android:shape="ring"
   android:thicknessRatio="2"
   android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke android:width="2dp" android:color="@color/selected_color" />

selected_bg_color:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@color/selected_color"/>
<size android:width="120dp" android:height="120dp"/>

Fonte: https://stackoverflow.com/a/37881374/5626568
Comment: Muito obrigada! Irei testar
Comment: Já testei! Consegui colocar um "ponto" colorido numa determinada data, mas ao invés de colocar esse ponto testei colocar uma pequena string e não funcionou...
Comment: Collection colldates;
        colldates = new HashSet<>();
        CalendarDay eventDay2 = CalendarDay.from(2017, 07, 18);
        colldates.add(eventDay2);
        materialCalendarView.addDecorator(new EventDecorator(colldates, "Nokas")); **Alterei a Classe EventDecorator o método decorate ** view.addSpan(new String(n));  O que estou a fazer de errad0? @ℛɑƒæĿ
Comment: @Nokas editei a resposta, coloquei um exemplo no final...
Comment: Obrigada mas testei e ainda não dá @ℛɑƒæĿ não está a aceitar o new TextSpan, não reconhece.
Answer: Você pode usar o DayViewDecorators. Seria algo como:
calendarView.addDecorators(new EventDecorator(
    getResources().getColor(R.color.coarCalendar), calendarDays))

Veja um exemplo simples que está na documentação:
public class EventDecorator implements DayViewDecorator {

    private final int color;
    private final HashSet<CalendarDay> dates;

    public EventDecorator(int color, Collection<CalendarDay> dates) {
        this.color = color;
        this.dates = new HashSet<>(dates);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return dates.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new DotSpan(5, color));
    }
}

Comment: Obrigada! Irei testar!
Comment: Já testei! Consegui colocar um "ponto" colorido numa determinada data, mas ao invés de colocar esse ponto testei colocar uma pequena string e não funcionou...
Comment: Collection colldates; colldates = new HashSet<>(); CalendarDay eventDay2 = CalendarDay.from(2017, 07, 18); colldates.add(eventDay2); materialCalendarView.addDecorator(new EventDecorator(colldates, "Nokas")); **Alterei a Classe EventDecorator o método decorate ** view.addSpan(new String(n)); O que estou a fazer de errad0? @acklay
Comment: @Nokas estava alterando aqui pra colocar a string.
Comment: foi exatamente isso que fiz, como pode ver no exemplo que coloquei no comentário, mas não está a funcionar infelizmente :-( @acklay
Comment: @Nokas está aparecendo algum erro?
Comment: não, não está a aparecer @acklay será que a string não aparece devido às dimensoes do meu MaterialCalendarView?
Comment: @Nokas tenta colocar apenas um letra para exemplo. Estou faendo um teste aqui.
Comment: testei apenas com uma letra e não deu @acklay
Comment: @Nokas você usou o addEvent como o Rafael exemplificou?
Comment: utilizei apenas o addDecorator... @acklay
Comment: @Nokas tenta fazer usando addEvent  em vez de DayViewDecorator
Comment: estou com um problema, o MaterialCalendarView não me permite fazer o addEvent @acklay

Calendário Android com eventos


Spring Mvc ModelAttribute with containing class reference not working?

Question: I want to to create different @Entity entities within the same Controller.
public class ContentContainer {

public Object content;

public ContentContainer(){}

public ContentContainer(Object object){
    setContent(object);
}

public Object getContent() {
    return content;
}

public void setContent(Object content) {
    this.content = content;
}

}

Controller method
@RequestMapping(value="create", method=RequestMethod.GET)
public String  GET(Model model) throws InstantiationException, IllegalAccessException {

Class<?> clazz = ????; // a Random POJO is chosen, i want to use POJOs!!
Object object = clazz.newInstance();

model.addAttribute("mymodel", new ContentContainer(object));

return "create";
}

@RequestMapping(value="create", method=RequestMethod.POST)
public @ResponseBody Object POST(@ModelAttribute(value="mymodel") ContentContainer cc) {
    Object object = cc.getContent();
    // object == NULL but why??
    return object;
}

Thymeleaf page as was asked in another comment.
That#s why i posted this
some more
text
so i can post
this additional information
dont't know
why this is necessary.
Please excuse me.
But this has to be done
to obey the rules.

<title th:text="${title}">Entity create</title>

 <form action="#" th:object="${mymodel}" th:action="@{${url}}"  method="post">
<fieldset>

        Fieldname
        Input

        Fieldname:
        <input type="text" th:field="*{__${v}__}" />

         <button type="submit" name="create" th:text="#{entity.create}">Create</button>

 </fieldset>

</form>

In the Post Method i get NULL for getContent
What am i missing?
Comment: The same as in your other question, here http://stackoverflow.com/questions/24031858/spring-mvc-modelattribute-with-referencing-name-is-not-working
Comment: But how can i achieve it, that i can open the same page multiple times without the session getting swapped or shared between the different site request? (if i open multiple tabs to the same url, but i will pass different parameters to the url)
Comment: Please read the answer I gave 2 solutions!.
Comment: @ModelAttribute does not work too, and i don't like dealing with Session if i use it only to send changes of a pojo to a controller
Comment: Why wouldn't that work, that method is execute before every method and if a named attribute is available it should be used.
Comment: If i use ModelAttribute i don't get the values i entered for it on the website. On the POST controller method i tried using it by calling the method and i also tried injecting it as an argument on the method. Both only return me a new object from the ModelAttribute annotated method that create a blank new object.
Comment: You don't call the method spring does that for you! It works if it doesn't work for you you have something wrong in your setup!.
Answer: I've just tested your thing.
In my JSP:
<form:form method="POST" action="./index.do" modelAttribute="testObject">

test for object

                <form:input path="object"/>
                <input type="submit" value="test Object"/>

</form:form>

And my testObject is similar to your ContentContainer
When I debug, I found no matter what I've given in my GET method for getting this page, the object contained in the container return by POST method has always the type String.
And can you post your JSP please, because in my test there is no convert or null error, maybe there's something wrong with your JSP about the modelAttribute.
Comment: String will always work, like all primitive types, but class types do not work
Comment: What's the JSP page like? I don't get a null, but I don't think spring can convert the object.
Comment: see edit, it's a thymeleaf page, converters from spring are added automatically with the spring-thymeleaf jar published by spring
Comment: @user2000811 hey dude, something new?
Comment: `*{__${v}__}`, this bind the value to which property?
Comment: values contains all fieldnames from the java object, so v contains a single fieldname, i think spring is not intelligent enough, i would expect, that it is possible to bind an object to a name with the ModelAttribute annotation, now you have to send this name within the form and use custom coding to get all the values from the httpRequest or use MultiValueMap  to get the values injected
Comment: Agreed, spring only knows the primitive types(List too)... for your pojos, you have to convert by yourself maybe.
Comment: My solution is to add an additional field that holds the type com.test.model.ModelA so that i can build it on my own.. if you have some suggestion where i have to hook so that i can extend @ModelAttribute to do it by name, i would appreciate it posting the complete code afterwards


How to get the hashtag value and ampersand value of a url in Javascript?

Question: I have a url like http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"
Now I need to get the portion of url from starting from #, How do I get that, I tried using window.location.search.substr(); but looks like that searches for ? in a url. is there a method to get the value of url after #
How do I also get  a portion of url from ampersand &
Thanks,
Michael
Comment: @MatthewBlancarte isnt there any shortcut way to get anything after ampersand like what we have for hash tag, if not then what is the approach
Comment: Have you tried the accepted approach in the link I gave at the bottom of my answer? http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript That will parse the query string. If you were doing this server-side (e.g., PHP/Rails/etc.) it would be much simpler.
Answer: var hash = window.location.hash;

More info here: https://developer.mozilla.org/en/DOM/window.location
Update: This will grab all characters after the hashtag, including any query strings. From the  MOZ manual:
window.location.hash === the part of the URL that follows the # symbol, including the # symbol.
You can listen for the hashchange event to get notified of changes to the hash in
supporting browsers.

Now, if you need to PARSE the query string, which I believe you do, check this out here: How can I get query string values in JavaScript?
Comment: Suppose I just have www.domain.com&val=1&val=4, and I need to get &val=1&val=4
Comment: Is ther a way to get a value after &
Comment: That's a separate question - please post it as such, or edit the current question. The part after `?` (not `&` is the query string - you asked about the hash).
Comment: @Mike it grabs everything after the hash tag, including the hashtag and your query-string without the '?'. :)
Comment: what do I need to grab just the query string.
Comment: `.hash` does not grab the query string
Comment: @Utkanos Yes it will, in his case. It will grab all characters following the hash. Try it out.
Comment: `.hash` does not grab the query string - what the OP has is a contrived query string that is actually part of the hash. A real query string goes before the hash in a URL.
Comment: @Mike I hope you don't have a query string with identical keys like val and val. :) Check my updated answer. At the bottom there is a link on how to parse a query string in js.
Comment: @Utkanos I don't think we are arguing about anything here. I've made it clear that .hash will grab it in this particular case only. :)
Comment: @MatthewBlancarte - agreed :) Sorry - I just saw your comment where you said "including ... and your query string".
Answer: To grab the hash:
location.hash.substr(1); //substr removes the leading #

To grab the query string
location.search.substr(1); //substr removes the leading ?

[EDIT - since you seem to have a sort query-string-esq string which is actually part of your hash, the following will retrieve and parse it into an object of name/value pairings.
var params_tmp = location.hash.substr(1).split('&'),
    params = {};
params_tmp.forEach(function(val) {
    var splitter = val.split('=');
    params[splitter[0]] = splitter[1];
});
console.log(params.set); //"none"

Comment: This is because you're confusing query strings with hashes. You seem to have a sort of query string-esq string as part of your hash. If you want to extract *that* you'll need some REGEX, string-handling. I'll edit the answer.
Answer: To get the hash
window.location.hash

To get the hash value (without #)
window.location.hash.slice(1)


.net dictionary object type

Question: I'm trying to use a dll on my system. One of the methods return a dictionary object defined in the object browser as
<code>"System.Collections.Generic.Dictionary<<string,1.5>>"
</code>
What is 1.5? Or is that some security mechanism to lock the dll from unintended use?
Comment: Thanks for the edit Blorgbeard
Comment: What can you see in the object browser when you expand the dictionary? What is the declared return type of the method?
Comment: @svik. Well if I expand the object I can see that the Dictionary in turn contains a KeyvaluePair which in turns contains a List, etc. A pretty deep hierarchy. But I don't know how to assign this object since I can't use 1.5 as a type.
Answer: "1.5" is not a valid type name in any common .NET language, they insist you start a type name with a letter.  Important to make the job of a lexer simple, the part of the compiler that preprocesses the source code into tokens before the program is parsed.  A lexer will identify "1.5" as a number, not an identifier.
The CLR has much more lax rules about that however, just about anything goes for a type name.  This is taken advantage of by obfuscators.  A program that you run after building an assembly that makes it difficult to reverse-engineer the source code from the assembly.  There are several very good decompilers available for .NET, like Reflector and ILSpy.  An obfuscator is designed to defeat them.
High odds that the assembly you are using was obfuscated.
Comment: Do you mean that while `1.5` is not a valid type name for .NET compiler/parser, it is valid for .NET runtime?
Comment: @SinaIravanian I think Hans meant exactly what he said, that `1.5` is not valid in most common .Net languages (C#, VB.NET, F#, …). But it is valid name in IL.

.net dictionary object type


How to Create dynamic tbody onclick of button using javascript or jquery

Question: I have this code:

$(document).ready(function() {
    //Try to get tbody first with jquery children. works faster!
    var tbody = $('#myTable').children('tbody');

    //Then if no tbody just select your table
    var table = tbody.length ? tbody : $('#myTable');

    $('button').click(function() {
        //Add row
        table.append('
\n\
        <input name="product_name[]" type="text"/>	\n\
        <input name="qty[]" type="text"/>	\n\
        <input name="price[]" type="text"/>	\n\

');
    })
});

<input name="row_no" type="text" placeholder="Type Your Number of row"  />
<button>Add row</button>

         Product name
         Quantity
         Price

When I click on the button Add row, it appends a row to the table.
But now, I have a textbox in the HTML. I want to append the table to generate rows based on the value of:
<input name="row_no" type="text" placeholder="Type Your Number of row"  />

How do I achieve this?
Answer: Here's what you're looking for:

$(document).ready(function() {
    //Try to get tbody first with jquery children. works faster!
    var tbody = $('#myTable').children('tbody');

    //Then if no tbody just select your table
    var table = tbody.length ? tbody : $('#myTable');

    $('[name=row_no]').text();

    $('button').click(function() {

        var rows = $('[name=row_no]').val();

        // If rows are at maximum 10,
        if (!(rows > 10)) {
            // then add rows
            for (var i = 0; i < rows; i++) {
                table.append('
\n\
      <input name="product_name[]" type="text"/>	\n\
      <input name="qty[]" type="text"/>	\n\
      <input name="price[]" type="text"/>	\n\

');
            }
        }
        else {
            alert("Error: Too many rows!\n" +
                  "Maximum allowed: 10\n" +
                  "- Inserted: " + rows);
        }
    });
});

   <input name="row_no" type="number" placeholder="Type Your Number of row"  />
   <button>Add row</button>

            Product name
            Quantity
            Price

What changed?

You needed to get the value inserted in the textfield, this can be achieved using, in this case: $('[name=row_no]').val();, so I valorised it as rows variable and then the only thing to add was a cycle that creates as many rows as the user inserts.
I also changed<input name="row_no" type="text" placeholder="Type Your Number of row"  />to <input name="row_no" type="number" placeholder="Type Your Number of row"  />. This little change allows the user to insert only integers and this is a nice solution to avoid time-loss because of writing a new function to validate values inserted.

Edit:

Added a control on about how many rows the user can insert with if (!(rows > 10)) condition (if you need more or less rows, the only thing to edit is the number)


Why do I get: double free or corruption (top) after running this c++ script?

Question: I've got the following piece of code:
Class Chain

with
char* c;

as its only public atrib
istream& operator>>(istream& i, Chain& s) {
  delete [] s.c;
  const int L = 256;
  char *t = new char[L];
  i.getline(t,L);
  s.c = t;
  return i;
}

ostream& operator<<(ostream& o, Chain s) {
  o << s.c;
  return o;
}

#include <iostream>
#include "Chain.h"
using namespace std;

int main(){

      Chain id;

      cin >> id;

      cout << id;
      cout << id;

After running the code under the Eclipse IDE on Xubuntu (last version) I get the following error:

Error in [...] double free or corruption (top): 0x00000000008fd290 ***

What could be wrong?
Comment: Please include a [mcve]. Every answer of this question will include guesswork about the internals of `Chain`, and that is bad.
Comment: Post a [MCVE](https://stackoverflow.com/help/mcve) please.
Comment: If this question was in an answerable state, it should most likely be dupe-hammered for stackoverflow.com/questions/4172722/what-is-the-rule-of-three
Comment: @GrahamS That would most likely not help here as OP probably screwed up the copy constructor.
Comment: Whyyyyyyy raw dynamic allocation for this?! And why three upvotes?!
Comment: @user3166611 To save you some time: Use a std::string instead of a char*. Raw owning pointers like that do not manage their own memory the way standard classes like std::string and std::vector do. It's very easy to accidentally double delete things (as you've done) when raw pointers are involved, and almost impossible when they aren't. You should not try to write classes with raw arrays or raw owning pointers until you fully understand things like the rule of three.
Comment: My advice is to always set c to `nullptr` (or `NULL` or `0`) after you delete it. That way it will never be double-deleted.
Comment: Yep fair point @BaummitAugen
Comment: Abel: Those two lines are not code.
Comment: @Abel: Please, please, please do not format non-code as code, otherwise it is totally unreadable....
Comment: @LightnessRacesinOrbit, lol, how do you mean? Oh crap, I see :/ (still unreadable though, improved now)
Answer: ostream& operator<<(ostream& o, Chain s) {

That's not a reference on s, it's building an entire copy which probably has a destructor that deletes the memory used. And since you call this twice, it gets deleted twice.
Comment: Probably true. Still, answering questions where answering requires guesswork gives the wrong impression to the OP. Please try to avoid answering questions until they're properly formed!
Comment: @Blindy: Well, exactly: Stack Overflow questions are not debugging sessions.
Comment: I think psychic remote debugging is super sweet and awesome!
Comment: @LightnessRacesinOrbit, this is C++, not a magic 8 ball. Given the code and the results shown, I'm pretty sure of my answer, and that's good enough to at least start a debugging session.
Answer: Your class Chain most likely has a destructor that is destroying c. So at this line:
delete [] s.c;

You are deleting c, then when Chain gets deleted, it tries destroying c again to find it has already been deleted and you are doing a double free.
Comment: @user3166611: All that would do is cause memory leaks. Programming by guessing doesn't work.
Comment: Yes I have that destructor, should I delete it?
Comment: No, even if you deleted the destructor, C++ creates one for you by default. Better to have one you define so you know what/how things are deleted.
Comment: I don't think this is the problem. He's deleting the **previous** contents of `s.c` because he's about to reassign it. When the destructor runs, it only deletes the last one, the other deletions shouldn't be a problem.
Comment: @Barmar: I don't see what _else_ it could be other than a violation of the rule of zero/three/five. The key is the accidental copy. But then, we don't have all the information.


How can a undergraduate student start learning geometry?

Question: I have finished all undergraduate course on analysis and abstract algebra. However, I know little about modern geometry, such as riemann geometry, conformal geometry, and general relativity.
Where should I start my self study of geometry?
Comment: Differential geometry was where I started (Spivak vol 1). If you want to get into general relativity (or just learn an awesome new tool for differential geometry), then tensor calculus is something that I've found very rewarding. [Here is one series of lectures on the subject](https://www.youtube.com/playlist?list=PLlXfTHzgMRULkodlIEqfgTS-H1AY_bNtq). Or if you want to skip that and dive straight into general relaivity instead then [this lecture series](https://www.youtube.com/watch?v=7G4SqIboeig&list=PLFeEvEPtX_0S6vxxiiNPrJbLu9aK1UVC_) really helped me when I took the GR course.
Comment: John Lee's book [Introduction to Smooth Manifolds](https://www.amazon.com/Introduction-Smooth-Manifolds-Graduate-Mathematics/dp/1441999817/ref=sr_1_1?s=books&ie=UTF8&qid=1518210231&sr=1-1&refinements=p_lbr_one_browse-bin%3AJohn+Lee&dpID=41QDnhkAV3L&preST=_SY291_BO1,204,203,200_QL40_&dpSrc=srch) is definitely worth a look. His books Introduction to Topological Manifolds and also Riemannian Manifolds: An Introduction to Curvature are worth checking out.
Answer: Textbooks are of course fine, but I would recommend Anton Petrunin's list of geometry problems.  It covers most of modern geometry and, as he writes in the introduction, it's about cool ideas and problem solving rather than theory and machinery.  Geometry is notorious for compelling people to learn 2 years' worth of theory before you get to do something cool, and Petrunin's problems are an antidote.
Of course, the problems are not at all easy - I'm not sure I would have been able to solve any of them on my own as an undergraduate.  But you can still learn a lot from them as follows:
1) Read the preamble to each section, and consult whatever external references you need to understand the example problem (filling in all missing details).
2) Pick one or two problems according to your interests, and consult whatever references you need to fully understand the statement.
3) Spend at least a few days trying to solve the problem(s), working out a concrete example or two if you can't get anywhere.
4) If you haven't solved the problem after a few days, read the partial solution and then consult whatever references you need to fill in all of the details.
If you do this with all of the problems then you will be better equipped than many people with advanced degrees to do research in geometry (myself included, if I'm being honest).
Answer: Your question is very general, but I'll share one of my favorites. The first six chapters of Visual Complex Analysis by Needham are an excellent introduction to Non-Euclidean geometry and the associated conformal models. It was here that I first learned the group of Möbius transformations is isomorphic to the Lorenz group from special relativity.
It is completely approachable at an undergraduate level and will give a nice base to head in various "modern" directions. It had a big effect on me.
You probably also want to look at answers to related questions, e.g. Where to start learning Differential Geometry/Differential Topology?


#upload_validators missing error message

Question: [Update]
Upon further investigation it seems that the message isn't appearing due to the following javascript error:
"Uncaught TypeError: Cannot read property 'length' of undefined"

I'm not sure how to resolve this error, but the following issues may be related:

[D7] Duplicate HTML IDs are created for file_managed_file fields
Duplicate HTML IDs are created for file_managed_file fields

Description
I'm trying to create a custom form with some number of file upload fields (for now I'm using the hard-coded value 3).
I have added an #upload_validators attribute to the managed_file element that calls file_validate_extensions and passes in "doc" as the only valid filetype.
When I try to upload a .jpg, an error appears -- which is what I want. However, the error doesn't contain any text.
Any idea what I'm doing wrong?
Code
function mymodule_example1_form($form_state) {
  $num_docs = 3;

  // Build the number of name fieldsets indicated by $form_state['num_docs'].
  for ($i = 1; $i <= $num_docs; $i++) {
    $form['managed_file'][$i] = array(
      '#type' => 'managed_file',
      '#title' => 'Managed File' . $i,
      '#progress_indicator' => 'throbber',
      '#progress_message' => 'Upload successful!',
      "#upload_validators"  => array("file_validate_extensions" => array("doc")),
      '#upload_location' => 'public://doc/',
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

Screeshot

Resources

Drupal Form API Reference - managed_file
Drupal API - function file_validate_extensions
Answer: I was able to resolve the issue using the solution posted here.
As I understand it, the issues is caused by an ID being used more than once. To fix this, you can implement an #after_build callback that ensures the upload fields will have unique IDs.
To summarize...
Add an #after_build callback to the managed_file field:
$num_docs = 3;

// Build the number of name fieldsets indicated by $form_state['num_docs'].
for ($i = 1; $i <= $num_docs; $i++) {
  $form['managed_file'][$i] = array(
    '#type' => 'managed_file',
    '#title' => 'Managed File' . $i,
    '#progress_indicator' => 'throbber',
    '#progress_message' => 'Upload successful!',
    "#upload_validators"  => array("file_validate_extensions" => array("doc")),
    '#upload_location' => 'public://doc/',
    '#after_build' => array("MODULE_file_managed_fix_duplicate_id"),
  );
}

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

Create the following callback:
function MODULE_file_managed_fix_duplicate_id($element) {
  if ($element['#id'] === $element['upload']['#id']) {
    $element['#id'] = drupal_html_id($element['#id']);
  }
  return $element;
}

Once I did that and cleared all my caches, the javascript errors went away and the error messages starting working.


Prove that if $XA=0$ only for $X=0$ then $A$ invertible

Question: Let $A$ be a $n\times n$ matrix over $\Bbb R$, and $W$ be a vector space of all matrices $X$ such that $XA = 0$. How can I prove that
$W = \{0\}$ implies $A$ is invertible?
Comment: What are your thoughts on the problem?
Answer: Consider the endomorphism of $V:=Mat_n(\mathbb{K})$ given by the multiplication by $A$. $\mu_A:V\longrightarrow V$, $\mu_A(X)=X·A$. This is a linear mapping, $\mu_A\in End(V)$ and $\ker{\mu_A}=W=\{0\}$ so it is injective. Being a linear map between vector spaces of the same dimension ($V$ and $V$ :D) this implies that is also surjective, so $\exists X\in V$ such that $X·A=I$ (and in the ring of square matrices you have left inverse iff you have right, for a given matrix)


Views filter count

Question: I'm trying to set up a block that will allow me to show 6 items in it, 2 that are checked yes and 4 that are checked no.  They are sorted by date so I have a pager set up to take the first 6 values.  What I would like is if for example the first 5 items are checked no and the next two are checked yes, then my block should show the first 4 no items and the first two yes items.
Thanks!
Answer: Create one block.
Then for the same view create an attachment and add it to the block (after).
Set the pager for the block to display specified number of items : 2 , and set the sort to checked yes and then by date.
Set the pager for the attachment to display specified number of items : 4 , and set offset to 2. Set the sort to not checked yes and then by date.
To swap the order around set the attachment to attach before the block.
Answer: This can't be done by simple view as per my knowledge. You need to change the output of view's <code>$result</code> array in hook_views_pre_render
Comment: Thanks Himanshu - Or I guess I could also create two blocks
Comment: Yep, that would be better solution

Views filter count


Is it possible to use com.google.gwt.core.ext.Generator on Google App Engine

Question: I'm working with GWT and Google App Engine...
I use  com.google.gwt.core.ext.Generator to load dynamic Presenter-Classes on client-side.
It works when i test it locally. But not on google App Engine... :-(
<code>PresenterFactory factory = (PresenterFactory) GWT.create(ReflectiveFactory.class);
IDynamicPresenter p =  factory.newInstance("ch...NewsPresenter");
</code>
this should bind the Class on runtime.
I implemented following code:
http://programmatica.blogspot.com/2007/10/classfornamefullyqualifiedclassnamenewi.html
Is it possible to use com.google.gwt.core.ext.Generator on GAE?
Kindest Regards
Sam
Comment: I can't figuere the error out. I only get an javascript exception which says "umbrella exception" inside i found "ClassCast"-Exception.
I figured out that the ***.cache.html is different in firefox and IE. The Code for IE throws the ClassCast Exception, Firefox doesn't.
Comment: I compiled it without Runtime Class-Casting - than it works!
Answer: I compiled it without Runtime Class-Casting - than it works!
problem was ClassCasting in IE-cache.html file
-XdisableCastChecking as Compiler Flag


Sort Java Script Object literals

Question: I inherited a project that uses JSON to perform a series of operations as denoted by each object literal.  I have zero experience with JSON and while the notation is straight forward, I'm finding working with the object literals less so.
Consider the following file:
[{
    "Name": "Hingle McCringleberry",
    "ID": "4"
},
{
    "Name": "Scoish Velociraptor Maloish",
    "ID": "1"
},
{
    "Name": "DGlester Hardunkichud",
    "ID": "3"
}]

Using Java, I want to sort them by ID.  I saw this thread that talks about implementing a JavaScript sort method, but I'm unsure how to do this in practice.  I'm using a JsonFactory and JsonParser to read and iterate over the file, but I need them to be sorted before I can process them.
Answer: Since you're using Jackson to parse these, I assume you must be parsing them into a List of some sort of object with an ID and name.  If that is the case, simply write a standard Comparator.  For example:
NamedObject.java:
public class NamedObject {
    // I'm using public fields instead of getters/setters for brevity,
    // since this is just sample code.

    @JsonProperty("ID")
    public int id;

    @JsonProperty("Name")
    public String name;
}

NamedObjectIdComparator.java:
public class NamedObjectIdComparator implements Comparator<NamedObject> {
    public int compare(NamedObject object1, NamedObject object2) {
        return object1.id - object2.id;
    }
}

Then, to sort the list of objects:
List<NamedObject> objects = // parse using JsonParser
Collections.sort(objects, new NamedObjectIdComparator());

Answer: I don't know much about jackson library, but I am sure jackson can convert JSON to Java List object (some methods call readValueXXX I guess).
Once we got a Java List, Collections.sort can do the sorting.

Sort Java Script Object literals


Using the ratio test for the series $\sum \frac1{3^n-2^n}$, I can't compute the limit

Question: $$\sum_{n=1}^{\infty} \frac{1}{3^n-2^n}$$
I know this series is convergent and using the ratio test.
But I can't conclude the proving.
$$\begin{align}\lim_{n\to\infty} \left| \frac{\frac{1}{3^{n+1}-2^{n+1}}}{ \frac{1}{3^n-2^n}}\right|
&= \lim_{n\to\infty} \left| \frac{3^n-2^n}{ 3^{n+1} - 2^{n+1}}  \right|\\
&= \lim_{n\to\infty} \left| \frac{1-(\frac{2}{3})^n}{ 3(1-2^{n+1}/3^{n+1})}\right| \end{align}$$
By using calculation, the limit is 0.
But I can't compute this limit by myself without using calculation. Any help?
Comment: MAy be it is better to write in the same form the numerator and the denominator?
Answer: $\lim_{n\to\infty} \left| \frac{1-(\frac{2}{3})^n}{3(1-(\frac{2}{3})^{n+1})}\right| = \frac{1}{3}$ because $\lim_{ n \to \infty} \left(\frac{2}{3}\right)^n=0$
Answer: Compare the general term of your series with
$
\frac1{3^n}
$:
$$
\frac{\frac{1}{3^n-2^n}}{\frac1{3^n}}=\frac{3^n}{3^n-2^n}\stackrel{n\to+\infty}{\longrightarrow}1
$$
thus, being $\sum_n\frac1{3^n}$ convergent, so is the given series.
Answer: You've almost got this one solved
$\lim_{n\to\infty} {(\frac{2}{3})}^n = \frac{2}{3} \times \frac{2}{3} \times \frac{2}{3} \times \frac{2}{3} .... = 0.\dot{6} \times 0.\dot{6} \times 0.\dot{6} ... = 0$
so your solution will come out to $\frac{1}{3}$
Answer: Also old style comparison:
$$
n>1\implies 3^n-2^n=2^n((3/2)^n-1)\ge2^n\implies
\frac1{3^n-2^n}\le\frac1{2^n}.
$$
Comment: @πr8, thanks for the correction.


Informações no Titulo - WPF

Question: Eu tenho uma aplicação onde o usuário pode selecionar a empresa a ser trabalhada.
Quando ele selecionar, gostaria que essas informações fossem para o Título da aplicação... Isso é possível?
O atributo Title está na janela pai. Já este evento MouseDoubleClick está em um UserControl filho... Esta é minha duvida, como passar do filho para o Pai..
Por enquanto eu tenho esse TextBlock para poder adicionar a informação no titulo:
<TextBlock Text="{Binding Titulo, RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}" HorizontalAlignment="Center" VerticalAlignment="Top"/>

Titulo:
private string _titulo;

    public string Titulo
    {
        get
        {
            return _titulo;
        }
        set
        {
            _titulo = value;
        }
    }

O que posso fazer aqui quando o usuário selecionar?
private void dataGridEmpresa_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {

          --- AQUI! ---

    }

Depois da alteração:
<my:EscolherEmpresa TitleValue="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}, Mode=OneWayToSource}"/>

Onde eu abro a UserControl:
private void main_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.F5){

            tbTitulo.Text = "ESCOLHER EMPRESA PARA TRABALHAR";

            MainMdiContainer.Children.Clear();
            MainMdiContainer.Children.Add(new MdiChild()
            {
                Margin = new Thickness(-10, -28, 0, 0),
                Width = this.Width - 20,
                Height = this.Height - 113,
                //WindowState = System.Windows.WindowState.Maximized,
                Style = null,
                Content = new Telas.EscolherEmpresa()
            });
        }

    }

Comment: Onde está exactamente a sua dificuldade? Está em como construir o *binding* no *xaml*, na implementação da interface *INotifyPropertyChanged* na classe que tem a propriedade *Titulo* ou está em como extrair, da *Grid*, o campo *titulo* no método `dataGridEmpresa_MouseDoubleClick()`?
Comment: Não estou utilizando MVVM @ramaral, Queria apenas levar algumas informações de meu DataGrid para o titulo da aplicação..
Comment: OK, mas a informação continua a ser pouca. Você fala num *TextBlock*, quer que essa informação seja colocada nele ou no atributo *Title* da *Window*. Se for no atributo basta, depois de ter essa informação, fazer no método `dataGridEmpresa_MouseDoubleClick()` `this.Title = varialvelQueTem_a_Infromacao;`
Comment: Então, mas o atributo Title está na janela pai. Já este evento MouseDoubleClick está em um UserControl filho... Esta é minha duvida, como passar do filho para o Pai...
Comment: Na pergunta você não fala isso.
Comment: Desculpa @ramaral, eu alterei a perguta.
Answer: Não testei mas julgo que isto faz o que pretende.
No UserControl declare uma DependencyProperty
public string TitleValue
{
    get { return (string)GetValue(TitleValueProperty); }
    set { SetValue(TitleValueProperty, value); }
}

public static readonly DependencyProperty TitleValueProperty =
    DependencyProperty.Register("TitleValue", typeof(string),
                                 typeof(UserControl1));//Nome da classe do UserControl

No XAML da Window ao incluir o UserControl:
<my:UserControl1 TitleValue="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}, Mode=OneWayToSource}"/>

No método dataGridEmpresa_MouseDoubleClick():
private void dataGridEmpresa_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{

   string title = //Obtenha o titulo
   TitleValue = title;
}

Comment: apareceu o meu UserControl inteiro la em cima no titulo no pequeno espaço. Fiz algo de errado? Postei a imagem de como ficou la em cima no post
Comment: Quando estou na tela principal (Window Pai), eu dou um F5 e abre o meu UserControl. Dai que eu consigo selecionar a empresa a ser escolhida..
Comment: Poste o código onde abre o *UserControl*.
Comment: Coloquei na pergunta...
Comment: Assim não é fácil ajudar, você não refere em lado algum que está a usar a uma *api* externa ao *WPF*. Julgo que seja a *WPF.MDI.DLL*. Eu nunca a utilizei por isso não posso ajudá-lo.
Comment: Estou utilizando sim essa DLL. Mas de qualquer forma eu agradeço então..

Informações no Titulo - WPF


React Native - text input não perde o foco

Question: Coloquei um <TextInput/> para fazer a ação de busca no meu projeto, mas depois que eu clico nesse <TextInput/>, o foco não sai mais dele, não importa onde clique na tela, a função onBlur() sequer é executada e não apresenta nenhum erro, mesmo se eu for para outra página e voltar para a tela que tem esse <TextInput/>, aquela barrinha que fica piscando quando vamos digitar, continua piscando, já tentei busquei por vários exemplos de <TextInput/> e todos apresentam esse mesmo problema, deve ser algo muito bobo, mas eu não consigo resolver de jeito nenhum. Aqui está o código que estou testando agora.

import {
  StatusBar,
  View,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  SafeAreaView,
} from 'react-native';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      borderColor: '#fff',
    };
  }

  onFocus() {
    this.setState({
      borderColor: '#000',
    });
  }

  onBlur() {
    this.setState({
      borderColor: '#fff',
    });
  }

  render() {
    return (
      <View
        style={{
          width: '100%',
          height: '100%',
          backgroundColor: '#363A44',
          alignItems: 'center',
        }}>
        <StatusBar
          barStyle="light-content"
          hidden={false}
          backgroundColor="#000"
        />
        <TextInput
          onBlur={() => this.onBlur()}
          onFocus={() => this.onFocus()}
          style={{
            height: 40,
            width: 100,
            borderWidth: 1,
            borderColor: this.state.borderColor,
          }}
        />
      </View>
    );
  }
}

export default App;```

Comment: Não esta a ocorrer erro algum, como você diz, nesse código. https://snack.expo.io/@sant0will/a2e726
Comment: Abra esse link que vc me mandou e coloque para rodar no Android, clique no `TextInput` e depois tente clicar fora dele.
Comment: certo certo, entendi
Answer: O seu problema é recorrente no React Native, ele acontece basicamente por que a View não consegue detectar os toques na tela. Como alternativa, você poderá trocar sua View master por uma ScrollView configurada para aceitar os toques na tela.
Baiscamente basta alterar:
<View
    style={{
      width: '100%',
      height: '100%',
      backgroundColor: '#363A44',
      alignItems: 'center',
    }}>
    <StatusBar
      barStyle="light-content"
      hidden={false}
      backgroundColor="#000"
    />
    <TextInput
      onBlur={() => this.onBlur()}
      onFocus={() => this.onFocus()}
      style={{
        height: 40,
        width: 100,
        borderWidth: 1,
        borderColor: this.state.borderColor,
      }}
    />
</View>

Por:
<ScrollView
    style={{
      width: '100%',
      height: '100%',
      backgroundColor: '#363A44',
      alignItems: 'center',
    }}
    scrollEnabled={false}
    keyboardShouldPersistTaps='handled'>
    <StatusBar
      barStyle="light-content"
      hidden={false}
      backgroundColor="#000"
    />
    <TextInput
      onBlur={() => this.onBlur()}
      onFocus={() => this.onFocus()}
      style={{
        height: 40,
        width: 100,
        borderWidth: 1,
        borderColor: this.state.borderColor,
      }}
    />
</ScrollView>

scrollEnabled: Deixa a view estatica, sem o scroll.
keyboardShouldPersistTaps: Habilita a possibilidade de tocar a área fora do teclado.
Exemplo funcionando
Comment: Entendi, eu coloquei o `` mas ai o problema foi que eu precisei usar um `` e dentro do `` ele não funcionava, ai eu consegui resolver com ``, valeu pela ajuda.


SimpleOnGestureListener not working

Question: I want to change between activities by swiping in my MainActivity. I declared an object from GestureDetectorCompat and initialized it in method onCreate like that:
gestureObject = new GestureDetectorCompat(MainActivity.this, new GestureListener());

Also, I override onTouchEvent like that:
@Override
public boolean onTouchEvent(MotionEvent event) {
    this.gestureObject.onTouchEvent(event);
    return super.onTouchEvent(event);
}

and my MainActivity extends from AppCompatActivity and implements NavigationView.OnNavigationItemSelectedListener, OnMenuItemClickListener.
GestureListener code is:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public void onLongPress(MotionEvent e) {
        Log.e(TAG, "long pressed");
        super.onLongPress(e);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        Log.e(TAG, "on Flig");

        if (e2.getX() > e1.getX()) {

            Log.e(TAG, "left to right");
        }
        return true;
    }
}

but it does not work.
Is it related to navigationView?
What can I do?
Comment: You might want to take a look at [ViewPager](https://developer.android.com/training/animation/screen-slide.html)
Comment: I have activity, not fragment.
Comment: How does it not work: crashes, error messages, freezes, unexpected behaviour or hordes of locusts?
Comment: Do not anything.
Answer: Try this code..
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class MainActivity extends AppCompatActivity {

private GestureDetectorCompat mDetector;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDetector = new GestureDetectorCompat(MainActivity.this, new SwipeGestureDetector());
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
    this.mDetector.onTouchEvent(motionEvent);
    return super.onTouchEvent(motionEvent);
}

@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
    super.dispatchTouchEvent(ev);
    return mDetector.onTouchEvent(ev);
}

/**
 * Swipe Gesture Detector Class for swipe detector.
 */
public class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if(e1 == null || e2 == null)
            return false;
        if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1)
            return false;
        else {
            try {
                float diffX = e2.getX() - e1.getX();
                float diffY = e2.getY() - e1.getY();
                if(Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > 100 && Math.abs(velocityX) > 1000) {
                        if ((diffX > 0) || (diffX < 0)) {
//                                      nextActivity();

                                return true;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
            return false;
        }
    }
}

}
Comment: Send me full code with all listener (NavigationView.OnNavigationItemSelectedListener, OnMenuItemClickListener.) So, i can figure out where is problem in your code.
Answer: Try this,
@Override
public boolean onTouchEvent(MotionEvent event) {
    this.gestureObject.onTouchEvent(event);
    return true;
}

SimpleOnGestureListener not working


How repeating field values in "EntityReference select list widget" as I would with "autocomplete widget"

Question: my question is how to display "select list widget" like "autocomplete widget" when
I create or edit an entity, I mean with "add another field". I need this
because I need repeating field values in "EntityReference select list
widget" as I would with "autocomplete widget" or as shown in the module "Double Field".
thanks and sorry for my english
Answer: I found everything I was looking for in the Multiple Selects module. Here is a quote about it (from the module's project page):

... provides a widget called Multiple Selects list for the the following fields types:

entity_reference
node_reference
user_reference
taxonomy_term_reference
list_integer
list_float
list_text
list_boolean
commerce_product_reference

Rather than having a multi-select field, this modules allows you to have multiple select fields with the traditional FieldAPI 'Add another item' button.


why my website display in FB Login window After Login through facebook?

Question: I am Integrating Face book application with Our Website.
My Website is in Java's [Google Web Toolkit] Framework 2.0.1
When we press FB-connect connect then FB's Login window comes, after that user enters
email & pwd.

When user clicks FB's connect button  then Our website display in that Login  window.
   Authentication and  Connect Url is Proper http://localhost:8090/websitename/
  How to solve this problem ?
  Where I did mistake ?
  Is there any solution?

When I did same thing in GWT's development/Hosted mode with Authentication and  Connect url  http:/127.0.0.1:8888/ then works properly.
Then why It create Probelm in localhost? :-/
Answer: On some browsers, localhost is not allowed to save cookies.
Try to deploy the app to see if the problem goes away.
Comment: ...Or try a different browser that may allow localhost to store cookies.
Comment: Thanks for Reply
Hello Friend[zz coder].
I tried it in safari,Google chrome,same thing happen.
One thing i forgot to mention that ,Initially same problem not occurs in Local host.

Hope for BEST Co-operation from your side
Answer: I create new application, and provide My website url in Everywhere i.e
 authentication : Post-Authorize Callback URL / Post-Remove Callback URL
 Canvas : Canvas Callback URL
 Connect : Connect URL / Account Preview URL.
And my problem is solved Now :) !!!


proof that L is regular

Question: Given that $A$ is a regular language and $B$ a regular or non-regular language, prove that $L$ is regular:
$$L = \{w | wx \in \text{A such that }x \in B\}$$
We can say that L is a subset of A. Regular languages are not closed under subsetting and I can't find a way to prove that this subset is regular regardless of B.
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: This is a quotient, not a subset. $L$ is not a subset of $A$, in general.
Answer:
Let $A$ be a regular language and let $B$ be any language.

Because $A$ is regular, there's a deterministic finite automaton that accepts $A$. Let $M$ be one such machine, with a set of states $Q$ and set of accepting states $F\subseteq Q$.

It is possible to modify the machine $M$ to make a machine that accepts the quotient language $L=\{w \;|\;  \exists x : wx\in A\wedge\, x\in B  \}$.

Indeed, for any state $q\in Q$ and any arbitrary string $x\in \Sigma^*$, let $\delta(q, x)$ denote the state that $M$ is in after it starts from the state $q$ and reads the string $x$.

Define a new machine $M^\prime$ which is exactly like $M$ except it has a new set $F^\prime$ of accepting states. The new accepting states are $$F^\prime \equiv \bigcup_{x \in B } \{q \in Q : \delta(q,x) \in F\}.$$
In other words, we consider each state $q$ in turn. We imagine feeding each string $x\in B$ into the machine starting from state $q$. If the machine ends up in an accepting state after reading some string $x$, then $q$ should be marked as an accepting state in the new machine. Otherwise, $q$ should be marked as a non-accepting state in the new machine.

This new machine $M^\prime$ accepts the language $L$. It is a deterministic finite automaton, so $L$ is a regular language.

Note that this proof is nonconstructive—if $B$ is a very complicated language, it may be difficult or impossible to compute the set of states $F^\prime \subseteq Q$.  Nonetheless, $F^\prime$ exists as a well-defined subset of $Q$. It exists even if we cannot confirm what it is, and so the machine $M^\prime$ exists, even if we cannot confirm what it is.

See: Quotient of a regular language

proof that L is regular


In Le Mans, what are the 3 lights on the side of the car?

Question:
In Le Mans, all cars have 3 lights on the side.
The color part is easy: It is the color of the series you are racing in.
But sometimes 1 is lit, other times it is 2 or 3.
What is the logic of those lights?
Answer: These are apparently called "leader lights", and they indicate that the car is currently in the top three in its class. If you have one leader light on, you're currently 1st in your class; two leader lights means you're 2nd; three means you're 3rd; and if they're all off, that means you're 4th or below.
As an example, you can see in your screenshot that the #22 car is currently leading the LMP2 class, and accordingly, it only has one leader light on.
I believe that the purpose of these lights is to make it easier for spectators at the track - who don't have the TV graphics available to them - to tell who's actually winning. Endurance racing has much greater field spread than, say, Formula One, with cars often ending up multiple laps behind the one in front, making it hard to tell at a glance who's in what position.
Answer: First answer is very good.
So I add just a small addition with the color code for who reads in future.
The lights make it easier to spot the first 3 leaders for each category, especially during the night for people who are spectators there at the track.
LM P1 or Hypercar LMH / LMDh - red lights
(also the car number is on red background with P1 or HYPER CAR red text next to it)
LM P2 - blue lights
(the car number is on blue background with P2 blue text next to it)
GTE PRO - green lights
(the car number is on green background with PRO green text next to it)
GTE AM - orange / amber lights
(the car number is on orange background with AM orange text next to it)


Allowing users to create calculated views

Question: I am using Views 3 and I was able to do some math on the fields using the "Views Custom Field" module that was recommended to me.
It works perfectly and does exactly what I want it to do, but my problem is that I need to grant access to users to create views and calculations on them.  Views custom field is not really a math only field, it's basically allowing them to execute PHP code directly on my site, which I suspect is dangerous.
Also, another requirement is that they are not directly modifying the actual data, but creating a view for themselves(or to share) that derived from this data. That means the view they create must somehow be connected to their ID and not modify the master data.
I don't know if it is the best approach, but I was thinking of using something like phpexcel and exposing the tables so they can link to certain data; it seems complicated for me and even more complicated for the users.
How would you approach this?
Answer: You are right, you shouldn't allow people to change php code on your site.
I would allow a lot of customization to the data that is returned via views filters.
You can return the data in a table format and allow this table to be exported to excel or csv (there are views modules for both of these). Then people can create whatever they want.
There are a few js libraries which can give you spreadsheet like functionality in the browser with an HTML table, that may be an option too.
Comment: Thanks Jeremy.  I've seen that there are different libraries but exposing my database to the site only seems like the tricky part.  Not sure how thats possible to do(and less technical for the user).  Maybe the final output to excel isn't a bad idea, but as much as possible I want to keep them on the site.  Is there a way to only allow certain math operators? or a allow users to run a restricted version of php where they only have access to querying certain tables
Comment: No, giving php is all or nothing. If you want to keep them on the site, look at using a JS lib to make the site look like a spreadsheet.


Stop a process (script) from invoking oom killer

Question: I had a very unfortunate situation, where a bash script that contained a subtle error gone wild and took all available memory and then started killing other tasks (production apps!) to get even more.
How can I future-proof invocations of this and other scripts so when they reached memory limit they fall themselves and not kill other apps?
I'd prefer something I could incorporate into the text of the script.
Comment: You are running Linux, presumably? bash runs on several operating systems.
Comment: @JohnMahowald yes, Ubuntu 16.04
Answer: On Linux,  https://www.kernel.org/doc/Documentation/sysctl/vm.txt  documents a variety of tunables for the virtual memory system.
For example, vm.oom_kill_allocating_task=1

If this is set to non-zero, the OOM killer simply kills the task that
  triggered the out-of-memory condition.  This avoids the expensive
  tasklist scan.

There is no guarantee your production apps won't be the ones triggering the OOM. But a runaway allocation is more likely to hit it.
There also is a score you can tweak to weight specific processes more or less likely to be murdered for their memory.  /proc/$PID/oom_adj.   Although, you probably want to set it in your init scripts.  systemd.exec  has  OOMScoreAdjust.
You may disable the OOM killer entirely. However, in extreme memory pressure the system may not be able to respond, or panic.
Answer: ulimit -m will let you set a core (well, RSS) limit applicable to a process, and ulimit -v will let you do likewise for the VM footprint.
Comment: So, I ended up with a mix of @MadHatter and @JohnMahowald answers. First, `ulimit -m` is deprecated (see https://unix.stackexchange.com/a/129592/285241), second, `vm.oom_kill_allocating_task=1` won't help, because both offending script and prod apps are allocating actively. Which led me to using `ulimit -v` and `echo 1000 > /proc/self/oom_score_adj`
Answer: You can use supervisord to manage process.
Supervisor can set memory quota.


How to run anaconda python with "execute a process" in Pentaho(PDI) in windows?

Question: I'm going to run a python program by "execute a process" in pdi and on a specific anaconda environment.
This is my solution which didn't work:

run_on_win = "C:\Users\x\Anaconda3\Scripts\activate.bat & python"

api_call = my python file

Remains fields are my parameters

How these commands, which run successfully on cmd, raise this error in PDI?
 Cannot run program "C:\Users\x\Anaconda3\Scripts\activate.bat & python": CreateProcess error=2, The system cannot find the file specified
Answer: At the end I created a .bat file with this content:
conda activate churn & python %*
the I assigned the path of that .bat file to run_on_win variable
Answer: Try specifying the complete path of python.exe


View of Node revisions exclude first revision of each node

Question: I have a view of Node revisions. I want to only show revisions that are edits. I want to exclude the first revision of each node.
I think filtering for created <> changed would work, but I could find a filter in views, or a contrib module that does this.
Is there a way to do this without writing a custom view filter plugin?
Comment: Couldn't it also be true that the highest revision id is not necessarily the published or current one? Is it possible to query for node revisions whos state is not published?
Comment: I am only looking to exclude the first revision. The publish state, and if it is the current revision or not does not matter to me.
Answer:
Is there a way to do this without writing a custom view filter plugin?

I'm afraid not.

I am only looking to exclude the first revision.

mymodule/mymodule.module
<?php

/**
 * Implements hook_views_data().
 */
function mymodule_views_data() {
  $data = [];

  $data['node_revision']['exclude_first_node_revision_filter'] = [
    'title' => t('Exclude first node revision'),
    'help' => t('Excludes the first node revision.'),
    'filter' => ['id' => 'exclude_first_node_revision_filter'],
  ];

  return $data;
}

mymodule/src/Plugin/views/filter/ExcludeFirstNodeRevisionFilter.php
<?php

namespace Drupal\mymodule\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\views\ViewExecutable;

/**
 * @ViewsFilter("exclude_first_node_revision_filter")
 */
class ExcludeFirstNodeRevisionFilter extends FilterPluginBase {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

    $this->valueTitle = t('Exclude first node revision');
    $this->definition['options callback'] = [$this, 'generateOptions'];
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    $this->ensureMyTable();

    // Exclude the first revision of each node.
    $this->query->addWhereExpression($this->options['group'], "node_revision.vid <> (SELECT MIN(vid) FROM {node_field_revision} WHERE nid = node_revision.nid)");
  }

  /**
   * {@inheritdoc}
   */
  public function adminSummary() {
  }

  /**
   * {@inheritdoc}
   */
  protected function operatorForm(&$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function canExpose() {
    return FALSE;
  }

}


Drum Theory Resources

Question: I recently started using drum software to create drum tracks for music I play on guitar. I know nothing of drum theory, so I feel rather lost.
Are there any online resources and/or books that would give me sufficient knowledge of drum theory that would give me better insight as to creating drum tracks?
Comment: Questions about requesting external resources are [off-topic here](https://music.stackexchange.com/help/on-topic).
Comment: @David Bowling, seeing as this question and its accepted answer are from 2014, there's gotta be a way to brand this question as historic, right? I think I've seen the "historic" label on this stack exchange before....
Comment: @Dekkadeci -- [You should vote to close off-topic questions, no matter how old](https://meta.stackexchange.com/questions/220986/how-to-flag-historic-off-topic-questions), and I don't see the value in keeping this one open. It shouldn't be kept open just because it has an accepted answer or because the question has remained open for a few years. A mod could lock this as historical, [but that probably does not fit this question](https://meta.stackexchange.com/questions/126587/what-is-a-historical-lock-and-what-is-it-used-for) since it is not a great question that has been very popular.
Comment: I'm voting to close this question as off-topic because the help center states that questions should not be about "requesting external resources (questions should be specific and answerable on this site; external links are for references and supporting material)."
Answer: As a guitarist who also does some beatmaking/computer music production myself, I understand where you are coming from. I'm not a drummer, so I can't really offer solid theory per se, but I can give you some advice to get started.
Listening to beats in songs you like is a great place to start. Listen for the kick drum, snare drum, and hi-hats.  For rock, pop, hip-hop, jazz, blues, and any genres that use a drum kit, those are the three main components that make up a beat.  Even newer EDM type stuff is based on those three drums, with some variations thrown in.
Depending on which software you use I have found Youtube to be a pretty good resource for this kind of thing as well. For a more specific details, let me know what software you are using and what music genre you are aiming for.
Quick tip: Snare on beats 2 and 4, bass/kick drum on 1 and 3, and hihats on eighth-notes is the standard starting place for most rock/pop drumbeats.  You'll recognize it once you hear it.
A couple ones I have found helpful on Youtube:
Dubspot
Point Blank
they both offer paid classes, but they have a lot of free content up on Youtube as well. I really can't overstate the usefulness of Youtube in this siutation.
Edit 2 after comment:
I use Ableton Live which uses more of a grid-based approach, where you either play the keyboard or just draw in the notes one-by one on a rhythm grid. But in general, in hard rock or metal, its the same general beat I described, but usually they just do more with the bass/kick drum. In metal especially there is a lot of fast kick drumming, where they use two foot pedals or even two kick drums to punch out the rhythm in 1/8th notes, 16ths, or even 1/32 notes. Also they hit the snare on beats 2 and 4 as usual, and instead of a hi-hat they will ride the 1/8 notes on cymbals for a heavier sound. (standard rock example with fills / metal example / hard rock example with more kick/snare variations)  Of course on top of the standard beat they will throw in fills that include more cymbals and the toms, but those are usually just variations used between sections and require more complex patterns and explanations.
From what I can tell, Ez Drummer uses a different approach where it has a lot of built in beats and loops that you play around with to find a combination you like.  I don't see much about programming in beats yourself, and although I'm sure thats possible, for your purposes it seems more like you can just mix and match with the presets they have built in.
Again, with this type of thing its much easier to SHOW you than TELL you, so here are a couple examples:

And more where that came from:
https://www.youtube.com/results?search_query=ezdrummer+2+tutorial+
Comment: I use EZdrummer 2. My main obstacle is to translate the beat in my head to the software, but I get the feeling it will get better with time. I'm not aiming for a specific genre, but at the moment I'm trying to create hard rock/metal music. What software do you use?
Comment: More above, but like any instrument, even virtual drums will take practice. The more beats you make and the more familiar you get with the software, the better you get at translating whats in your head to what comes out of your speakers. For your purposes it might help to try to tap out rhythms on a keyboard (you can use a MIDI keyboard, or some software allows you to use the computer keyboard). That might give you a more direct connection between whats in your head and what comes out.  This is a skill all in itself that requires practice as well (see: finger-drumming/controllerism).
Comment: I agree that using a MIDI keyboard would be a good idea, however I'd prefer if I could use my computer keyboard. What is that function called, using your computer keyboard instead of a MIDI keyboard? All results I find via google search are MIDI keyboard related instead of computer keyboard, perhaps I'm lacking the proper terminology?
Comment: I don't think there is a standard name for it. Garage Band I believe lets you do it by default. Are you running EZ Drummer through GarageBand or by itself? Either way (two different links):
http://homerecording.com/bbs/general-discussions/newbies/can-i-use-my-laptop-keyboard-play-ezdrummer-336839/
http://www.ehow.com/how_6859493_do-ez-drummer-standard-keyboard_.html
Answer: As a drummer, I'll recommend you the same thing as Charles did: listen to the songs you like and you want to get inspired from.
Now if you want some typical beats in every genre, from the easiest to the hardest, Onlinedrummer.com is a good website where you can find some drum beats, how it is written (drumly speaking) and how it sounds. When I lack inspiration, this is one of the website I'm visiting, they are really diversified.
Then if you want to make your drums sound better... Well it should exist plenty of tutorials teaching you how to build a good rock/jazz/blues/EDM drumkit, according to the software you are using.
But as Charles said: listen, listen, listen and listen to songs, this is the only way you will realize that the world of drums is really a coded world.

Drum Theory Resources