/*===================================================================
Chord recognition
===================================================================
971487
function determine(chord, shorthand, no_inversions, no_polychords) {
	if(shorthand == null) {
		shorthand = false;
	}
	if(no_inversions == null) {
		no_inversions = false;
	}
	if(no_polychords == null) {
		no_polychords = false;
	}
	if(chord == []) {
		return [];
	} else if(chord.length == 1) {
		return chord;
	} else if(chord.length == 2) {
		return [intervals.determine(chord[0], chord[1])];
	} else if(chord.length == 3) {
		return determine_triad(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 4) {
		return determine_seventh(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 5) {
		return determine_extended_chord5(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 6) {
		return determine_extended_chord6(chord, shorthand, no_inversions, no_polychords);
	} else if(chord.length == 7) {
		return determine_extended_chord7(chord, shorthand, no_inversions, no_polychords);
	} else {
		return determine_polychords(chord, shorthand);
	}
}
101607
function(tune) {
  var ret = {
    attributes: {
      divisions: 1 /tune.getBeatLength(),
      clef: {
        line: 2
      },
      key: {},
      time: {}
    }
  };
  var measures = [];
  var measureCounter = 0;
  var barlineCounter = 0;

  // parse lines
  for (var l = 0; l < tune.lines.length; l++) {
    for (var s = 0; s < tune.lines[l].staff.length; s++) {
      var staff = tune.lines[l].staff[s];

      // parse default clef, key, meter
      if (l === 0 && s === 0) {
        ret.attributes.clef.sign = getKeyByValue(clefs, staff.clef.type);
        ret.attributes.clef.line = staff.clef.clefPos / 2;
        ret.attributes.key.fifths = parseInt(getKeyByValue(circleOfFifths, staff.key.root));
        ret.attributes.time.beats = staff.meter.value[0].num;
        ret.attributes.time['beat-type'] = staff.meter.value[0].den;
      }

      for (var v = 0; v < staff.voices.length; v++) {
        for (var t = 0; t < staff.voices[v].length; t++) {
          var token = staff.voices[v][t];

          // init measure if none exists
          if (measures[measureCounter] === undefined) {
            measures[measureCounter] = new Measure();
          }

          switch (token.el_type) {
            case "note":
              measures[measureCounter].addNote(token, ret.attributes.divisions, ret.attributes.time['beat-type']);
              break;
            case "bar":
              if (token.type === 'bar_right_repeat') {
                measures[measureCounter].setRepeatRight();
              }
              measureCounter++;
              if (measures[measureCounter] === undefined) {
                measures[measureCounter] = new Measure();
              }
              if (token.type === 'bar_left_repeat') {
                measures[measureCounter].setRepeatLeft();
              }
              break;
            default:
              console.log(token);
              break;
          }
        }
      }
    }
  }

  // put measures together
  ret.measures = [];
  for (var i = 0; i < measures.length; i++) {
    var measure = measures[i].get();
    if (measure.notes.length > 0) {
      ret.measures.push(measure);
    }
  }
  return ret;
}
141440
private void parseLastConsonant() {
		if (!validViSyll)
			return;
		if (iCurPos > strSyllable.length())
			strLastConsonant = ZERO;
		String strCon = strSyllable.substring(iCurPos, strSyllable.length());

		if (strCon.length() > 3) {
			validViSyll = false;
			return;
		}

		Iterator iter = alLastConsonants.iterator();
		while (iter.hasNext()) {
			String tempLastCon = (String) iter.next();
			if (strCon.equals(tempLastCon)) {
				strLastConsonant = tempLastCon;
				iCurPos += strLastConsonant.length();
				return;
			}
		}
		strLastConsonant = ZERO;
		if (iCurPos >= strSyllable.length())
			validViSyll = true;
		else validViSyll = false;
		
		return;
	}
952794
function(obj, num, chordPos) {
        if (currSlur[chordPos] === undefined) {
          // There isn't an exact match for note position, but we'll take any other open slur.
          for (x = 0; x < currSlur.length; x++) {
            if (currSlur[x] !== undefined) {
              chordPos = x;
              break;
            }
          }
          if (currSlur[chordPos] === undefined) {
            var offNum = chordPos*100+1;
            Common.each(obj.endSlur, function(x) { if (offNum === x) --offNum; });
            currSlur[chordPos] = [offNum];
          }
        }
        var slurNum;
        for (var i = 0; i < num; i++) {
          slurNum = currSlur[chordPos].pop();
          obj.endSlur.push(slurNum);
//					lyr.syllable += '<' + slurNum;	// TODO-PER: debugging
        }
        if (currSlur[chordPos].length === 0)
          delete currSlur[chordPos];
        return slurNum;
      }
140764
def _parse(self, chord):
        
        root, quality, appended, on = parse(chord)
        self._root = root
        self._quality = quality
        self._appended = appended
        self._on = on
285695
function ResponsiveAccordionTabs(element, options) {
      _classCallCheck(this, ResponsiveAccordionTabs);

      this.$element = $(element);
      this.options = $.extend({}, this.$element.data(), options);
      this.rules = this.$element.data('responsive-accordion-tabs');
      this.currentMq = null;
      this.currentPlugin = null;
      if (!this.$element.attr('id')) {
        this.$element.attr('id', Foundation.GetYoDigits(6, 'responsiveaccordiontabs'));
      };

      this._init();
      this._events();

      Foundation.registerPlugin(this, 'ResponsiveAccordionTabs');
    }
280745
function html()
	{
		$version = get_option('acf_version','1.0.5');
		$next = false;

		// list of starting points
		if( $version < '3.0.0' )
		{
			$next = '3.0.0';
		}
		elseif( $version < '3.1.8' )
		{
			$next = '3.1.8';
		}
		elseif( $version < '3.2.5' )
		{
			$next = '3.2.5';
		}
		elseif( $version < '3.3.3' )
		{
			$next = '3.3.3';
		}
		elseif( $version < '3.4.1' )
		{
			$next = '3.4.1';
		}

		?>
		<script type="text/javascript">
		(function($){

			function add_message(messaage)
			{
				$('#wpbody-content').append('<p>' + messaage + '</p>');
			}

			function run_upgrade(version)
			{
				$.ajax({
					url: ajaxurl,
					data: {
						action : 'acf_upgrade',
						version : version
					},
					type: 'post',
					dataType: 'json',
					success: function(json){

						if(json)
						{
							if(json.status)
							{
								add_message(json.message);

								// next update?
								if(json.next)
								{
									run_upgrade(json.next);
								}
								else
								{
									// all done
									add_message('Upgrade Complete! <a href="<?php echo admin_url(); ?>edit.php?post_type=acf">Continue to ACF &raquo;</a>');
								}
							}
							else
							{
								// error!
								add_message('Error: ' + json.message);
							}
						}
						else
						{
							// major error!
							add_message('Sorry. Something went wrong during the upgrade process. Please report this on the support forum');
						}
					}
				});
			}

			<?php if($next){ echo 'run_upgrade("' . $next . '");'; } ?>

		})(jQuery);
		</script>
		<style type="text/css">
			#message {
				display: none;
			}
		</style>
		<?php

		if(!$next)
		{
			echo '<p>No Upgrade Required</p>';
		}
	}
606435
function (root, symbol, bass) {
  var name = root.name + symbol;
  var octave = bass ? bass.octave : root.octave;

  if (bass) name += '/' + bass.name;
  return new Chord(name, octave);
}
237558
protected void adaptToTune(Tune tune, ScoreMetrics metrics) {
		//reinit the values of the engraving mode
		setMode(m_mode, m_variation);
		
		if (m_mode != NONE) {
			//11=notes spacing at 45px (default font size)
			double ratio = 100 * (11 / metrics.getNotesSpacing()) - 100;
			int oldVariation = m_variation;
			setMode(m_mode, m_variation - (int)ratio);
			m_variation = oldVariation;
			
			Music music = tune.getMusic();
			Note shortestNote = music.getShortestNoteInAllVoices();
			int shortestDuration = Note.SIXTEENTH;
			if (shortestNote != null)
				shortestDuration = shortestNote.getDuration();
			//System.out.println("shortest note duration = "+shortest.getDuration());
			short min = /*(shortestDuration >= Note.QUARTER)
				? Note.SIXTEENTH
				: */Note.SIXTEENTH;
			if (shortestDuration > min) {
				TreeSet set = new TreeSet(spacesAfter.keySet());
				Object[] durations = set.toArray();
				int iMin = 0, iShortest = 0;
				for (int i = 0; i < durations.length; i++) {
					//System.out.println("durations["+i+"] = "+durations[i]);
					int j = (Integer) durations[i];
					if (j == min)
						iMin = i;
					if (j == shortestDuration)
						iShortest = i;
				}
				int offset = (iShortest>iMin)?iShortest - iMin:0;
				if (offset != 0) {
					for (int i = durations.length-1; i >= iShortest; i--) {
						//DEBUG
						/*String s = "";
						for (Iterator itSet = set.iterator(); itSet.hasNext();) {
							Integer i2 = (Integer) itSet.next();
							System.out.print(i2+"\t");
							s += getSpaceAfter(i2.intValue())+"\t";
						}
						System.out.println("\n"+s);*/
						setSpaceAfter((Integer) durations[i],
							getSpaceAfter((Integer) durations[i - offset])
							);
					}
				}
				//System.out.println(spaceAfter.keySet().toArray());
				//System.out.println(spaceAfter.entrySet().toArray());
			}
		}
	}
