Music and Maths - Is there a way to prove that there are only 7 Modes of Limited Transposition?

Question: 'Modes of limited transposition' are modes that have a limited availability of transpositions. Unlike a major scale that has 12 possible unique transpositions, the seven modes of limited transposition have fewer than 12 possibilities of transposition.
French Composer Olivier Messiaen coined this idea, and he wrote, "Their series is closed, it is mathematically impossible to find others, at least in our tempered system of 12 semitones." I want to try and figure out why. Might anyone have any idea how I could use mathematics to prove this statement?
Comment: By 'mathematically', I think he meant 'by using patterns of tones/semitones', rather than pure maths. While the term 'modes' is technically correct, I wish he'd have come up with a different term - there's enough modes, as we know them, without adding to the list...
Comment: @Tim Can you explain a bit more what you mean by your comment?
Comment: Messiaen used the term mode because that's what a set of notes, with tone/semitone spaces, in particular order, is. It's just that there are many, many modes that already exist, such as church, Ambrosian, modern, all with their own special 'foibles', and differs, so when Mesiaen decided to embark on his thesis, adding his own 'modes' to what already existed muddied things (for me). Even calling them scales may have simplified things. Just my view...
Answer: Well, to give a boring answer to how it can be proved – since there are only finitely many subsets of the 12 tones (namely, 4096), you can just list them all and check exhaustively. But we can be a bit more efficient than that.
There's not really such a thing as limited transposition. What characterises these scales is that some of the transpositions will be enharmonically equivalent to the original. In other words, there's a transpositional symmetry in the scale. (Mathematically, you could say the group of transpositions contains nontrivial equivalences classes with respect to action on those scales.)
In effect, this boils down to these scales splitting up into several equal parts. Because 12 has the integer factors 2, 3, 4 and 6, that means you have the following options, omitting scales that are equivalent by global transposition and omitting the scales that have additional finer-grained symmetry:

Size-2 blocks: s0=□□, s1=■□, s2=■■
Size-3 blocks: □□□≃s0, s3=■□□, s4=■■□, ■■■=s2
Size-4 blocks: □□□□≃s0, s5=■□□□, s6=■■□□, ■□■□=s1, s7=■■■□, ■■■■=s2
Size-6 blocks: □□□□□□≃s0, s8=■□□□□□, s9=■■□□□□, s10=■□■□□□, ■□□■□□=s3, s11=■■■□□□, s12=■■□■□□, s13=■■□□■□, ■□■□■□≃s1, s14=■■■■□□, s15=■■■□■□, ■■□■■□≃s4, s16=■■■■■□, ■■■■■■≃s1

Putting it back together again, that means we have these 17 note-sets which have a transpositional symmetry:
□□□□□□□□□□□□, ■□□□□□■□□□□□, ■■□□□□■■□□□□, ■□□□■□□□■□□□, ■□■□□□■□■□□□, ■■■□□□■■■□□□, ■□□■□□■□□■□□, ■■□■□□■■□■□□, ■■□□■■□□■■□□, ■□■■□□■□■■□□, ■■■■□□■■■■□□, ■□■□■□■□■□■□, ■■■□■□■■■□■□, ■■□■■□■■□■■□, ■■■□■■■□■■■□, ■■■■■□■■■■■□, ■■■■■■■■■■■■
From these we can manually filter out those that Messiaen considers "modes", as those that have no steps larger than two semitones and aren't simply the full chromatic scale:
■□■□■□■□■□■□, ■■■□■□■■■□■□, ■■□■■□■■□■■□, ■■■□■■■□■■■□, ■■■■■□■■■■■□
For reasons that are a bit mysterious to me, he also includes ■■■■□□■■■■□□ and ■■■□□□■■■□□□, though these have bigger steps in them.
Comment: I wonder if using Cayley tables would be clearer. Maybe clearer to the mathematical mind but less clear to the musical one.
Comment: I know that this answer is incredibly useful, but from a mathematical perspective (I don't have too much of a music theory background) I somewhat struggle to comprehend it!
Comment: @DPJDPJ so, what is not clear? –I mean, I didn't really use any group theory here since most people on the site don't have too much of a maths background. This could of course be expressed more elegantly by talking about subgroups, but I daresay the stupid manual enumeration approach is clear enough as well?
Answer: I have made a video with list them all and check exhaustively approach

Here is the code
https://codesandbox.io/s/basicaccordion-material-demo-forked-ggkek?file=/index.js
https://gist.github.com/srghma/3d28ecf2db90edffe66302466c68e5ce
the
      if (R.toPairs(xs).length >= 12) { return "" }

filters non-12 scales
You can use
https://guichaoua.gitlab.io/web-hexachord/
https://cifkao.github.io/tonnetz-viz/
to visualize tonnetz
import * as React from 'react'
import { useState } from 'react'
import ReactDOM from 'react-dom'
import { StyledEngineProvider } from '@mui/material/styles'
import * as R from 'ramda'
import * as RA from 'ramda-adjunct'
import { useMIDI, useMIDIOutput } from '@react-midi/hooks'
// import { Pcset } from "@tonaljs/tonal"
//
// TODO: calculate Forte number
// TODO: is generated by "Ervin Wilson's Hexany" (not cube https://www.youtube.com/watch?v=-GeR8XbFxvI)
// TODO: perfect vs imperfect scale http://allthescales.org/scales.php?n=6

// What is a scale?
// 1. A scale starts on the root tone.
// 1. A scale does not have any leaps greater than n semitones.
// chroma, valid colors https://github.com/tonaljs/tonal/blob/9622ec8fa4031f0c80515d278dfa06424bf159e5/packages/pcset/index.ts#L161

// does scale have refl symm (palyndrome), IF yes THEN is it chiral

function assert(x, y) {
  if (!R.equals(x, y)) {
    console.log({ x, y })
    throw new Error('assert')
  }
}

//////////////////////

const arrRotateLeft1Mutate = a => {
  a.push(a.shift())
}
const arrRotateRight1Mutate = a => {
  a.unshift(a.pop())
}
const arrRotateLeft = (a, n) => {
  const a_ = [...a]
  while (n > 0) {
    arrRotateLeft1Mutate(a_)
    n--
  }
  return a_
}
const arrRotateRight = (a, n) => {
  const a_ = [...a]
  while (n > 0) {
    arrRotateRight1Mutate(a_)
    n--
  }
  return a_
}
//////////////////////

const binaryToDecimal = x => parseInt(x, 2)

assert(binaryToDecimal("010101010101"), 1365)
assert(binaryToDecimal("101010101010"), 2730)

const decimalToBinary = x => x.toString(2)

//////////////////////

// https://en.wikipedia.org/wiki/Interval_(music)
const numberOfNotesForPerfectUnison = 12

const endingBigEndianBinary = R.times(R.always("1"), numberOfNotesForPerfectUnison).join('')
const endingDecimals = binaryToDecimal(endingBigEndianBinary)
assert(endingDecimals, 4095)

let chords = R.range(1, endingDecimals + 1)
chords = chords.map(decimalToBinary)
chords = chords.map(x => RA.padCharsStart("0", numberOfNotesForPerfectUnison, x))

assert(R.head(chords), "000000000001")
assert(R.last(chords), "111111111111")

const rotateUntil = (predicate, a) => {
  const a_ = [...a]
  let n = 0
  while (predicate(a_[0]) !== true) {
    if (n > a.length) {
      throw new Error(`rotateUntil: maxTimes for ${JSON.stringify(a)}`)
    }
    arrRotateLeft1Mutate(a_)
    n++
  }

  if (typeof a === 'string') { return a_.join('') }
  return a_
}

assert(rotateUntil(x => x[0] === "1", "010101010101"), "101010101010")
assert(rotateUntil(x => x[0] === "1", "101010101010"), "101010101010")
assert(rotateUntil(x => x[0] === "1", "000101010101"), "101010101000")

function binaryToIndexesOfEnabledNotes(binary) {
  // if (binary[0] !== "1" || binary.length !== 12) { throw new Error(binary) }

  // console.log(binary)
  return binary.split('').map((x, index) => {
    // console.log({ x, index })
    if (x === "0") { return undefined }
    if (x === "1") { return index }
    throw new Error('binaryToIndexesOfEnabledNotes')
  }).filter(x => x !== undefined)
}

assert(binaryToIndexesOfEnabledNotes("000000000000"), [])
assert(binaryToIndexesOfEnabledNotes("111111111111"), [0,1,2,3,4,5,6,7,8,9,10,11])
assert(binaryToIndexesOfEnabledNotes("010101010101"), [1,3,5,7,9,11])
assert(binaryToIndexesOfEnabledNotes("101010101010"), [0,2,4,6,8,10])
assert(binaryToIndexesOfEnabledNotes("101111111111"), [0,2,3,4,5,6,7,8,9,10,11])

// https://github.com/AtActionPark/Pianissimo/blob/master/lib/theory.js
// https://felixroos.github.io/pitch-class-sets
function indexesOfEnabledNotesToPitchClassSet(indexesOfEnabledNotes) {
  const firstNoteIsEnabled = indexesOfEnabledNotes[0] === 0
  if (!firstNoteIsEnabled) { throw new Error(indexesOfEnabledNotes) }

  // indexesOfEnabledNotes = R.tail(indexesOfEnabledNotes)

  const output = indexesOfEnabledNotes.reduce((accumulator, value, index, array) => {
    let nextIndexOfEnabledNotes = array[index + 1]

    if (nextIndexOfEnabledNotes === undefined) { nextIndexOfEnabledNotes = numberOfNotesForPerfectUnison }

    // console.log({ accumulator, value, index, nextIndexOfEnabledNotes })
    accumulator.push(nextIndexOfEnabledNotes - value)
    return accumulator
  }, [])

  // console.log(output)

  return output
}

assert(indexesOfEnabledNotesToPitchClassSet([0,1,2,3,4,5,6,7,8,9,10,11]), [1,1,1,1,1,1,1,1,1,1,1,1])
assert(indexesOfEnabledNotesToPitchClassSet([0,1,2,3,4,5,6,7,8,9,10,11]), [1,1,1,1,1,1,1,1,1,1,1,1])
assert(indexesOfEnabledNotesToPitchClassSet([0,2,3,4,5,6,7,8,9,10,11]),   [2,1,1,1,1,1,1,1,1,1,1])

const permutationCycles = xs => {
  const buff = []
  for (let index = 0; index < xs.length; index++) {
    const buff_ = []
    for (let plusIndex = 0; plusIndex < xs.length; plusIndex++) {
      const indexSum = plusIndex + index
      const index_ = indexSum % xs.length
      //console.log({ index, plusIndex, indexSum, index_ })
      buff_.push(xs[index_])
    }
    buff.push(buff_)
  }
  if (typeof xs === 'string') { buff = buff.map(xs => xs.join('')) }
  return R.uniq(buff)
}

assert(permutationCycles([1]), [[1]])
assert(permutationCycles([1,2]), [[1,2], [2,1]])
assert(permutationCycles([1,2,3]), [[1,2,3], [2,3,1], [3,1,2]])
assert(permutationCycles([1,1,1,1,1,1,1,1,1,1,1,1]), [[1,1,1,1,1,1,1,1,1,1,1,1]])

const sortByLengthThenByContent = arr => {
  arr = R.groupBy(R.prop('length'), arr)
  arr = R.values(arr).map(x => x.sort()).flat()
  return arr
}

function normalizedPitchClassSet_rotationalSymmetry(pitchClassSet) {
  const scalesThatShareRotationSymmetryWithThisOne = permutationCycles(pitchClassSet)
  // console.log({pitchClassSet, scalesThatShareRotationSymmetryWithThisOne})
  return scalesThatShareRotationSymmetryWithThisOne.sort()[0]
}

assert(normalizedPitchClassSet_rotationalSymmetry([1,1,1,1,1,1,1,1,1,1,1,1]), [1,1,1,1,1,1,1,1,1,1,1,1])
assert(normalizedPitchClassSet_rotationalSymmetry([2,1,1,1,1,1,1,1,1,1,1]),   [1,1,1,1,1,1,1,1,1,1,2])
assert(normalizedPitchClassSet_rotationalSymmetry([12]),   [12])

// b.c scalesThatShareRotationSymmetryWithThisOne = [[11, 1], [1, 11]]
assert(normalizedPitchClassSet_rotationalSymmetry(indexesOfEnabledNotesToPitchClassSet(binaryToIndexesOfEnabledNotes("100000000001"))),   [1,11])
assert(normalizedPitchClassSet_rotationalSymmetry(indexesOfEnabledNotesToPitchClassSet(binaryToIndexesOfEnabledNotes("110000000000"))),   [1,11])

// function normalizedPitchClassSet_transitivity_and_inversion(pitchClassSet) {
//   return sortByLengthThenByContent(permutationCycles(pitchClassSet).map(x => [x, x.reverse()]).flat())[0]
// }

// assert(normalizedPitchClassSet_transitivity_and_inversion(binaryToIndexesOfEnabledNotes("100000000010")),   [2,10])
// assert(normalizedPitchClassSet_transitivity_and_inversion(binaryToIndexesOfEnabledNotes("101000000000")),   [2,10])

function omitUndefinedFields(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    const _acc = acc;
    if (obj[key] !== undefined) _acc[key] = obj[key];
    return _acc;
  }, {})
}