962505
def note_to_chord(notes):
    
    if not notes:
        raise ValueError("Please specify notes which consist a chord.")
    root = notes[0]
    root_and_positions = []
    for rotated_notes in get_all_rotated_notes(notes):
        rotated_root = rotated_notes[0]
        root_and_positions.append([rotated_root, notes_to_positions(rotated_notes, rotated_notes[0])])
    chords = []
    for temp_root, positions in root_and_positions:
        quality = find_quality(positions)
        if quality is None:
            continue
        if temp_root == root:
            chord = "{}{}".format(root, quality)
        else:
            chord = "{}{}/{}".format(temp_root, quality, root)
        chords.append(Chord(chord))
    return chords
704187
function (chords, settings) {
  var chordEvents = makeChordEvents(chords, settings);

  // Set all channels
  var setPatches = _.reduce(_.range(0xf), function (buffer, channel) {
    return Buffer.concat([buffer, makePatchEvent(channel, settings.chordPatch)]);
  }, new Buffer(0));

  var length = setPatches.length + chordEvents.length + trackFooter.length;

  return Buffer.concat([trackHeader, padNumber(length, 4), setPatches, chordEvents, trackFooter]);
}
579919
function triad(note, key) {
	return [note, intervals.third(note, key), intervals.fifth(note, key)]
}
192724
def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
        no_polychords=False):
    """"""
    if len(chord) != 5:
        # warning raise exeption: not an extended chord
        return False

    def inversion_exhauster(chord, shorthand, tries, result, polychords):
        """Recursive helper function."""
        def add_result(short):
            result.append((short, tries, chord[0]))

        triads = determine_triad(chord[:3], True, True)
        sevenths = determine_seventh(chord[:4], True, True, True)

        # Determine polychords
        if tries == 1 and not no_polychords:
            polychords += determine_polychords(chord, shorthand)

        intval4 = intervals.determine(chord[0], chord[4])
        for seventh in sevenths:
            seventh = seventh[len(chord[0]):]
            if seventh == 'M7':
                if intval4 == 'major second':
                    add_result('M9')
            elif seventh == 'm7':
                if intval4 == 'major second':
                    add_result('m9')
                elif intval4 == 'perfect fourth':
                    add_result('m11')
            elif seventh == '7':
                if intval4 == 'major second':
                    add_result('9')
                elif intval4 == 'minor second':
                    add_result('7b9')
                elif intval4 == 'augmented second':
                    add_result('7#9')
                elif intval4 == 'minor third':
                    add_result('7b12')
                elif intval4 == 'augmented fourth':
                    add_result('7#11')
                elif intval4 == 'major sixth':
                    add_result('13')
            elif seventh == 'M6':
                if intval4 == 'major second':
                    add_result('6/9')
                elif intval4 == 'minor seventh':
                    add_result('6/7')
        if tries != 5 and not no_inversions:
            return inversion_exhauster([chord[-1]] + chord[:-1], shorthand,
                    tries + 1, result, polychords)
        else:
            res = []
            for r in result:
                if shorthand:
                    res.append(r[2] + r[0])
                else:
                    res.append(r[2] + chord_shorthand_meaning[r[0]]
                                + int_desc(r[1]))
            return res + polychords

    return inversion_exhauster(chord, shorthand, 1, [], [])
1211360
function(oneaccidental) {
    var key = this.key(), limit = oneaccidental ? 2 : 3;

    return ['m3', 'm2', 'm-2', 'm-3']
      .map(this.interval.bind(this))
      .filter(function(note) {
      var acc = note.accidentalValue();
      var diff = key - (note.key() - acc);

      if (diff < limit && diff > -limit) {
        var product = vector.mul(knowledge.sharp, diff - acc);
        note.coord = vector.add(note.coord, product);
        return true;
      }
    });
  }
9359
function convertJsonToAbc(input) {
  var outputData = "";
  outputData += "X:1\n";
  if (typeof input.id !== 'undefined') {
    outputData += "T:"
      + input.id
      + "\n";
  }
  outputData += "M:"
    + input.attributes.time.beats
    + "/"
    + input.attributes.time["beat-type"]
    + "\n";
  outputData += "L:"
    + "1/"
    + (input.attributes.divisions * 4)
    + "\n";
  outputData += "K:"
    + getAbcKey(input.attributes.key.fifths, input.attributes.key.mode)
    + "\n";
  outputData += "K:"
    + getAbcClef(input.attributes.clef.sign)
    + "\n";

  for (var i = 0; i < input.measures.length; i++) {
    if (i % 4 === 0 && i > 0) { // 4 measures per line
      outputData += "\n";
      outputData += "|";
    }
    var measure = input.measures[i];
    if (measure.attributes.repeat.left === true || measure.attributes.repeat.left === 'true') {
      outputData += ":";
    }

    for (var j = 0; j < measure.notes.length; j++) {

      outputData += getAbcNote(measure.notes[j-1], measure.notes[j]);
    }

    if (measure.attributes.repeat.right === true || measure.attributes.repeat.right === 'true') {
      outputData += ":";
    }
    outputData += "|";

  }

  return outputData;
}
1293726
function (root, bass, intervals) {
  var chord = _.chain(intervals)
    .map(function (quality, number) {
      var int;
      if (quality) {
        // #9 is stored as b10, so special case this
        if (number === 10 && quality === 'm') {
          int = interval.create(9, 'aug');
        }
        else {
          int = interval.create(number, quality);
        }
        return root.transpose(int);
      }
    })
    .compact()
    .value();

  var bassIndex;

  // Handle slash chords
  if (bass && !root.enharmonic(bass)) {
    bassIndex = _.findIndex(chord, bass.enharmonic.bind(bass));

    if (bassIndex > -1) { // Rotate chord so bass is first
      chord = rotateArr(chord, bassIndex);
    }
    else { // Otherwise, add bass to beginning
      chord.unshift(bass);
    }
  }

  return chord;
}
591353
function startBenchmark() {
  let audioContext =
    new OfflineAudioContext(numberOutputChannels,
      durationSeconds * sampleRate, sampleRate);
  if (typeof webkitOfflineAudioContext !== 'undefined') {
    playback.textContent = 'Begin';
    playback.disabled = false;
    let statusBar = document.getElementById('statusBar');
    statusBar.innerHTML = 'Benchmarks are unsupported on Safari/iOS.';
    statusBar.hidden = false;
    let progressBar = document.getElementById('progressBar');
    progressBar.hidden = true;
    return;
  }

  let audioElement = document.createElement('audio');
  audioElement.src = 'resources/cube-sound.wav';
  audioElement.crossOrigin = 'anonymous';
  audioElement.load();
  audioElement.loop = true;
  let audioElementSource = audioContext.createMediaElementSource(audioElement);

  let numberSources =
    Number(document.getElementById('numberSourcesNumber').value);
  if (numberSources < 1) {
    playback.textContent = 'Begin';
    playback.disabled = false;
    return;
  }

  let renderingMode = document.getElementById('renderingModeSelect');
  let order = -1;
  switch (renderingMode.value) {
    case 'foa':
    {
      order = 1;
    }
    break;
    case 'soa':
    {
      order = 2;
    }
    break;
    case 'toa':
    {
      order = 3;
    }
    break;
  }

  let sources = [];
  if (order > -1) {
    let options = selectDimensionsAndMaterials();
    let scene = new ResonanceAudio(audioContext, {
      ambisonicOrder: order,
      dimensions: options.dimensions,
      materials: options.materials,
    });
    for (let i = 0; i < numberSources; i++) {
      sources[i] = scene.createSource();
      audioElementSource.connect(sources[i].input);
    }
    scene.output.connect(audioContext.destination);
  } else {
    for (let i = 0; i < numberSources; i++) {
      sources[i] = audioContext.createPanner();
      sources[i].panningModel = 'HRTF';
      sources[i].distanceModel = 'inverse';
      sources[i].refDistance = 0.1;
      sources[i].maxDistance = 1000;
      audioElementSource.connect(sources[i]);
      sources[i].connect(audioContext.destination);
    }
  }

  for (let i = 0; i < numberSources; i++) {
    let theta = Math.random() * Math.PI * 2;
    let phi = Math.acos(Math.random() * 2 - 1);
    let x = Math.cos(theta) * Math.sin(phi);
    let y = Math.cos(phi);
    let z = Math.sin(theta) * Math.sin(phi);
    sources[i].setPosition(x, y, z);
  }

  audioElement.currentTime = 0;
  audioElement.play();

  window.setTimeout(function() {
    let startTime = Date.now();
    audioContext.startRendering().then(function(renderedBuffer) {
      playback.textContent = 'Begin';
      playback.disabled = false;
      let currentTime = (Date.now() - startTime) / 1000;
      let statusBar = document.getElementById('statusBar');
      statusBar.innerHTML = 'Elapsed Time: ' + currentTime + ' seconds.';
      statusBar.hidden = false;
      let progressBar = document.getElementById('progressBar');
      progressBar.hidden = true;
    }).catch(function(error) {
      console.log(error);
    });
  }, 100);
}