const chordToInfo = chord => {
  const isScaleAndChord = chord[0] === "1"

  const binary = binaryToDecimal(chord)
  const indexesOfEnabledNotes = binaryToIndexesOfEnabledNotes(chord)

  const commonFields = {
    isScaleAndChord,
    binary,
    indexesOfEnabledNotes,
  }

  if (isScaleAndChord) {
    const pitchClassSet = indexesOfEnabledNotesToPitchClassSet(indexesOfEnabledNotes)

    return {
      ...commonFields,
      pitchClassSet,
      normalizedPitchClassSet_rotationalSymmetry: normalizedPitchClassSet_rotationalSymmetry(pitchClassSet),
      // normalizedPitchClassSet_transitivity_and_inversion: normalizedPitchClassSet_transitivity_and_inversion(pitchClassSet),
      // scalesThatShareRotationSymmetryWithThisOne: permutationCycles(pitchClassSet),
    }
  }

  if (chord.includes("1")) {
    const approximated_scale = rotateUntil(chord_ => {
      const firstNoteIsEnabled = chord_[0] === "1"
      return firstNoteIsEnabled
    }, chord)

    return {
      ...commonFields,
      approximated_scale
    }
  }

  return commonFields
}

chords = chords.map(chord => ({ chord, ...chordToInfo(chord) }))

const chordToInfoObject = R.fromPairs(chords.map(x => [x.chord, x]))

// let scales = chords.filter(x => x.isScaleAndChord)
let scales = chords

// console.log(chordToInfoObject)

scales = R.groupBy(x => x.chord.split('').filter(x => x === "1").length, scales)

scales = R.map(
  chords => {
    return R.groupBy(
      x => {
        const info = x.isScaleAndChord ? x : chordToInfoObject[x.approximated_scale]
        // console.log(x)
        // console.log(info)
        return info.normalizedPitchClassSet_rotationalSymmetry
      },
      chords
    )
  },
  scales
)

// console.log(scales)

// scales = R.map(R.map(
//   chords => {
//     return R.groupBy(
//       x => {
//         const info = x.isScaleAndChord ? x : chordToInfoObject[x.approximated_scale]
//         // console.log(x)
//         // console.log(info)
//         return info.normalizedPitchClassSet_rotationalSymmetry
//       },
//       chords
//     )
//   }),
//   scales
// )

// console.log(scales)

// x = R.uniq(chords.map(([chord, info]) => info.pitchClassSet).filter(x => x))
// x = sortByLengthThenByContent(x)
// console.log(x)

// let x = R.uniq(chords.map(([chord, info]) => info.normalizedPitchClassSet).filter(x => x))
// x = sortByLengthThenByContent(x)
// console.log(x)

wikipediaScaleNames = `Acoustic scale   W-W-W-H-W-H-W
1st Messiaen mode   W--W--W--W--W--W
2st Messiaen mode   W-H--W-H--W-H--W-H
3st Messiaen mode   W-H-H--W-H-H--W-H-H
4st Messiaen mode   H-H-H-3H--H-H-H-3H
5st Messiaen mode   H-4H-H--H-4H-H
6st Messiaen mode   W-W-H-H--W-W-H-H
Aeolian mode or natural minor scale W-H-W-W-H-W-W
Algerian scale  W-H-3H-H-H-3H-H-W-H-W
Altered scale or Super Locrian scale    H-W-H-W-W-W-W
Augmented scale 3H-H-3H-H-3H-H
Bebop dominant scale    W-W-H-W-W-H-H-H
Blues scale 3H-W-H-H-3H-W
Chromatic scale H-H-H-H-H-H-H-H-H-H-H-H
Dorian mode W-H-W-W-W-H-W
Double harmonic scale   H-3H-H-W-H-3H-H
Enigmatic scale H-3H-W-W-W-H-H
Flamenco mode   H-3H-H-W-H-3H-H
"Gypsy" scale   W-H-3H-H-H-W-W
Half diminished scale   W-H-W-H-W-W-W
Harmonic major scale    W-W-H-W-H-3H-H
Harmonic minor scale    W-H-W-W-H-3H-H
Hirajoshi scale 2W-W-H-2W-H
Hungarian "Gypsy" scale / Hungarian minor scale W-H-3H-H-H-3H-H
Hungarian major scale   3H-H-W-H-W-H-W
In scale    H-2W-W-H-2W
Insen scale H-2W-W-3H-W
Ionian mode or major scale  W-W-H-W-W-W-H
Istrian scale   H-W-H-W-H-5H
Iwato scale H-2W-H-2W-W
Locrian mode    H-W-W-H-W-W-W
Lydian augmented scale  W-W-W-W-H-W-H
Lydian mode W-W-W-H-W-W-H
Major bebop scale   W-W-H-W-W-W-H
Major Locrian scale W-W-H-H-W-W-W
Major pentatonic scale  W-W-3H-W-3H
Melodic minor scale (descending) OR Mixolydian mode or Adonai malakh mode   W-W-H-W-W-H-W
Melodic minor scale (ascending) W-H-W-W-W-W-H
Minor pentatonic scale, Yo scale    3H-W-W-3H-W
Neapolitan major scale  H-W-W-W-W-W-H
Neapolitan minor scale  H-W-W-W-H-3H-H
Octatonic scale W-H-W-H-W-H-W-W-W-H-W-H-W-H
Persian scale   H-3H-H-H-W-3H-H
Phrygian dominant scale H-3H-H-W-H-W-W
Phrygian mode   H-W-W-W-H-W-W
Prometheus scale    W-W-W-3H-H-W
Scale of harmonics  3H-H-H-W-W-3H
Tritone scale   H-3H-W-H-3H-W
Two-semitone tritone scale  H-H-4H-H-H-4H
Ukrainian Dorian scale  W-H-3H-H-W-H-W
Vietnamese scale of harmonics   5Q-Q-H-H-W
Whole tone scale    W-W-W-W-W-W`.split('\n').map(x => x.split('\t'))
wikipediaScaleNames = wikipediaScaleNames.map(([name, pattern]) => {
  pattern = pattern.split('-').filter(Boolean).map(x => {
    let number = 0
    if (x.endsWith('Q')) { number = Number(x.replace('Q', '')) * 100 }
    if (x.endsWith('H')) { number = Number(x.replace('H', '')) }
    if (x.endsWith('W')) { number = Number(x.replace('W', '')) * 2 }
    if (x === 'H') { number = 1 }
    if (x === 'W') { number = 2 }
    if (x === 'Q') { number = 100 }
    const valid = number > 0
    if (valid) { return number }
    throw new Error(JSON.stringify({ name, pattern, x, number }))
  })
  return { name, pattern }
})
wikipediaScaleNames = R.groupBy(x => x.pattern, wikipediaScaleNames)
wikipediaScaleNames = R.map(x => {
  const valid = R.sum(x[0].pattern) === 12
  const name = x.map(x => x.name).join(' OR ')
  return `${name}${valid ? '' : ' (INVALID)'}`
}, wikipediaScaleNames)

// console.log(wikipediaScaleNames)

function InfoImplementation({ onPlay }) {
  const output = R.toPairs(scales).map(([nOfNotes, xs]) => {

    xs = R.toPairs(xs).map(([normalizedPitchClassSet_rotationalSymmetry, xs]) => {
      // const items = permutationCycles(normalizedPitchClassSet_rotationalSymmetry)
      if (R.toPairs(xs).length >= 12) { return "" }

      xs = xs.map(x => {
        if (x.isScaleAndChord) {
          const name = wikipediaScaleNames[x.pitchClassSet]
          const pitchClassSet_ = x.pitchClassSet.map(x => {
            if (x === 1) { return 'H' }
            if (x === 2) { return 'W' }
            return `${x}H`
          }).join('-')

          return
 onPlay(x.indexesOfEnabledNotes, e)}>
            {x.chord}
            {x.pitchClassSet}
            {pitchClassSet_}
            <a rel="noopener noreferrer" href={`https://ianring.com/musictheory/scales/${x.binary}`} target="_blank">{x.binary}
            {name || ''}

        }

        return
 onPlay(x.indexesOfEnabledNotes,e )}>
          {x.chord}

          <a rel="noopener noreferrer" href={`https://ianring.com/musictheory/scales/${x.binary}`} target="_blank">{x.binary}

      })

      return

rotationalSymmetry: {normalizedPitchClassSet_rotationalSymmetry}, length: {xs.length}

        {xs}

    })

    return

N of Notes: {nOfNotes}, length: {xs.length}

{xs}

  })

  return
{output}

}

const Info = React.memo(InfoImplementation)

function midiSend(onOff, { output, note, velocity, activateAfter }) {
  if (note > 12 || note < 0) { throw new Error('note') }
  const pitch = note + 60
  const timestamp = activateAfter ? window.performance.now() + activateAfter : undefined
  output.send([onOff, pitch, velocity], timestamp)
}

// https://webmidi-examples.glitch.me/
const midiNoteOn = (config) => midiSend(0x90, config)
const midiNoteOff = (config) => midiSend(0x80, config)

function App() {
  const [playingNotes, setPlayingNotes] = useState([])

  const { outputs } = useMIDI();

  if (outputs.length < 1) return
No MIDI Outputs
;

  const output = R.last(outputs)
  const velocity = 100
  const midiNotesOn = notes => {
    notes.forEach((note, index) => {
      midiNoteOn({ output, note, velocity, activateAfter: index * 500 })
    })
  }
  const midiNotesOff = notes => {
    notes.forEach((note, index) => {
      midiNoteOff({ output, note, velocity, activateAfter: undefined })
    })
  }

  const handlePlay = (notes, e) => {
    const addToExisting = e.shiftKey

    if (addToExisting) {
      midiNotesOn(notes)
      setPlayingNotes(R.uniq(playingNotes.concat(notes)))
      return
    }

    midiNotesOff(playingNotes)
    midiNotesOn(notes)
    setPlayingNotes(notes)
  }

  const handleRemoveAll = () => {
    midiNotesOff([0,1,2,3,4,5,6,7,8,9,10,11,12])
    setPlayingNotes([])
  }

  return

Using {output.name}

    <Info onPlay={handlePlay}/>

}

ReactDOM.render(
  ,
  document.querySelector("#root")
)

Answer: There are several papers on the subject. With any limited set of tones (12 in the Western Case) and choosing a subset (7 for example), there are only a finite number of combinations that fit.
For Western music, we consider a closed 8-tone scale (the last note an octave above the first). There are 12 half-step intervals to select from. There is a constraint that the intervals should span the octave. Two obvious choices are 12 half steps or 6 whole steps which yield the chromatic and whole-tone scale respectively. WIth 7 notes (the most common), one needs 5 whole steps and 2 half steps. Still, there are many arrangements. The major scale and its cyclic rotations are one possibility. While not derived this way historically, these are the most "balanced" inf various way. The link leads to one discussion on the subject. There are more (but I can't remember the exact links).
Comment: Don't [write link-only answers](https://music.stackexchange.com/help/how-to-answer), please.


Path is not properly set. Cognos will fail to start

Question: I am trying to run Cognos (using IBM Cognos Configuration). But I received this error:
[ERROR] The variable PATH is not properly set. IBM Cognos will fail to start.
When I checked my environment variables, it contains:
C:\Program Files\IBM\cognos\c10_64\bin64;
C:\Program Files\IBM\cognos\c10_64\bin;
Did I miss anything? Hoping someone could help me. Thank you in advance! :)
Comment: This doesn't seem to be a [programming](http://stackoverflow.com/help/on-topic) question?
Answer: Check the following TechNote from IBM about setting the JAVA path (this is normally the problem):
http://www-01.ibm.com/support/docview.wss?uid=swg21340128


Is it natural to have some small buzzing in the guitar?

Question: I have an Ernie Ball Music Man Majesty which plays extremely well. When I bought it it was set-up.
After 6 months I have noticed that the low E-string buzzes slightly if I pluck it moderately strongly.
I know that for lead guitar the distance of the E-string from the fretboard must be at 1.5mm or 1.75mm. Mine is exactly at 1.75mm, therefore this seems to be ok.
I just don't know if it is natural for the first frets to have some minimal buzzing or if there should be none. On the other hand this seems weird if you want a very low action.

What is the case?
Is there some book/reference where these things are clearly
explained?
Comment: 1.75mm at what fret?
What fret is buzzing? (If you fret on the first fret and it does away then it's that fret ... lets say it's the 7th fret ... you neck may need a trust adjustment... look down the neck, is it flat?

"I know that for lead guitar the distance of the E-string from the fretboard must be at 1.5mm or 1.75mm."

??? Why must it be any measurement ... let alone two specific ones.

Do some troubleshooting. Is it the fret, neck, or perhaps even the nut.
Comment: If the buzzing is not stopping the note from sustaining, and the buzzing noise isn't obvious in the sound picked up by the pickups, then hearing a little fret buzz when you play the guitar without amplification isn't a problem.
Comment: My opinion is no, not on a really good instrument.  I have played on plenty of them that are perfect... unfortunately for me, all of mine buzz somewhere. :^P
Comment: I see. But for very low action, is this possible?
Comment: Yes.. on a perfect instrument it is very possible.  Also.. strings could be your problem.. I have guitars that buzz with Ernie Ball but not with Dean Markley.  Not saying Balls are bad.. just saying try other brands.  Good luck
Comment: Thanks. I still have factory strings which are indeed Ernie Ball. I will ask my technician too. Thanks a lot!
Answer: Those measurements are not gospel. There are a lot of factors involved in setting up a guitar - one important one is personal choice! It's far better to use eyes and ears setting up than a ruler and a feeler gauge!
The neck relief and action may have settled a little, causing buzz. But you hold back information as to where it buzzes. Open? 3rd fret only? All frets up to 6th? The saddle on the 6th string may have dropped slightly, and all it needs is raising a few thous. Far more information might help bring answers.
Comment: Thanks. It is only the first couple of frets of the low E string when plucked strikingly. The highly I mentioned is on the 12th fret.
Answer: Necks are wood, and wood changes over time.  Humidity can be a factor, temperature can be a factor, etc.  The only way you can have a neck that never changes is to have it made out of something besides wood, maybe aluminum or some kind of composite.


director error in corona

Question: settings.lua
 local lang_table = {
    {image = display.newImage("en.png"), x = 600, y = 400, lang = "1033", i = 1},
    {image = display.newImage("fr.png"), x = 600, y = 400, lang = "fr", i = 2},
    {image = display.newImage("dk.png"), x = 600, y = 400, lang = "dk", i = 3},
    {image = display.newImage("ge.png"), x = 600, y = 400, lang = "ge", i = 4}                                      }

local function changelanguage (event)
  if event.phase == "ended" then
    lang_table[event.target.i].image.isVisible = false
    if event.target.i == 4 then
      lang_table[1].image.isVisible = true
      _G.value = event.target.lang
      director:changeScene("settings")
    else
      lang_table[event.target.i+1].image.isVisible = true
      _G.value = lang_table[event.target.i+1].lang
      director:changeScene("settings")
   end
  end
  return true
end

for i = 1,#lang_table do
    local img_display = lang_table[i].image
    img_display.x = lang_table[i].x
    img_display.y = lang_table[i].y
    img_display.i = lang_table[i].i
    img_display.lang = lang_table[i].lang

    if _G.value ~= lang_table[i].lang then
        img_display.isVisible = false
    end

    img_display:addEventListener("touch", changelanguage)
    langGroup:insert(img_display)
end

When I touch the image,changelanguage function is being invoked.In that function there is
director:changeScene

but this is not working.Basically,what I want is that whenever there is touch event to the image I want the same lua file to be called.But this is not happening.Then What I did was changed the function "changelanguage" to
_G.t =1
local function changelanguage (event)
    if event.phase == "ended" then
        lang_table[event.target.i].image.isVisible = false
        if event.target.i == 7 then
            lang_table[1].image.isVisible = true
            _G.value = event.target.lang
            director:changeScene("settings")
        else
            lang_table[event.target.i+1].image.isVisible = true
            _G.value = lang_table[event.target.i+1].lang
            if _G.t ==1 then
                director:changeScene("..\settings")
                _G.t = _G.t+1
            elseif _G.t ==2 then
                director:changeScene("..\..\settings")
            end
        end
    end
    return true
end

Now, it is working.But I dont know why is this happening.Can anyone suggest me why is this happening.Cant I use the same director:changeScene("settings") to change the scene again and again on touch event.
Answer: I tried using the empty scene to switch right back another scene to restart it.
At first it didn't work at all, I had to display a button in the empty scene, and attach a function to it, so that when the user presses it , it switches back to the old scene, which would restart it.
However, further Googling the problem, I found out that the Director class v. 1.3 and above, can reload the scene that you are in by simply calling it using the director:changeScene("") function!
(Read about it here:
http://rauberlabs.blogspot.com/2011/07/director-class-13.html )
So if you are in settings.lua, and you want to reload it, just include director:changeScene("settings") in the same settings.lua (as you did the first time).
of course remember to update the director.lua to the latest version.
I guess you can still download it from here:
https://bitbucket.org/ricardorauber/corona/downloads
Answer: You cannot use Director to change to a scene you are already in, eg, calling director:changeScene("settings") from within settings.lua, no.
You can do this in Storyboard, however. (It may be worth considering a switch if this is something you will be doing a lot of, alternatively you could make a file such as reset.lua and write functions within there to effectively reload any scene you liked simply by changing to reset and back to the previous scene again.)
Comment: Would it be worth creating an empty scene to switch to, which switches right back to the current scene?
Comment: Personal opinion - yes. I believe it's the easiest way of handling this situation and although perhaps not the most elegant it is certainly a functional solution/workaround.

director error in corona


Is there a function that is integrable and continuous on $[a,b]$ but that it is not uniformly continuous on $(a,b)$?

Question: Any hints or exercises that I could use. I do not know how to start this.
Answer: Hint: A continuous function on a compact set is always uniformly continuous. An assumption about integrability is superfluous here.
Comment: Dang that was fast. Teach me your ways.


tensorflow modify variables in py_func (and its grad func)

Question: In tensorflow, we can define our own op and its gradient by:
https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342
However, can we modify any variable in the computational graph in these python functions. For example in the "_MySquareGrad" function?
I assume we can get the variable by:
var  = tf.get_variable('var')

and then do something to change its value and then assign it back?
e.g.
tmp = var*10
var.assign(tmp)

Thanks!
Also when we do var*10, do we have to convert it to numpy?
Background: I'm familiar with automatic differentiation, but new to Tensorflow and Python. So please point out any syntactic problem and let me know if my intention is clear.
Comment: I would recommend you to take a look at: http://stackoverflow.com/questions/42870727/can-one-only-implement-gradient-descent-like-optimizers-with-the-code-example-fr, basically just code ur update rule in tensorflow entirely.
Comment: Here's a following-up question: https://stackoverflow.com/questions/43462376/pieces-of-numerically-identical-code-produce-drastically-different-results
Answer: You can modify the variables in the computational graph in these python functions. Your example code with tmp = var*10 will work and does not convert anything to numpy.
In fact you should try to avoid converting to numpy as much as possible since it will slow down the computation.
edit:
You can include your code to the gradient computation graph of the _MySquareGrad function doing this:
def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x

Here is a working example:
import tensorflow as tf
from tensorflow.python.framework import ops
import numpy as np

# Define custom py_func which takes also a grad op as argument:
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

# Def custom square function using np.square instead of tf.square:
def mysquare(x, name=None):

    with ops.name_scope(name, "Mysquare", [x]) as name:
        sqr_x = py_func(np.square,
                        [x],
                        [tf.float32],
                        name=name,
                        grad=_MySquareGrad)  # <-- here's the call to the gradient
        return sqr_x[0]

### Actual gradient:
##def _MySquareGrad(op, grad):
    ##x = op.inputs[0]
    ##return grad * 20 * x  # add a "small" error just to see the difference:

def _MySquareGrad(op, grad):

  #first get a Variable that was created using tf.get_variable()
  with tf.variable_scope("", reuse=True):
    var  = tf.get_variable('var')

  #now create the assign graph:
  tmp = var*10.
  assign_op = var.assign(tmp)

  #now make the assign operation part of the grad calculation graph:
  with tf.control_dependencies([assign_op]):
    x = tf.identity(op.inputs[0])

  return grad * 20 * x

with tf.Session() as sess:
    x = tf.constant([1., 2.])

    var = tf.get_variable(name="var", shape=[], initializer=tf.constant_initializer(0.2))

    y = mysquare(x)
    tf.global_variables_initializer().run()

    print(x.eval(), y.eval(), tf.gradients(y, x)[0].eval())
    print("Now var is 10 times larger:", var.eval())

Comment: Thank you so much! This is very interesting. I thought tmp = var*10, if carried out by tensorflow, was a "mini computational graph". So I wasn't sure if we can embed this "mini computation graph" in the backpropagtion of a larger computational graph.
Comment: One question, when we perform this "var.assign(tmp)" in python. Does it take effect immediately? I thought tensorflow only constructs computational graph and waits until a sess.run() to evaluate the operation. since we are already inside the backprop execution of a larger graph, are we able to perform this "var.assign(tmp)" immediately? I'm confused because it's a mini computational graph within a larger graph.
Comment: @user21707 No it does not take place immediately. Just as you say it only constructs a computational graph that will be executed once sess.run() is used on this graph, or on a larger graph that includes the small graph. I added an example showing how to add your computational graph to the larger gradient-computation graph.
Comment: Thank you so much! I solved this issue with your suggestions.
Comment: However, I have do encounter another issue. http://stackoverflow.com/questions/43462376/pieces-of-numerically-identical-code-produce-drastically-different-results


Proving that the Universe Theory implies Godel-Bernays

Question: I'm reading a book on Category Theory, and the authors claim that one gets a model of Godel-Bernays theory by choosing "sets" to be elements of the Universe and "classes" to be subsets of the Universe. I'm not able to prove how this is the case.
To make things clearer, let me state the Universe Axiom and the Godel-Bernays theory.
We say that a set $\mathfrak U$ is a universe if

$x\in y$ and $ y\in \mathfrak U$, then $x \in \mathfrak U$;
$I \in \mathfrak U$, and $\forall i \in I, x_i \in \mathfrak U$, then $\cup_{i\in I}x_i \in \mathfrak U$;
$x \in \mathfrak U$ then $\mathcal P(x) \in \mathfrak U$, where $\mathcal P(x)$ is the power set;
$x \in \mathfrak U$ and $f:x\to y$ is a surjective function, then $y \in \mathfrak U$;
$\mathbb N \in \mathfrak U$.

Thus, the Universe Axiom claims that every set belongs to a universe.
The Godel-Bernays theory states that besides sets, we have a primitive called "class" for which we have the axiom:
A class is a set if and only if it belongs to (other) class.
Therefore, I have to prove that for a universe $U$, a subset $S \subset U$ is a set (i.e. $S \in U$) if and only if $S \in V$ where $V \subset U$.
Any ideas on how to prove this?
Comment: It's pretty trivial, yeah (note that we can set $V=U$).
Comment: There's a typo in your goal: "$S\subset V$" should be "$S\in V$." In Godel-Bernays, sets are exactly classes which are *elements of* other classes.
Comment: Oh, now I understood your comment. We have that every set is a class by axiom. I didn't realize this. I was trying to prove that a set was a class.
Comment: Thanks @NoahSchweber, corrected the typo.
Comment: Just to clarify, is your comment supposed to point that the proof is actually a tautology?
Answer: You misstated the universe axiom. As you have phrased it, a universe must be the class of all sets.
For take any set $z$. Define $f : \mathbb{N} \to \{z\}$ by $f(x) = z$. Then $f$ is surjective and $\mathbb{N} \in \mathfrak{U}$, so $\{z\} \in \mathfrak{U}$. Since $z \in \{z\}$, we have $z \in \mathfrak{U}$.
But of course, the class of all sets is not itself a set. Put another way, there is no set of all sets.
The correct way to phrase that part of the axiom is: for any function $f : x \to \mathfrak{U}$, where $x \in \mathfrak{U}$, we have $range(f) \in \mathfrak{U}$.
Once we have a universe, we can produce from it a model of the very strong Morse-Kelley set theory. Every axiom of NBG is a theorem of Morse-Kelley set theory (and in fact implies the consistency of NBG).
In particular, the sort of classes will be $P(\mathfrak{U})$. The relation $\in$ is just the usual $\in$ relation. Note that $P \models \exists Y (X \in Y)$ if and only if $X \in \mathfrak{U}$. We abbreviate $\exists Y (X \in Y)$ as $isSet(X)$. Small variables range over sets, as usual.

Extensionality: $(\forall x (x \in X \iff x \in Y)) \to X = Y$

Proof: this follows directly from transitivity of $\mathfrak{U}$ plus ambient extensionality.

Foundation: $A \neq \emptyset \to \exists b \in A \forall c \in A (c \notin b)$

Proof: this follows from transitivity plus ambient foundation.

Class comprehension schema: all axioms which are universal closures of some statement of the form $\exists Y \forall x (x \in Y \iff \phi(x, W_1, \ldots, W_n))$

Proof: just take $Y = \{x \in \mathfrak{U} \mid P(\mathfrak{U}) \models \phi(x, W_1, \ldots, W_n))\}$. Note: in fact, the second-order class comprehension scheme is satisfied.

Axiom of pairing: $\exists z \forall w (x \in z \iff w = x \lor w = y)$

Proof: Take $w = \{x, y\}$. To show that $w \in \mathfrak{U}$, we can define $f : \mathbb{N} \to \mathfrak{U}$ by $f(0) = x$, $f(n + 1) = y$. Then $w = range(f)$.

Limitation of size (I'll write this one in English): $C$ is not a set if, and only if, there is some injective $F : V \to C$. Here, $V$ is the necessarily unique class satisfying $\forall x (x \in V)$.

Proof: Suppose that there is some injective $F : V \to C$. That is, we have $F : \mathfrak{U} \to C$. Then if $C \in \mathfrak{U}$, we would have $range(F) \subseteq C \in \mathfrak{U}$ and therefore $range(F) \in \mathfrak{U}$. Since $F$ is injective, we can define $G : range(F) \to \mathfrak{U}$ by setting $G(x)$ to be the unique $y$ such that $F(y) = x$. Then $range(G) = \mathfrak{U} \in \mathfrak{U}$; contradiction.
The converse is a bit trickier. We must use the fact that we can write $\mathfrak{U} = V_\kappa$, where $\kappa$ is a strongly inaccessible cardinal and also the smallest cardinal not in $\mathfrak{U}$. In particular, $\mathfrak{U}$ contains all cardinals smaller than itself.
So suppose we have some $C \subseteq \mathfrak{U}$ but $C \notin \mathfrak{U}$.
First, suppose $|C| < |\mathfrak{U}|$. In that case, we see that $|C| \in \mathfrak{U}$. We can therefore take some bijection $f : |C| \to C$; then $C \in \mathfrak{U}$.
Therefore, since $C \subseteq \mathfrak{U}$ and $|C|$ is not less than $|\mathfrak{U}|$, we must have $|C| = |\mathfrak{U}|$. That is, there is some bijection $F : \mathfrak{U} \to \mathfrak{C}$. This completes the converse.

Power set: $P(x)$ is a set.

Proof: If $x \in \mathfrak{U}$ then $P(x) \in \mathfrak{U}$.

Union: $\bigcup x$ is a set.

Proof: if $x \in \mathfrak{U}$ than $\bigcup x \in \mathfrak{U}$.

Infinity: $\mathbb{N}$ is a set.

Proof: $\mathbb{N} \in \mathfrak{U}$.
Comment: A useful explanation/explication! :)
Comment: NBG doesn't prove the consistency of NBG. Well, I hope it doesn't.
Comment: @ZhenLin Not sure how that typo made its way into my post, but thanks for pointing it out.


What specific practice exercice would you recomend for woodwind during extreme hot days ? (There's no air !)

Question: Practice during summer and extremely hot weather is really difficult, (for me, and may be for you as well).
Would you have any specific exercise to ease the practice session ?
I tend to feel like a beginner with no air support, bad embouchure, short of  breath and overall feels my practice session harms more than does good.
Should I focus on easier pieces (below my actual skills), technique or just shorten the practice session?
Comment: As Paris as just been ranked "red" in terms of pollution and heat by France I feel this is a legit question.
Comment: My inclination would be to start by seeing a doctor to make sure there isn't some heat- or season-related medical issue. Once I knew one way or the other, it would be easier to make an adjustment.
Comment: Using a fan must be a big help.
Comment: @Tim   "I'm your biggest fan!"
Comment: @CarlWitthoft - I know a lot of misery, but not that particular one...
Comment: Specifically I am in Paris, France and temps is 33 °C or higher these days. Also this question has been bothering me every summer since I began clarinet 6ish years ago.
Comment: @Tim A fan helps but it's so noisy I can't keep my cool ;) !
Comment: @Tom_C Thanks for the comment. I felt as if I had missed the point of this StackExchange channel. This heat wave was a bad one and really impacted my practice.
Comment: @CarlWitthoft - well, 'blow me down...'!
Comment: @Tim   I was referencing  "Misery" by S. King.
Answer: Breath is not everything for woodwind instruments, sight reading, technique are also among them.
What you can try is to practice what you are working on now with the clarinet but without having the beak in mouth. Play the keys as usual but instead of blowing in the instrument say the notes names for instance. This let you practice without overdoing your breath in the hot weather and without frustration of getting to easier pieces…
Just for the small story, I used to practice like that a lot on the saxophone, in order to annoy as little as possible my neighbors, usually the first half of the practice session. The other half breathing in the instrument allowed me to concentrate more on the sound than on the technique. Sounds simple but found it worked pretty well, and might be suited in your situation!
Hope it helps!
Answer: I don't think this is a music question.  Millions of wind musicians, along with, e.g., millions of distance runners, continue to work thru hot or other inimical weather conditions.
Aside from the possiblity of installing air conditioning in your practice space, heat and humidity may make you uncomfortable (and sleepy!), but they in no way preclude a normal healthy person from working hard.
Keep a towel and a bottle of water next to you, and see if you can't work up your endurance.  If not, then, as other folks have suggested here, you may need to get a medical evaluation.
Comment: @Carl_Witthoft Sorry I never said I was healthy or normal. Truly, I am not. Medical evaluation has been done and all is as well as it can be in my condition. Still, even if I wasn't seeking medical advice, I feel you were right to remind us of this basid advice.


How to tell in which key to transpose a song

Question: My vocal range is D3-D5.
I have found that most of the songs I sing will be very comfortable for me if I change their pitch to match the D key. Yet there are others that do not fall into that category and the only way for me to be sure that I want this song in that key is to increase its pitch semitone by semitone until I find a key that will allow me to sing the whole song naturally.
As you can probably guess, that takes a lot of time as most trial and error approaches.
Is there a way to tell what the target key would be when transposing a song without going through the above process?
Comment: "As you can probably guess, that takes a lot of time as most trial and error approaches." Is that not true for the whole process of incorporating a tune to your own repertoire? I don't see that as a downside, to me that's all time wisely spent, as it can lead to valuable lessons.
Comment: If you perform with other people, rather than considering all 12 keys with equal weight, I'd give a little weight to the keys your fellow band members may favour... hear what they may want to say. It's good to know their preferences and reasons, and it will make you a more knowledgeable musician and more respected. Going up or down a half tone can make a lot of sense to different instrumentalists sometimes.
Comment: I'd also give a little weight to the keys used already on popular recordings of the tune. If you find yourself comfortable with any of them (singing over the recording), that's probably a winner. And it increases your chances in improvised jam sessions, too :-)
Comment: @AlexLopez I'm not saying it's a downside and fine-tuning cannot be avoided, yet I wonder if there could be a way to at least approximately go near the desired key before beginning to fine-tune.
Answer: There can never be one key that a singer is happy in for every song they sing. That's simply because each song, in whatever key, has its own range - between the lowest and highest notes in that particular song.And just because D works for you for a lot certainly doesn't mean 'that's the key I sing in'. I've heard too many singers say that. It will certainly be true for some songs, but never all.
Given that a singer knows his/her vocal range, (and an awful lot don't...) makes it quite easy to determine a good key for a new song. Most songs will have their own range of less than two octaves.So set your own 'base' notes as F3 to C5. That should cover most songs.
Search through the song to find its lowest and highest notes. Then work out how far off your range that song's range is. Move accordingly, and there's your new key. For example, if a song has its highest note as G5 (too high by five semitones) and it's already in, say, key A, then you'll need to transpose it into key E (lower by five semitones).
There will be songs that do exactly what I've described, but dropping them down that far then puts the lowest note too low! That's why I suggested having a margin top and bottom of your existing range.
However (there's often one of those!) the tessitura of some songs can rear its head. That's a place in some songs, where there is a concentration of high (or low) notes. They may well be at the limits of your range, making it tricky to sing. That says a song has a 'high' or 'low' tessitura.
Another however is that some words or syllables are not easy to sing - particularly at the high end. So it is sometimes worthwhile dropping the whole song another tone or so, to alleviate that problem.
So, while there is a sort of scientific way to establish a good key, the trial and error will still come into the equation! And the problem never goes away! Working in 4/5 part harmony groups is more fun, as compromises crop up all the time - find a good key for four and it's out of range for the bass voice, for instance!
Comment: The margin would be there to give a ball-park key. If you need to drop a key down so low to enable the high parts to be sung, and they are then too low, how could you sing that song *in any key*? Sometimes either let someone else sing, change the tune, or forget it.You might find, if you had transposing instruments that were included  in the song, that they may well not be happy with a key the rest of you are happy with. Sometimes compromises aren't the option, scrapping a song is.
Comment: My concern with automating all sorts is that there is rarely a 'one size fits all'. If there was a facilty, and the app told you to play a song in, say, Ab, a lot of guitarists - and some other players would baulk at the idea, so there would be not a lot of help there.
Comment: No. I can't. What's wrong with being proactive, and just doing what I've (and countless others have) done for decades, and worked it out ourselves. I'm sorry if this comes across as harsh, but why rely on sites when do it yourself is still alive - and personally viable?
Comment: "There will be songs that do exactly what I've described, but dropping them down that far then puts the lowest note too low!" - this happens more often than not. What do we do in that case? Also, I didn't understand how the top and bottom margin help in this case.
Comment: I just found out that the song "Let It Go" (-2 semitones) is a perfect example of what you describe above with a top and bottom margin of 1 semitone and my voice fits perfectly into it. Could you please refer to a website or tool (if any) that provides information on the lowest and highest note of a song (or an imported track) ?
Comment: Well, that just diminishes any attempt to automate all sorts of procedures and make our lives a little bit easier. I'm not saying it's wrong to figure it out ourselves, but consider that someone might not have enough time to do something, big or small, or they might not have the necessary education to do so. Anyway, your answer actually helped me so I'm going to accept it. Cheers!
Comment: This comment explained your concern better, yet I wasn't suggesting to automate the part of finding a key that would fit a song to someone's vocal range, just merely say that _that_ song's highest note is _foo_ and its lowest _bar_ . Much like having the BPM of a song or its original key.
Comment: I understand. Although finding the highest and lowest note of a song (whose version..?) or the bpm or the original key (what's that..?) are fairly inconsequential, and don't particularly help when it comes to doing a cover version. (In my experience).
Comment: My bad, I've probably misused the word _original_. What I meant was the song as performed by the band in their album. For example Queen's - "Don't Stop Me Now", is in F Major with a BPM of 156 in their album "Jazz". It's true that there might be inconsistencies between versions of a song even within the recordings of the same band that performed it originally. I see your point.


Android Volley: How do I get the response from the server, whatever it might be?

Question: I'm starting with Android development with Kotlin. I'm trying to use Volley for reading an API and the update the GUI elements. I made it work with StringObjectRequests that use the http GET method, now my problem is when I want to use using POST method.
Here's my basic function:
fun volley() {
    val queue = Volley.newRequestQueue(this)
    val url   = "http://x.x.x.x/api.php"
    val json = JSONObject()

    json.put("ciudad", "Londres")
    json.put("nombre", "Luis")

    val stringRequest = JsonObjectRequest(Request.Method.POST,
      url, json,
      Response.Listener<JSONObject> { response ->
        taContenido.setText(response.toString())
      },
      Response.ErrorListener {
        taContenido.setText("No Funcionó")
      })

    queue.add(stringRequest)
  }

The code in the "API" is quite simple...
<?php
$j = array('ciudad' => $_POST["ciudad"],
   'nombre' => $_POST["nombre"]);

echo json_encode($j);

My problem is that when I run the function, it goes through the ErrorListener part and shows "No Funcionó". I got no idea why. Of course if I try my API with Postman it returns the expected {"ciudad":"Londres","nombre":"Luis"}
So, how can I see what the server is returning, whatever it is, when using the JsonObjectRequest?
If I change the Request to StringRequest, of course I'll be able to see the PHP errors (since there will be no $_POST[] defined :|
Comment: Sorry, I don't get it. Where do I get the networkResponse from? `var nr : NetworkResponse = error.networkResponse` ??? it complains about unresolved reference to networkResponse
Comment: Inside `Response.ErrorListener` try using `it.networkResponse`
Comment: or do something like this `Response.ErrorListener { error ->`
Comment: `it.networkResponse` was the first thing I tried, it returns a `Attempt to read from field 'byte[] com.android.volley.NetworkResponse.data' on a null object reference`
Comment: If I force the API tu return a json object manually, everything works, so it looks like the API is never getting the POST, but I can't know for sure if I can't see what it comes from the server
Comment: If I print `it.toString()` I can see the error: `com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject` for the `<br` I'm pretty sure it's an error in the PHP script, but I can't see what. The only thing I can gess is that the values aren't passed via the POST method. Is my call to `JsonObjectRequest`okay?
Comment: Sorry I am not that familiar with Php
Comment: My PHP is okay, looks like it is throwing an exception because it isn't reading the POST
Answer: I am posting in Java. Please convert in Kotlin. Make a singleton class like this -
public class VolleyManager {
    private static VolleyManager ourInstance;
    private final Context mContext;
    private final ImageLoader mImageLoader;
    private RequestQueue mRequestQueue;

    private VolleyManager(final Context pContext) {
        mContext = pContext;
        mImageLoader = new ImageLoader(getRequestQueue(), new ImageLoader.ImageCache() {
            private LruCache<String, Bitmap> mCache = new LruCache<>(20);

            @Override
            public Bitmap getBitmap(final String url) {
                return mCache.get(url);
            }

            @Override
            public void putBitmap(final String url, final Bitmap bitmap) {
                mCache.put(url, bitmap);
            }
        });
    }

    private RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mContext);
        }
        return mRequestQueue;
    }

    public static synchronized VolleyManager getInstance(final Context pContext) {
        if (ourInstance == null) {
            ourInstance = new VolleyManager(pContext);
        }
        return ourInstance;
    }

    public void addRequest(final Request pRequest) {
        getRequestQueue().add(pRequest);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(tag);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

And make requests like this -
public class AccessTokenRequest extends StringRequest {
    Map<String,String> mParms = new ArrayMap<>();
    Map<String,String> mHeader = new ArrayMap<>();

    public AccessTokenRequest(String code, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(Method.POST, WebConfig.END_POINT + WebConfig.ACCESS_TOKEN_METHOD, listener, errorListener);
        mHeader.put("Authorization","Basic MjJEUT");
        mHeader.put("Content-Type","application/x-www-form-urlencoded");
        mParms.put("clientId","63FGDF");
        mParms.put("grant_type","authorization_code");
        mParms.put("redirect_uri","https://example.com/thu");
        mParms.put("code",code);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeader;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParms;
    }
}

And in activity, call like this -
private void requestAccessToken(String code) {

        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.show();

        VolleyManager.getInstance(AuthorizationActivity.this).addRequest(new AccessTokenRequest(code, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject responseJsonObj = new JSONObject(response);
                    String accessToken = responseJsonObj.getString("access_token");
                    long expiresIn = responseJsonObj.getInt("expires_in") + (System.currentTimeMillis() / 1000);
                    String refreshToken = responseJsonObj.getString("refresh_token");
                    List<Scope> scopes = parseScopes(responseJsonObj.getString("scope"));
                    String tokenType = responseJsonObj.getString("token_type");
                    String userId = responseJsonObj.getString("user_id");

                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    pDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pDialog.dismiss();
                Toast.makeText(AuthorizationActivity.this, "Please check internet connection", Toast.LENGTH_LONG).show();
            }
        }));
    }

Comment: This is a full working code in java. I think this answer does not deserve a negative vote. If someone cannot understand this simple code then please do not give negative vote atleast. Thank you.


Breaking down statement in discrete mathematics

Question: Anyone mind helping me break down this statement in discrete mathematics?
Having trouble understanding if I'm doing this correctly or not.
The original statement was:
~(~p -> q) -> (p v r)
And I went on:
Comment: Correct, but the 4th and 5th lines are superfluous : you can go from $\lnot (p \lor q) \to (p \lor r)$ to $\lnot \lnot (p \lor q) \lor (p \lor r)$ and then...
Answer: You've done fine.  A tip, though, following your third step: third statement:
$$\lnot (p\lor q) \rightarrow (p\lor r)\tag{3}$$
$$ \equiv \lnot\lnot (p\lor q) \lor (p \lor r)\tag 4$$
$$\equiv (p\lor q)\lor (p\lor r)\tag 5$$ $$\equiv p\lor q \lor p \lor r \tag{(6) associativity of $\lor$}$$
$$\equiv \underbrace{p \lor p}_{\large \equiv p} \lor q \lor r\tag{(7) commutativity of $\lor$}$$
$$\equiv p\lor q\lor r\tag 8 $$
Answer: Well that's correct. Now all you need as a final step is:
$$
p \lor q \lor r
$$
Since you have $$\lor$$ everywhere, you can eliminate brackets.


ListFragment Android

Question: Hoje usando um Fragment para resolver um problema, vi que exite uma classe chamada de ListFragment mas o que ela faz? Qual a diferença com um Fragment?
Quando devo usar o ListFragment quando devo usar o Fragment.
Answer: ListFragment é basicamente um Fragment com uma ListView. Tens alguns métodos como getListView() e getListAdapter() para te facilitar a vida.
Depende para o que precisas mas na maioria das vezes eu usaria um Fragment com Listview.
Fonte: https://developer.android.com/reference/android/support/v4/app/ListFragment.html

ListFragment Android


Qt: class Ui::StartScreen has no member named 'lbl_gif'

Question: I have read many other forums, but this is not the result of a typo or missing definition in the .ui file, and thus I am at a loss. I added the label in the Designer pane of QtCreator, then went over to the .cpp file to reference the label and add a movie. That did not work so I tried adding just text, and still no luck. I have cleaned the project, rebuilt it, closed and reopened Qt, deleted and re-added new labels with new names, but Qt is not recognizing any labels I add to this form. All other forms work fine when adding labels. I know the label is there because the intellisense autocompletes the lbl_gif name for me, and it is present in the dropdown of options after typing "ui->".
Error:
C:\Users\user\OneDrive\Desktop\project\screens\startscreen.cpp:30: error: 'class Ui::StartScreen' has no member named 'lbl_gif'
..\screens\startscreen.cpp: In constructor 'StartScreen::StartScreen(QWidget*)':
..\screens\startscreen.cpp:30:9: error: 'class Ui::StartScreen' has no member named 'lbl_gif'
   30 |     ui->lbl_gif->setText("testing");
      |         ^~~~~~~~~~~~~~~~~~~~~~~

StartScreen class constructor where lbl_gif is referenced:
// Constructor
StartScreen::StartScreen(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::StartScreen)
{
    // Setup the mainwindow
    ui->setupUi(this);
    setWindowTitle("title");

     // Load logo
    QString path = R"(C:/Users/user/OneDrive/Desktop/project/logos/8bitlogo.png)";
    QPixmap img(path);
    img = img.scaled(img.size()*.9, Qt::KeepAspectRatio);
    ui->lbl_logo->setPixmap(img);

    // Load gif
    QMovie *movie = new QMovie("C:/Users/user/OneDrive/Desktop/project/logos/knight.gif");
    ui->lbl_gif->setText("testing");
    movie->start();

    this->show();
}

StartScreen.ui snippet proving existence of object in ui:
      <layout class="QVBoxLayout" name="verticalLayout_6" stretch="0,2,2,2,2,2">
       <item>
        <widget class="QLabel" name="lbl_gif">
         <property name="text">
          <string>TextLabel</string>
         </property>
        </widget>
       </item>

Comment: Are you sure you've properly rebuilt the header file related to `StartScreen.ui` with the `uic` utility program and cleared the compiler cache? Such errors are normally the result of "old" headers that have not been properly updated.
Answer: I just did as @musicamante suggested and ran C:/Qt/6.6.1/mingw_64/bin/uic.exe .\startscreen.ui from the directory containing the form files, which created a fresh ui_startscreen.h file. I opened this file and confirmed it contained the line QLabel *lbl_gif; under public with the rest of the member variables. The project was still having the build errors.
By chance I noticed that an outdated version of the ui_startscreen.h file had somehow made its way into the project directory where the .pro file was also located. Thus, it was reading the outdated ui_startscreen.h file instead of reading the one in the build folder. The problem has been resolved.


If a sequence of monotone functions converges in measure, does it also converge almost everywhere?

Question: Let $\{f_n\}$ be a sequence of monotone functions from $\Bbb R$ to $\Bbb R$ such that $f_n$ converges in measure to some function $f$. Is it true that $f_n$ converges to $f$ a.e.?
I am sure it has a sub-sequence that converges to $f$ a.e., and intuitively it seems that it must be true, but I am not able to prove it rigorously. Could you please give me some hint?
Comment: Is $f_n$ monotone wrt $x$ or wrt $n$? If wrt $n$ then this is trivial, $f_n$ converges everywhere (possibly to $\pm \infty$) without assuming it converges in measure. If wrt $x$ then there's a bit more to do. Also, is the measure space in question finite?
Comment: yes, you are correct, it must be monotone in $x$. About space it doesn't specify whether finite or not.
Comment: Could you do it if the $f_n$ were continuous? The monotonicity implies the $A = \{ x : (\exists n) f_n \text{ is not continuous at } x \}$ is countable, hence measure zero. That might help.
Answer: By dividing $\{f_n\}$ into two subseqences, the increasing functions and the decreasing ones, and working with each subsequence separately, we may assume without loss of generality that $\{f_n\}$ is a sequence of increasing functions.
Note that $\{{f_n}_{|[-1,1]}\}$ is a sequence of functions defined on a finite measure space converging in measure to $f_{|[-1,1]}$, so a standard result tells us that there is a subsequence, say $\{{f^{(1)}_n}_{|[-1,1]}\}$, of $\{{f_n}_{|[-1,1]}\}$, that converges a.e. to $f$ on $[-1,1]$. Furthermore there is a subsequence, say $\{{f^{(2)}_n}_{|[-2,2]}\}$, of $\{{f^{(1)}_n}_{|[-2,2]}\}$ converging a.e. to $f$ on $[-2,2]$. If we continue producing subsequences of subsequences in this fashion we see that the "diagonal" subsequence $\{f^{(n)}_n\}$ converges pointwise to $f$ on a co-null set $X\subset \mathbb{R}$. Since the $f^{(n)}_n$ functions are increasing we get that $f_{|X}$ is increasing. This also means that $f_{|X}$ is continuous on a co-countable set $A\subset X$. Then $A$ is also co-null.
We claim that $f_n \rightarrow f$ pointwise on $A$. Indeed, fix $x'\in A$ and $\epsilon>0$. Choose $a, b\in A$ such that $x'\in (a, b)$ and $f(b)-f(a)<\epsilon$. Pick $\delta$ such that $x'\in (a+\delta, b-\delta)$. Since $f_n \rightarrow f$ in measure there exists $N\in \mathbb{N}$ such that $\mu(|f-f_n|\geq \epsilon)<\delta$ for $n\geq N$.
For such $n$ we must have $|f(x')-f_n(x')|<2\epsilon$. Indeed, suppose for contradiction that either $f_n(x')\leq f(x')-2\epsilon$ or $f(x')+2\epsilon\leq f_n(x')$. In the first case we get that for $x\in (a, x')\cap A$: $f_n(x)\leq f_n(x')\leq f(x')-2\epsilon\leq f(x)-\epsilon$ where the last inequality follows from the fact that $f$ does not vary by more than $\epsilon$ on $(a,b)\cap A$. But this means in particular that $(a, x')\cap A\subset \{|f-f_n|\geq \epsilon\}$ which is impossible since the LHS has measure greater than $\delta$ and the RHS measure less than $\delta$. Similarly, if $f(x')+2\epsilon\leq f_n(x')$ were to hold we would get that $(x', b)\cap A\subset \{|f-f_n|\geq \epsilon\}$ which again is impossible. Hence $|f(x')-f_n(x')|<2\epsilon$.
Comment: trying to read through your proof now. (1) do you want the choice of $a$ for a given $y$ to be inside $X$? (2) maybe this is easily fixable, but you can't always choose such $a,a'$ (e.g. $f_n, f \equiv 0$). (3) "where we the last"
Comment: Yep, I realized that too and hopefully this last edit fixes the issues
Comment: (1) please read my last comment in full. (2) "RHS measure greater than $\delta$" --> "RHS measure less than $\delta$".
Comment: Sorry it should be "RHS measure less than delta", as in the defintion of convergence in measure. Now that I've edited my answer I guess question (1) in your original comment no longer applies.
Comment: ok u can figure that out. anyways, nice solution and well written! +1


Access function of C# from XAML

Question: I have this button in my XAML code-
           <Button x:Name="button"
            Content="{Binding Name}"
            Click="Start"
            HorizontalAlignment="Left"
            Margin="123,45,0,0"
            VerticalAlignment="Top"/>

I have another C# code-
namespace MyGame
{

    public sealed partial class MainPage : Page
    {
        public string Name()
          {

             get{ return "Hello" };
          }
       private void ButtonNo3(object sender, RoutedEventArgs e)
        {

          Button obj = (Button)sender;

          var selectedButton = obj.Content.ToString();
          //This is where I get this error-An exception of type        'System.NullReferenceException' occurred in MyGame.exe but was not handled in user code
         }
    }
  }

My question is how can I get Content of my Button in my xaml code to store the value from the function of C# code?
Answer: You accomplish this via binding. Binding has a couple rules:

You can only bind to properties
Those properties must be public
For the binding to evaluate, the property must be on the View's DataContext

That data context is usually a ViewModel object instead of the view itself, following the MVVM pattern.
So in your view model, you would have:
//Properties (and methods) are PascalCase!
public string Name { get { return "Hello";} }

Then once you set the data context, your XAML is:
      <Button x:Name="button"
        Content="{Binding Name}"
        Click="Start"
        HorizontalAlignment="Left"
        Margin="123,45,0,0"
        VerticalAlignment="Top"/>

Comment: Note that there are ways to duck around the `DataContext` restriction by setting the `Source` or `RelativeSource`  - these offer the ability to bind through static values or `DataContext` of other controls
Comment: It is also possible to set the button's data context to the parent MainPage class using a RelativeSource.  Then you could bind to properties in the "code behind" but I would strongly recommend going with a View Model and following the MVVM architecture.  (See http://stackoverflow.com/questions/84278/how-do-i-use-wpf-bindings-with-relativesource)
Comment: @BradleyDotNET I tried the above implementation.But it is giving me this error-
`An exception of type 'System.NullReferenceException' occurred in MyGame.exe but was not handled in user code`
Comment: @Coder Trap the exception and do some debugging. Thats not enough information for me to help, and you need to able to debug your NREs anyways :)
Comment: @BradleyDotNET Sorry But I am still not able to figure it out.I have editted my code above with the error.Also the contents of the Button is not displaying anything.
Comment: @Coder You still need to set the `DataContext`. If you insist on doing so in the code-behind, write `this.DataContext = this` in the constructor (note, this is *terrible* design).
Answer: Since you haven't mentioned the need for syncing, the simplest answer to your question would be to use the x:Name identifier and just set the content property from a function in your C# code.
button.Content = name();

In case your can move your method into a different class, you can also use an ObjectDataProvider to wire up your method name to the XAML code, and then use data-binding to connect the data provider to your code:
<Grid>
    <Grid.Resources>
        <ObjectDataProvider x:Key="fnName"
                         ObjectType="{x:Type bind:SomeClassHoldingYourMethod}"
                         MethodName="name">
        </ObjectDataProvider>
    </Grid.Resources>
    <Button x:Name="button"
        Content="{Binding Source={StaticResource fnName}, Mode=OneTime}"
        HorizontalAlignment="Left"
        Margin="123,45,0,0"
        VerticalAlignment="Top"/>
</Grid>

However if you want a simpler approach and you want your data to be in sync with the UI (so whenever you change something in your data it is reflected on the UI controls automatically) you can convert your function to a readonly property and do what @BradleyDotNET suggested.
In general, separating data-binding from actual data, is considered a good thing.
Be aware that in WPF you can always do stuff declaratively in XAML, but you can also do the same thing in code programmatically using C#. Most people prefer the declarative way, but it's good to know you can do the same (and more) in C# if you need it.
And please, use the .NET framework naming conventions, and name your methods with pascalCase.
Answer: If you want to access methods from XAML, your options are relatively restricted.
The first and most obvious is to use event handlers, which go into the code-behind of your View and thus violate MVVM. The can, however, offer the easiest way to execute code. If you are using a ViewModel, you can also use dynamic  to perform late binding to the desired method - but only from C# code.
<Button ...
        Clicked="Button_OnClick"/>

and in code-behind
public void Button_OnClick(object sender, RoutedEventArgs e)
{
    (DataContext as dynamic).ButtonClicked;
}

Note that while it is possible to use the specific type of ViewModel instead of dynamic, this would also be a violation of MVVM pattern - and a far worse one than code behind, because it forces your View to be used with a particular ViewModel.
Another option is to utilize Interactions and a CallMethodAction (from the Expressions Blend SDK).
<Button>

            <ei:CallMethodAction MethodName="ButtonClicked"/>

</Button>

Comment: I would contend that all views are made to work with a particular view model. Feel free to decouple via an interface, but to say that `dynamic` is a good solution, let alone the only one, is a bit of a stretch

Access function of C# from XAML


number of subgroups up to isomorphism in a group $G$

Question: In any group $G$, we can also consider the group isomorphism problem for its subgroups, so we might ask the following problems:
I, If $H_1\cong H_2$ for some two subgroup $H_i$ of $G$, if $H_1$ is normal, is $H_2$ also normal? I believe it is not true in general, the motivation is that we can expect to extend the isomorphism between $H_i$ to an isomorphism on $G$.
II, Define the number of different subgroups in $G$ up to isomorphism to be $\phi(G)$, are there any result on relating $\phi(G)$ to the propertity of $G$, such as its order when $G$ is finite or anything else if $G$ has any other further structures such as $G$ is a algebraic group. etc?
Answer: In the group of symmetries of a square, the subgroup consisting of the identity and the 180-degree rotation about the center of the square is normal, but the subgroup consisting of the identity and the reflection about a diagonal is not normal.  Nevertheless, these two 2-element subgroups are isomorphic.


How do you figure out what relations of $A \times A$ are not transitive?

Question: I have found all 16 relations on a two element set. But now I can not find the ones which are not transitive. I dont know how ($xRy \land yRz) \implies xRz$ relates to this conversation.
This should be obvious because some relations in this context have $x,y,z,w$ elements.
Any help would be tremendously appreciated.
Answer: The relation $\{(a_1,a_2), (a_2,a_1)\}$ is not transitive. We can prove this by contradiction: assume the relation is transitive. We have that $a_1\sim a_2$, and that $a_2\sim a_1$. This means that by transitivity, we must have that $a_1\sim a_1$. But we don't. This is a contradiction, so the above relation is not transitive.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/30987/discussion-on-answer-by-alex-s-how-do-you-figure-out-what-relations-of-a-times).
Comment: @GrahamKemp then what about the relation $(x,y), (y,x)$ here we have $(x,y) \land (y,x) \implies (x,x)$ this is false. but everywhere I go it says that $(x,x)$ must exist in the relation.
Comment: @Big Mike. Definition : A binary relation on a set $S$ is any subset of $S\times S$. Example "<" on  $N$,the  set of positive integers, is $L=\{(m,n)\in N\times N :\exists r\in N (m+r=n)\} .$  A set theorist will write $<=L$ which looks strange but in this context, "$<$" is a set.
Answer:
I don't know how $(xRy∧yRz)⟹xRz$ relates to this conversation.

It is $\forall x\,\forall y\,\forall z\;\Big(\big(x\mathop Ry\wedge y\mathop Rz\big) \to x\mathop Rz\Big)$.
Transitivity is the claim that if there is some indirect relationship from one entity ($x$) to another entity ($z$), through some bridge ($y$), then there must be a direct relationship.
It's not a matter of finding cases that satisfy this condition, just that no case can be found to falsify it.
Another way to express transitivity is that:
$$\neg\,\exists x\,\exists y\,\exists z\;\Big(\big(x\mathop Ry\wedge y\mathop Rz\big)\wedge\neg x\mathop Rz\Big)$$
So if you can find any such indirect relationship but cannot find a corresponding direct relationship, then the entire relation is not transitive.
Only if you can demonstrate that no such counterexample exists can you claim transitivity.
Comment: okay you have made things extremely clear. I cannot commend you enough. what about the relation $(y,x)$ here i have $(y,?) \land (?,x) \implies (y,x)$ [where the question mark indicates either x or y] but if $(y,x) \land (x,x) \implies (y,x)$ we dont have a $(x,x)$ in the relation so that means this would false too? @GrahamKemp
Comment: @BigMike Implications are true when their antecedents are false.  They are only false when antecedent is true *and* the consequent is false.  Only having a bridge and no direct path forms a counterexample.
Answer: Suppose $R$ is not transitive.Equivalently, for some $a,b,c$ we have $(a,b)\in R \wedge (b,c)\in R\wedge (a,c)\not \in R.$ If you put $a=b$ or $b=c$ into this you get a contradiction. So $a \ne b\wedge b\ne c$. Since $a,b,c$ belong to $\{x,y\}$ with $x\ne y$ this gives, equivalently,  (i) $(x,y)\in R\wedge (y,x)\in R\wedge (x,x)\not \in R$ or (ii) $(y,x)\in R\wedge (x,y)\in R\wedge (y,y)\not \in R$. That is, $(x,y)$ and $(y,x)$ both belong to $R$ and at least one of $(x,x),(y,y)$ does not. In all, $3$ non-transitive binary relations on $\{x,y\} $ : $R_1=A , R_2=A\cup \{(x,x)\}, R_3=A\cup \{(y,y)\}$ where $A=\{(x,y),(y,x)\}.$


How to set up SourceGear DiffMerge as the diff/merge tool for Visual Studio?

Question: I am using TFS for source control, but I want to use SourceGear DiffMerge for viewing file differences and doing merges.  I found the Tools -> Options -> Source Control -> Visual Studio Team Foundation Server -> Configure User Tools dialog, but setting up the merge parameters is very confusing.  What should those parameters be?
Comment: possible duplicate of [How do I configure TFS to work with various merge tools](http://stackoverflow.com/questions/1313908/how-do-i-configure-tfs-to-work-with-various-merge-tools)
Answer: These are the SourceGear settings that I use:
C:\Program Files\SourceGear\Common\DiffMerge\sgdm.exe
Compare:
<code>/t1=%6 /t2=%7 %1 %2
</code>
Merge:
<code>/m /r=%4 /t1=%7 /t2=%8 /t3=%6 /c=%9 %2 %3 %1
</code>
Comment: I +1'd this but regret it as I @Colin Bacon's order is more intuitive and fits the standard pattern established in http://stackoverflow.com/a/1313961/11635
Answer: These are my settings.  Can't remember where I got them from but I have used them in VS2010, VS2012, VS2013.

C:\Program Files\SourceGear\Common\DiffMerge\sgdm.exe

Compare

/title1=%6 /title2=%7 %1 %2

Merge

/title1=%6 /title2=%8 /title3=%7 /result=%4 %1 %3 %2
Comment: My guess is you may have got them from [this MSDN blog](http://blogs.msdn.com/b/jmanning/archive/2006/02/20/diff-merge-configuration-in-team-foundation-common-command-and-argument-values.aspx)
Answer: Firstly, you need to change the default command line to:

C:\Program Files (x86)\SourceGear\Vault Client\sgdm.exe

I found the parameters in this thread on the SourceGear support forums, but the arguments given there are incorrect and result in the auto-merge being executed in reverse, i.e. old code overwrites new code.  The correct arguments are:

/m /t1=%6 /t2=%7 /t3=%8 /c=%9 %1 %3 %2 /r=%4
Comment: ah, sorry - I upvoted and 'this' refers to your parameters as above
Comment: @RubenBartelink: Note my comment there. "The parameters he uses for SourceGear DiffMerge are incorrect. The correct parameters can be found here."  Try it out.  If you use the parameters listed there, the auto-merge chooses exactly the wrong code as the merge result.
Comment: Hmm. I'm using the args from Colin Bacon's asnwer and they seem to work, but I was under the illusion that I was using the ones from the 'universal' blog post for 6 years with no such ill effects - perhaps that's because arg order/semantics changed across sgdm versions (doesnt seem too likely though). Will analyze and report back at some point...
Comment: Hmm, still using the other config happily - have not taken the time to understand your point as things still seem to work in a nice predicatable fashion that way...
Comment: @RubenBartelink do the experiment of simulating two non-conflicting changes to one file by two different users, and perform an automatic merge.  Try with both sets of parameters and see how differently the merge gets resolved.
Comment: OK, I'll keep it on my TODO list - it's just tight at the top of it :(
Comment: I'm using this now and it's Doing What I Mean. Thanks for pushing!
Comment: @RubenBartelink "Doing What I Mean" = ?
Comment: => It reads my mind and Just Works for the situations I use it in without me actually being able to necessarily explain in depth what it is that I Mean. (Reference to an ex-colleague's frequent assertion that the really 'all' the User is asking for is a simple Do What I Mean button)
Comment: @RubenBartelink So, to be clear, does it work with the parameters as I said, or the other way?
Answer: For some reason my old settings for DiffMerge with %1 %2 stopped working, error "File not found (%1). File not found (%2)."
Changed it to:

"C:\Program Files\SourceGear\Common\DiffMerge\sgdm.exe" $(Base)
  $(Mine)


Probability that uniform distributed variable lies within interval

Question: If a,b is uniform in [0,1] what is the probability that a/b is in [1,3]
My friend was asked this question in an interview recently but I'm unsure of how to approach it.
I understand that a,b uniform in [0,1] implies the 2 equations 0 <= x <= 1 and 0 <= y <= 1
But I'm unsure how to proceed now.
Comment: Without independence there is no answer to this question.
Answer: To answer this question, I'll assume $A, B$ are independent and distributed according to $\text{Unif}(0,1)$.
\begin{eqnarray*} && \Pr\left(1 \leq \dfrac{A}{B} \leq 3\right) \\ &=& \Pr\left(\frac{A}{3} \leq B \leq A\right)\\ & = & \int_0^1\int_{a/3}^{a}1dbda \\ & = & \int_0^1\frac{2a}{3}da \\ & = & \frac{1}{3}\end{eqnarray*}
Geometrically, it is the area of the coloured region in the graph below:


Expected value of a function of two random variables

Question: In Bishop's "Pattern Recognition and Machine learning" in chapter 1.2.2, the author introduces the concept of expectations of functions of two random variables. In pg 20, introduces the following term,
$$
E_x[f(x,y)]
$$
And goes on to remark on it, saying that it-

denotes the average of the function f(x, y) with respect to the distribution of x. Note that Ex[f(x, y)] will be a function of y.

Why is the expectation a function of y?
Comment: Because you are _averaging out_ the $x$.
Answer: The notation is ambiguous because (a) it is using lower cases and (b) $X$ and $Y$ are both random variables, possibly dependent random variables. One then wonders whether it should be
$$\mathbb E_{X|Y=y}[f(X,y)]=\dfrac{\int_\mathfrak X f(x,y) p_{X,Y}(x,y)\,\text d x}{\int_\mathfrak X p_{X,Y}(x,y)\,\text d x}$$
or
$$\mathbb E_{X}[f(X,y)]=\int_\mathfrak X f(x,y) \int_\mathfrak Y p_{X,Y}(x,z)\,\text d z\,\text d x$$
where $p_{X,Y}$ denotes the joint density of $(X,Y)$.
Comment: (1) I don't understand why case might matter: authors should be allowed to adopt whatever typographical conventions they find convenient.  (2) In light of that, why isn't the verbal description sufficiently clear? Blindly applying the definition of expectation with respect to a distribution gives $$E_X(f(X,Y))=\int_{\mathbb R}f(x,Y)\,\mathrm dF_X(x)$$ where $F_X$ is the distribution function of $X.$ Whatever "$Y$" might represent, regardless whether it's written in upper or lower case or even Egyptian hieroglyphics, the right hand side is explicitly a function of $Y.$
Comment: @whuber While all notations are welcome in their diversity, I find [Bishop's](https://www.microsoft.com/en-us/research/uploads/prod/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf) $$\mathbb E_x[f(x,y)]=\sum_x p(x)f(x,y)$$confusing for beginners...
Comment: Hmm...that looks like an approach based on Nonstandard Analysis ;-).


Algorithm for determining if a string is a prefix of a date in some range

Question: I'm trying to validate a textbox in VBA so that a user cannot enter values that couldn't possibly end up being a date within some interval. Is there a good away to determine if a string can be the prefix of a date subject to some interval? For example, if the user needs to enter a date between 1/1/2018 and 12/31/2018, I want to "02/20" to pass but not something like "02/29". Dates can be in mm/dd/yyyy or dd/mm/yyyy format, although I'll take a good algorithm for just one of the formats. I'm not sure of a way to do this without a lot of loops or conditions.
Edit: I think I found a good solution if anyone wants to check it.
Private Sub mMainControl_Change()

    Dim vIsValid As Boolean
    Dim vPrefixLength As Integer
    Dim vDatePrefix As String

    vDatePrefix = CStr(mMainControl.Value)
    vPrefixLength = Len(vDatePrefix)

    If vPrefixLength = 0 Then
        Exit Sub
    ElseIf Not InitialCheck(vDatePrefix, mMinValue, mMaxValue) Then
        vIsValid = False
    ElseIf mMaxValue - mMinValue > 365 Then
        If Not FullYearCheck(vDatePrefix, mMinValue, mMaxValue) Then vIsValid = False
    Else
        If Not PartYearCheck(vDatePrefix, mMinValue, mMaxValue) Then vIsValid = False
    End If

    If Not vIsValid Then mMainControl.Value = Left(vDatePrefix, Min(10, vPrefixLength - 1))

End Sub

Private Function InitialCheck(ByVal DatePrefix As String, ByVal MinDate As Date, ByVal MaxDate As Date) As Boolean

    Dim vPrefixLength As Integer
    Dim vTestDate As Variant

    vPrefixLength = Len(DatePrefix)

    If vPrefixLength > 10 Or Not DatePrefix Like Left("##/##/####", vPrefixLength) Then
        InitialCheck = False
        Exit Function
    End If

    On Error Resume Next
    vTestDate = CDate(DatePrefix & Right("01/01/1996", 10 - vPrefixLength))
    vTestDate = CDate(DatePrefix & Right("01/00/1984", 10 - vPrefixLength))
    On Error GoTo 0

    InitialCheck = Not IsEmpty(vTestDate)

End Function

Private Function FullYearCheck(ByVal DatePrefix As String, ByVal MinDate As Date, ByVal MaxDate As Date) As Boolean

    Dim i As Integer, vPrefixLength As Integer, vMinPrefixYear As Integer, vMaxPrefixYear As Integer
    Dim vFullDate As Variant

    vPrefixLength = Len(DatePrefix)
    If vPrefixLength > 6 Then
        vMinPrefixYear = CInt(Right(DatePrefix, vPrefixLength - 6) & Left("0000", 10 - vPrefixLength))
        vMaxPrefixYear = CInt(Right(DatePrefix, vPrefixLength - 6) & Left("9999", 10 - vPrefixLength))
        If Year(MinDate) < vMinPrefixYear Then MinDate = DateSerial(vMinPrefixYear, 1, 1)
        If Year(MaxDate) > vMaxPrefixYear Then MaxDate = DateSerial(vMaxPrefixYear, 12, 31)
    End If

    For i = 0 To Year(MaxDate) - Year(MinDate)
        vFullDate = DatePrefix & Right("01/01/" & CStr(Year(MinDate) + i), 10 - vPrefixLength)
        If ValidByMonth(vFullDate, MinDate, MaxDate) Or ValidByDay(vFullDate, MinDate, MaxDate) Then Exit For
        vFullDate = DatePrefix & Right("01/00/" & CStr(Year(MinDate) + i), 10 - vPrefixLength)
        If ValidByMonth(vFullDate, MinDate, MaxDate) Or ValidByDay(vFullDate, MinDate, MaxDate) Then Exit For Else vFullDate = Empty
    Next i

    FullYearCheck = Not IsEmpty(vFullDate)

End Function

Private Function PartYearCheck(ByVal DatePrefix As String, ByVal MinDate As Date, ByVal MaxDate As Date) As Boolean

    Dim i As Integer, vPrefixLength As Integer
    Dim vFullDate As Variant

    vPrefixLength = Len(DatePrefix)

    For i = 0 To MaxDate - MinDate
        vFullDate = DatePrefix & Right(Format(CStr(MinDate + i), "mm/dd/yyyy"), 10 - vPrefixLength)
        If ValidByMonth(vFullDate, MinDate, MaxDate) Then Exit For
        vFullDate = DatePrefix & Right(Format(CStr(MinDate + i), "dd/mm/yyyy"), 10 - vPrefixLength)
        If ValidByDay(vFullDate, MinDate, MaxDate) Then Exit For Else vFullDate = Empty
    Next i

    PartYearCheck = Not IsEmpty(vFullDate)

End Function

Private Function ValidByMonth(ByVal DateString As String, ByVal MinDate As Date, ByVal MaxDate As Date) As Boolean

    Dim vTestDate As Variant

    On Error Resume Next
    vTestDate = CDate(MonthName(Left(DateString, 2)) & " " & Mid(DateString, 4, 2) & ", " & Right(DateString, 4))
    If vTestDate < MinDate Or vTestDate > MaxDate Then vTestDate = Empty
    On Error GoTo 0

    ValidByMonth = Not IsEmpty(vTestDate)

End Function

Private Function ValidByDay(ByVal DateString As String, ByVal MinDate As Date, ByVal MaxDate As Date) As Boolean

    Dim vTestDate As Variant

    On Error Resume Next
    vTestDate = CDate(MonthName(Mid(DateString, 4, 2)) & " " & Left(DateString, 2) & ", " & Right(DateString, 4))
    If vTestDate < MinDate Or vTestDate > MaxDate Then vTestDate = Empty
    On Error GoTo 0

    ValidByDay = Not IsEmpty(vTestDate)

End Function

Comment: 2/29 should pass roughly ever 4 years.
Comment: All dates have the same year?
Comment: There's no limit on the lower/upper bound. You can say lower = 11/18/1932, upper = 12/15/5354.
Comment: Then how to test the prefix without the year?  Do you just mean "invalid" dates  like "12/34" for example ?  Even your "2/29" example falls over when evaluated within a multi-year window
Comment: Whether something is valid or not should be determined partially based on the constraints. "12/34" should always fail, "2/29" should sometimes fail.
Comment: So - 01/11 should pass and 11/01 should  pass, but how to determine which is which? Using a datepicker is so much safer.
Comment: if the upper and lower bounds are several years apart, when should 2/29 pass? as long as there's at least one leap year in the interval?
Comment: Sorry for the long delay. Yes Tim, you understand correctly. I would prefer to use a date picker but I don't want people to have to install the package for it.
Answer: If you reject 02/29 and 29/02 Excel might do the rest for you if you input into a General format cell and then detect that cell's format with =CELL("format",cr) (column/row to suit).


Create Add-in for Acrobat Reader - PDF

Question: Can i create an Add-in for Acrobat Reader? (something like Office Add-ins in visual studio)
for example, i open a pdf file with Acrobat Reader, i want to add my custom button in the Reader in order to perform a specific action.
Is it doable?
Is it Free?
Does it require third-party components?
Thanks.
Comment: I'm in the same situation - how did you go?
Answer: I'm afraid the answer is slightly more complicated than indicated here. First of all, you do indeed need the (free) Adobe Acrobat SDK, which you can download here: http://www.adobe.com/devnet/acrobat.html
This will give you the documentation and sample codes for a number of different approaches.
However, you need to realise that you will not automatically be able to write plug-ins for Adobe Reader. Adobe Acrobat Standard or Pro, yes. Adobe Reader, no.
Adobe Reader is a free product and Adobe allows only those plug-ins that wouldn't violate that concepts. It is for example not permitted to write a Reader plug-in that edits a PDF file and saves those changes. Those are things restricted to Acrobat. To enforce these limitations, Adobe makes you sign plug-ins before they will actually work in Reader. During the signing process you will have to tell them what you intend to do, sign a bunch of papers and fork out a sizeable amount of cash. And if they don't like your project, they might not give you permission at all.
When you download the documentation however, also look at what you can do with JavaScripts. Things like adding menu items and buttons are normally possible with a bit of JavaScript that is executed as Adobe Reader launches. Once again though the functionality you'll have access to in Adobe Reader from JavaScript will be quite limited...
Comment: Are there alternative PDF readers which enable writing addons(extension, plguins) to them by C#?
Comment: Not that I'm aware of. The biggest competitor to Adobe Acrobat is perhaps Nitro PDF - I found this post on their support pages (http://nitropdf.zendesk.com/entries/24502438-Add-an-SDK-to-Nitro-Pro) suggesting that there is no SDK for their product.
Answer: Download source code for a GNU-licensed PDF readerlike Evince or Okular and fork it to your heart's content.  With some massaging they can be compiled into Win32 binaries (probably requiring lots of libraries from their Linux counterparts, but still do-able).
Okular source code:
https://github.com/KDE/okular
Evince source code:
https://github.com/GNOME/evince

Create Add-in for Acrobat Reader - PDF


Regex error in paste

Question: I use this paste option which have some regex expression:
a <- paste("/[\n\r]+|[\s]{2,}/g, \' \');")

the initial regex expression is:
(/[\n\r]+|[\s]{2,}/g, ' ')

and I receive this error:
Error: '\s' is an unrecognized escape in character string starting ""(/[\n\r]+|[\s"

any idea what can I use to make it to see the whole regex expression acceptable?
Comment: Try `\\s`, `\\\s`, and `\\\\s`
Answer: Use four backslashes with your escape characters.  Two will yield a literal backslash, and the other two handle the escape character.
a <- paste("/[\\\\n\\\\r]+|[\\\\s]{2,}/g, \' \');")

Comment: thank you for your answer. I guess I should expect when I press a I should give back the initial `(/[\n\r]+|[\s]{2,}/g, ' ')` but I take this `"/[\\\\n\\\\r]+|[\\\\s]{2,}/g, ' ');"`
Comment: So did my answer help your problem?  I think you have an escaping problem.  Not sure if you need two or four backslashes though.
Comment: Sorry but it is not the expected. I tried the \\ or \\\ for s but it is not working. I can't understand why \n and \r works without additional \ and s has this problem
Comment: Please update your question and show us what actual string you need, and how that string will be used.  Keep in mind that if you plan on feeding the string into a regex engine, this may require extra handling.

Regex error in paste


I need help understanding how to assign roman numerals to a key as well as how to do a melodic analysis

Question: Here is the link to the questions:
https://scontent.fybz2-1.fna.fbcdn.net/v/t1.15752-9/s2048x2048/76767498_631590154044645_5429312693389492224_n.jpg?_nc_cat=108&_nc_ohc=xzP3WM_WkZMAQmsld8rZQ8kb20ASCOrOSCyvGWN0pnvYS5Q0eX7tCdXZg&_nc_ht=scontent.fybz2-1.fna&oh=dcfbf15fad574a77425df2f45d7bf38e&oe=5E7EAB39
Can someone explain how to figure out what the roman numerals are for the underlined chords?
Also, how do I know which notes to look at when analyzing the melody when labelling it as passing tone, suspension, etc (do I look at the whole chord+melody until the next chord+melody)?
Any help is greatly appreciated, thanks!!
Comment: Did you look up the related questions on the right corner of this site? 1. you missed in your marks below the flats! 2nd. You don't have to analyze the passing and short changing tones. 3. Is this a homework? (SE doesn't do your homework ...)
Comment: I'm voting to close this question as off-topic because it's homework/quiz. You will find the answers by reading the chapter and asking your teacher. If you have read the material, explain what is confusing you in the question.
Answer: Here's a start.

First, identify the key:
<code>You have already found the key to be Eb major.
</code>

Then, write the notes in the key/scale:

    1  2  3  4  5  6  7  1
    Eb F  G  Ab Bb C  D  Eb

Now, find the primary and secondary triad chords of the scale:

    I     Eb G  Bb
    ii    F  Ab C
    iii   G  Bb D
    IV    Ab C  Eb
    V     Bb D  F
    vi    C  Eb G
    vii°  D  F  Ab

Now match the triads with the chords.

(Sorry I can't help with figured bass)
Comment: what if the there are two of the same notes in one chord? ex D Bflat D
Comment: Doubling a note in a chord is okay, but it makes it a bit harder to identify which chord it is.

The first and third notes (first two columns of my table) in the chords are more important than the fifth (third column).

So, with D, Bflat, D, it is a form the V chord.
Answer: An important point to remember when writing out the chord tones is to designate which tones include accidentals. Without the accidentals, we're actually talking about completely different chords and it makes it more difficult to properly analyze. If you refer back to the key signature, it will tell you which notes in the scale are to be flatted or sharped and you will be able to sort these things out more accurately. I hope this helps.
Comment: By way of explanation about my use of the words flatted and sharped, I'm referring to the addition of a flat sign or a sharp sign to the particular note, rather than to the actual raising in pitch or reducing in pitch of a scale tone. I find changing my wording around sometimes alters the meaning of the point I'm attempting to make. If you choose to edit my answer, please don't change the meaning. Thank you.


Create radio button for each sharepoint list item

Question: how can i assign radio button for each SharePoint list item using JavaScript and add onclick function to it?
Comment: Share your code what you have tried so far.
Answer: Easy!
<form>
Radio number 1<input name="radio1" type="radio" onclick="myFunction()"></input></form>

This is the better I can help without any code :/ If you can edit your question and share a bit of code.
Hope I helped!