repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
bspaans/python-mingus
|
mingus/core/notes.py
|
int_to_note
|
def int_to_note(note_int, accidentals='#'):
"""Convert integers in the range of 0-11 to notes in the form of C or C#
or Db.
Throw a RangeError exception if the note_int is not in the range 0-11.
If not specified, sharps will be used.
Examples:
>>> int_to_note(0)
'C'
>>> int_to_note(3)
'D#'
>>> int_to_note(3, 'b')
'Eb'
"""
if note_int not in range(12):
raise RangeError('int out of bounds (0-11): %d' % note_int)
ns = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
nf = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
if accidentals == '#':
return ns[note_int]
elif accidentals == 'b':
return nf[note_int]
else:
raise FormatError("'%s' not valid as accidental" % accidentals)
|
python
|
def int_to_note(note_int, accidentals='
if note_int not in range(12):
raise RangeError('int out of bounds (0-11): %d' % note_int)
ns = ['C', 'C
nf = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
if accidentals == '
return ns[note_int]
elif accidentals == 'b':
return nf[note_int]
else:
raise FormatError("'%s' not valid as accidental" % accidentals)
|
[
"def",
"int_to_note",
"(",
"note_int",
",",
"accidentals",
"=",
"'#'",
")",
":",
"if",
"note_int",
"not",
"in",
"range",
"(",
"12",
")",
":",
"raise",
"RangeError",
"(",
"'int out of bounds (0-11): %d'",
"%",
"note_int",
")",
"ns",
"=",
"[",
"'C'",
",",
"'C#'",
",",
"'D'",
",",
"'D#'",
",",
"'E'",
",",
"'F'",
",",
"'F#'",
",",
"'G'",
",",
"'G#'",
",",
"'A'",
",",
"'A#'",
",",
"'B'",
"]",
"nf",
"=",
"[",
"'C'",
",",
"'Db'",
",",
"'D'",
",",
"'Eb'",
",",
"'E'",
",",
"'F'",
",",
"'Gb'",
",",
"'G'",
",",
"'Ab'",
",",
"'A'",
",",
"'Bb'",
",",
"'B'",
"]",
"if",
"accidentals",
"==",
"'#'",
":",
"return",
"ns",
"[",
"note_int",
"]",
"elif",
"accidentals",
"==",
"'b'",
":",
"return",
"nf",
"[",
"note_int",
"]",
"else",
":",
"raise",
"FormatError",
"(",
"\"'%s' not valid as accidental\"",
"%",
"accidentals",
")"
] |
Convert integers in the range of 0-11 to notes in the form of C or C#
or Db.
Throw a RangeError exception if the note_int is not in the range 0-11.
If not specified, sharps will be used.
Examples:
>>> int_to_note(0)
'C'
>>> int_to_note(3)
'D#'
>>> int_to_note(3, 'b')
'Eb'
|
[
"Convert",
"integers",
"in",
"the",
"range",
"of",
"0",
"-",
"11",
"to",
"notes",
"in",
"the",
"form",
"of",
"C",
"or",
"C#",
"or",
"Db",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L42-L67
|
bspaans/python-mingus
|
mingus/core/notes.py
|
is_valid_note
|
def is_valid_note(note):
"""Return True if note is in a recognised format. False if not."""
if not _note_dict.has_key(note[0]):
return False
for post in note[1:]:
if post != 'b' and post != '#':
return False
return True
|
python
|
def is_valid_note(note):
if not _note_dict.has_key(note[0]):
return False
for post in note[1:]:
if post != 'b' and post != '
return False
return True
|
[
"def",
"is_valid_note",
"(",
"note",
")",
":",
"if",
"not",
"_note_dict",
".",
"has_key",
"(",
"note",
"[",
"0",
"]",
")",
":",
"return",
"False",
"for",
"post",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"post",
"!=",
"'b'",
"and",
"post",
"!=",
"'#'",
":",
"return",
"False",
"return",
"True"
] |
Return True if note is in a recognised format. False if not.
|
[
"Return",
"True",
"if",
"note",
"is",
"in",
"a",
"recognised",
"format",
".",
"False",
"if",
"not",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L73-L80
|
bspaans/python-mingus
|
mingus/core/notes.py
|
note_to_int
|
def note_to_int(note):
"""Convert notes in the form of C, C#, Cb, C##, etc. to an integer in the
range of 0-11.
Throw a NoteFormatError exception if the note format is not recognised.
"""
if is_valid_note(note):
val = _note_dict[note[0]]
else:
raise NoteFormatError("Unknown note format '%s'" % note)
# Check for '#' and 'b' postfixes
for post in note[1:]:
if post == 'b':
val -= 1
elif post == '#':
val += 1
return val % 12
|
python
|
def note_to_int(note):
if is_valid_note(note):
val = _note_dict[note[0]]
else:
raise NoteFormatError("Unknown note format '%s'" % note)
for post in note[1:]:
if post == 'b':
val -= 1
elif post == '
val += 1
return val % 12
|
[
"def",
"note_to_int",
"(",
"note",
")",
":",
"if",
"is_valid_note",
"(",
"note",
")",
":",
"val",
"=",
"_note_dict",
"[",
"note",
"[",
"0",
"]",
"]",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"Unknown note format '%s'\"",
"%",
"note",
")",
"# Check for '#' and 'b' postfixes",
"for",
"post",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"post",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"post",
"==",
"'#'",
":",
"val",
"+=",
"1",
"return",
"val",
"%",
"12"
] |
Convert notes in the form of C, C#, Cb, C##, etc. to an integer in the
range of 0-11.
Throw a NoteFormatError exception if the note format is not recognised.
|
[
"Convert",
"notes",
"in",
"the",
"form",
"of",
"C",
"C#",
"Cb",
"C##",
"etc",
".",
"to",
"an",
"integer",
"in",
"the",
"range",
"of",
"0",
"-",
"11",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L82-L99
|
bspaans/python-mingus
|
mingus/core/notes.py
|
reduce_accidentals
|
def reduce_accidentals(note):
"""Reduce any extra accidentals to proper notes.
Example:
>>> reduce_accidentals('C####')
'E'
"""
val = note_to_int(note[0])
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
else:
raise NoteFormatError("Unknown note format '%s'" % note)
if val >= note_to_int(note[0]):
return int_to_note(val%12)
else:
return int_to_note(val%12, 'b')
|
python
|
def reduce_accidentals(note):
val = note_to_int(note[0])
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '
val += 1
else:
raise NoteFormatError("Unknown note format '%s'" % note)
if val >= note_to_int(note[0]):
return int_to_note(val%12)
else:
return int_to_note(val%12, 'b')
|
[
"def",
"reduce_accidentals",
"(",
"note",
")",
":",
"val",
"=",
"note_to_int",
"(",
"note",
"[",
"0",
"]",
")",
"for",
"token",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"Unknown note format '%s'\"",
"%",
"note",
")",
"if",
"val",
">=",
"note_to_int",
"(",
"note",
"[",
"0",
"]",
")",
":",
"return",
"int_to_note",
"(",
"val",
"%",
"12",
")",
"else",
":",
"return",
"int_to_note",
"(",
"val",
"%",
"12",
",",
"'b'",
")"
] |
Reduce any extra accidentals to proper notes.
Example:
>>> reduce_accidentals('C####')
'E'
|
[
"Reduce",
"any",
"extra",
"accidentals",
"to",
"proper",
"notes",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L101-L119
|
bspaans/python-mingus
|
mingus/core/notes.py
|
remove_redundant_accidentals
|
def remove_redundant_accidentals(note):
"""Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E'
"""
val = 0
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
result = note[0]
while val > 0:
result = augment(result)
val -= 1
while val < 0:
result = diminish(result)
val += 1
return result
|
python
|
def remove_redundant_accidentals(note):
val = 0
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '
val += 1
result = note[0]
while val > 0:
result = augment(result)
val -= 1
while val < 0:
result = diminish(result)
val += 1
return result
|
[
"def",
"remove_redundant_accidentals",
"(",
"note",
")",
":",
"val",
"=",
"0",
"for",
"token",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"result",
"=",
"note",
"[",
"0",
"]",
"while",
"val",
">",
"0",
":",
"result",
"=",
"augment",
"(",
"result",
")",
"val",
"-=",
"1",
"while",
"val",
"<",
"0",
":",
"result",
"=",
"diminish",
"(",
"result",
")",
"val",
"+=",
"1",
"return",
"result"
] |
Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E'
|
[
"Remove",
"redundant",
"sharps",
"and",
"flats",
"from",
"the",
"given",
"note",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L121-L143
|
bspaans/python-mingus
|
mingus/extra/musicxml.py
|
_gcd
|
def _gcd(a=None, b=None, terms=None):
"""Return greatest common divisor using Euclid's Algorithm."""
if terms:
return reduce(lambda a, b: _gcd(a, b), terms)
else:
while b:
(a, b) = (b, a % b)
return a
|
python
|
def _gcd(a=None, b=None, terms=None):
if terms:
return reduce(lambda a, b: _gcd(a, b), terms)
else:
while b:
(a, b) = (b, a % b)
return a
|
[
"def",
"_gcd",
"(",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"terms",
"=",
"None",
")",
":",
"if",
"terms",
":",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"_gcd",
"(",
"a",
",",
"b",
")",
",",
"terms",
")",
"else",
":",
"while",
"b",
":",
"(",
"a",
",",
"b",
")",
"=",
"(",
"b",
",",
"a",
"%",
"b",
")",
"return",
"a"
] |
Return greatest common divisor using Euclid's Algorithm.
|
[
"Return",
"greatest",
"common",
"divisor",
"using",
"Euclid",
"s",
"Algorithm",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/musicxml.py#L43-L50
|
bspaans/python-mingus
|
mingus/extra/musicxml.py
|
write_Composition
|
def write_Composition(composition, filename, zip=False):
"""Create an XML file (or MXL if compressed) for a given composition."""
text = from_Composition(composition)
if not zip:
f = open(filename + '.xml', 'w')
f.write(text)
f.close()
else:
import zipfile
import os
zf = zipfile.ZipFile(filename + '.mxl', mode='w',
compression=zipfile.ZIP_DEFLATED)
zi = zipfile.ZipInfo('META-INF' + os.sep + 'container.xml')
zi.external_attr = 0660 << 16L
zf.writestr(zi,
"<?xml version='1.0' encoding='UTF-8'?>"
"<container><rootfiles><rootfile full-path='{0}.xml'/>"
"</rootfiles></container>".format(filename))
zi = zipfile.ZipInfo(filename + '.xml')
zi.external_attr = 0660 << 16L
zf.writestr(zi, text)
zf.close()
|
python
|
def write_Composition(composition, filename, zip=False):
text = from_Composition(composition)
if not zip:
f = open(filename + '.xml', 'w')
f.write(text)
f.close()
else:
import zipfile
import os
zf = zipfile.ZipFile(filename + '.mxl', mode='w',
compression=zipfile.ZIP_DEFLATED)
zi = zipfile.ZipInfo('META-INF' + os.sep + 'container.xml')
zi.external_attr = 0660 << 16L
zf.writestr(zi,
"<?xml version='1.0' encoding='UTF-8'?>"
"<container><rootfiles><rootfile full-path='{0}.xml'/>"
"</rootfiles></container>".format(filename))
zi = zipfile.ZipInfo(filename + '.xml')
zi.external_attr = 0660 << 16L
zf.writestr(zi, text)
zf.close()
|
[
"def",
"write_Composition",
"(",
"composition",
",",
"filename",
",",
"zip",
"=",
"False",
")",
":",
"text",
"=",
"from_Composition",
"(",
"composition",
")",
"if",
"not",
"zip",
":",
"f",
"=",
"open",
"(",
"filename",
"+",
"'.xml'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"text",
")",
"f",
".",
"close",
"(",
")",
"else",
":",
"import",
"zipfile",
"import",
"os",
"zf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"filename",
"+",
"'.mxl'",
",",
"mode",
"=",
"'w'",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"zi",
"=",
"zipfile",
".",
"ZipInfo",
"(",
"'META-INF'",
"+",
"os",
".",
"sep",
"+",
"'container.xml'",
")",
"zi",
".",
"external_attr",
"=",
"0660",
"<<",
"16L",
"zf",
".",
"writestr",
"(",
"zi",
",",
"\"<?xml version='1.0' encoding='UTF-8'?>\"",
"\"<container><rootfiles><rootfile full-path='{0}.xml'/>\"",
"\"</rootfiles></container>\"",
".",
"format",
"(",
"filename",
")",
")",
"zi",
"=",
"zipfile",
".",
"ZipInfo",
"(",
"filename",
"+",
"'.xml'",
")",
"zi",
".",
"external_attr",
"=",
"0660",
"<<",
"16L",
"zf",
".",
"writestr",
"(",
"zi",
",",
"text",
")",
"zf",
".",
"close",
"(",
")"
] |
Create an XML file (or MXL if compressed) for a given composition.
|
[
"Create",
"an",
"XML",
"file",
"(",
"or",
"MXL",
"if",
"compressed",
")",
"for",
"a",
"given",
"composition",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/musicxml.py#L303-L324
|
bspaans/python-mingus
|
mingus/core/keys.py
|
get_key_signature
|
def get_key_signature(key='C'):
"""Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures.
"""
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
for couple in keys:
if key in couple:
accidentals = keys.index(couple) - 7
return accidentals
|
python
|
def get_key_signature(key='C'):
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
for couple in keys:
if key in couple:
accidentals = keys.index(couple) - 7
return accidentals
|
[
"def",
"get_key_signature",
"(",
"key",
"=",
"'C'",
")",
":",
"if",
"not",
"is_valid_key",
"(",
"key",
")",
":",
"raise",
"NoteFormatError",
"(",
"\"unrecognized format for key '%s'\"",
"%",
"key",
")",
"for",
"couple",
"in",
"keys",
":",
"if",
"key",
"in",
"couple",
":",
"accidentals",
"=",
"keys",
".",
"index",
"(",
"couple",
")",
"-",
"7",
"return",
"accidentals"
] |
Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures.
|
[
"Return",
"the",
"key",
"signature",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L73-L85
|
bspaans/python-mingus
|
mingus/core/keys.py
|
get_key_signature_accidentals
|
def get_key_signature_accidentals(key='C'):
"""Return the list of accidentals present into the key signature."""
accidentals = get_key_signature(key)
res = []
if accidentals < 0:
for i in range(-accidentals):
res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b'))
elif accidentals > 0:
for i in range(accidentals):
res.append('{0}{1}'.format(notes.fifths[i], '#'))
return res
|
python
|
def get_key_signature_accidentals(key='C'):
accidentals = get_key_signature(key)
res = []
if accidentals < 0:
for i in range(-accidentals):
res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b'))
elif accidentals > 0:
for i in range(accidentals):
res.append('{0}{1}'.format(notes.fifths[i], '
return res
|
[
"def",
"get_key_signature_accidentals",
"(",
"key",
"=",
"'C'",
")",
":",
"accidentals",
"=",
"get_key_signature",
"(",
"key",
")",
"res",
"=",
"[",
"]",
"if",
"accidentals",
"<",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"-",
"accidentals",
")",
":",
"res",
".",
"append",
"(",
"'{0}{1}'",
".",
"format",
"(",
"list",
"(",
"reversed",
"(",
"notes",
".",
"fifths",
")",
")",
"[",
"i",
"]",
",",
"'b'",
")",
")",
"elif",
"accidentals",
">",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"accidentals",
")",
":",
"res",
".",
"append",
"(",
"'{0}{1}'",
".",
"format",
"(",
"notes",
".",
"fifths",
"[",
"i",
"]",
",",
"'#'",
")",
")",
"return",
"res"
] |
Return the list of accidentals present into the key signature.
|
[
"Return",
"the",
"list",
"of",
"accidentals",
"present",
"into",
"the",
"key",
"signature",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L87-L98
|
bspaans/python-mingus
|
mingus/core/keys.py
|
get_notes
|
def get_notes(key='C'):
"""Return an ordered list of the notes in this natural key.
Examples:
>>> get_notes('F')
['F', 'G', 'A', 'Bb', 'C', 'D', 'E']
>>> get_notes('c')
['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']
"""
if _key_cache.has_key(key):
return _key_cache[key]
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
result = []
# Calculate notes
altered_notes = map(operator.itemgetter(0),
get_key_signature_accidentals(key))
if get_key_signature(key) < 0:
symbol = 'b'
elif get_key_signature(key) > 0:
symbol = '#'
raw_tonic_index = base_scale.index(key.upper()[0])
for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7):
if note in altered_notes:
result.append('%s%s' % (note, symbol))
else:
result.append(note)
# Save result to cache
_key_cache[key] = result
return result
|
python
|
def get_notes(key='C'):
if _key_cache.has_key(key):
return _key_cache[key]
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
result = []
altered_notes = map(operator.itemgetter(0),
get_key_signature_accidentals(key))
if get_key_signature(key) < 0:
symbol = 'b'
elif get_key_signature(key) > 0:
symbol = '
raw_tonic_index = base_scale.index(key.upper()[0])
for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7):
if note in altered_notes:
result.append('%s%s' % (note, symbol))
else:
result.append(note)
_key_cache[key] = result
return result
|
[
"def",
"get_notes",
"(",
"key",
"=",
"'C'",
")",
":",
"if",
"_key_cache",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"_key_cache",
"[",
"key",
"]",
"if",
"not",
"is_valid_key",
"(",
"key",
")",
":",
"raise",
"NoteFormatError",
"(",
"\"unrecognized format for key '%s'\"",
"%",
"key",
")",
"result",
"=",
"[",
"]",
"# Calculate notes",
"altered_notes",
"=",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"0",
")",
",",
"get_key_signature_accidentals",
"(",
"key",
")",
")",
"if",
"get_key_signature",
"(",
"key",
")",
"<",
"0",
":",
"symbol",
"=",
"'b'",
"elif",
"get_key_signature",
"(",
"key",
")",
">",
"0",
":",
"symbol",
"=",
"'#'",
"raw_tonic_index",
"=",
"base_scale",
".",
"index",
"(",
"key",
".",
"upper",
"(",
")",
"[",
"0",
"]",
")",
"for",
"note",
"in",
"islice",
"(",
"cycle",
"(",
"base_scale",
")",
",",
"raw_tonic_index",
",",
"raw_tonic_index",
"+",
"7",
")",
":",
"if",
"note",
"in",
"altered_notes",
":",
"result",
".",
"append",
"(",
"'%s%s'",
"%",
"(",
"note",
",",
"symbol",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"note",
")",
"# Save result to cache",
"_key_cache",
"[",
"key",
"]",
"=",
"result",
"return",
"result"
] |
Return an ordered list of the notes in this natural key.
Examples:
>>> get_notes('F')
['F', 'G', 'A', 'Bb', 'C', 'D', 'E']
>>> get_notes('c')
['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']
|
[
"Return",
"an",
"ordered",
"list",
"of",
"the",
"notes",
"in",
"this",
"natural",
"key",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L100-L134
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.attach
|
def attach(self, listener):
"""Attach an object that should be notified of events.
The object should have a notify(msg_type, param_dict) function.
"""
if listener not in self.listeners:
self.listeners.append(listener)
|
python
|
def attach(self, listener):
if listener not in self.listeners:
self.listeners.append(listener)
|
[
"def",
"attach",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"not",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
".",
"append",
"(",
"listener",
")"
] |
Attach an object that should be notified of events.
The object should have a notify(msg_type, param_dict) function.
|
[
"Attach",
"an",
"object",
"that",
"should",
"be",
"notified",
"of",
"events",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L90-L96
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.detach
|
def detach(self, listener):
"""Detach a listening object so that it won't receive any events
anymore."""
if listener in self.listeners:
self.listeners.remove(listener)
|
python
|
def detach(self, listener):
if listener in self.listeners:
self.listeners.remove(listener)
|
[
"def",
"detach",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
".",
"remove",
"(",
"listener",
")"
] |
Detach a listening object so that it won't receive any events
anymore.
|
[
"Detach",
"a",
"listening",
"object",
"so",
"that",
"it",
"won",
"t",
"receive",
"any",
"events",
"anymore",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L98-L102
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.notify_listeners
|
def notify_listeners(self, msg_type, params):
"""Send a message to all the observers."""
for c in self.listeners:
c.notify(msg_type, params)
|
python
|
def notify_listeners(self, msg_type, params):
for c in self.listeners:
c.notify(msg_type, params)
|
[
"def",
"notify_listeners",
"(",
"self",
",",
"msg_type",
",",
"params",
")",
":",
"for",
"c",
"in",
"self",
".",
"listeners",
":",
"c",
".",
"notify",
"(",
"msg_type",
",",
"params",
")"
] |
Send a message to all the observers.
|
[
"Send",
"a",
"message",
"to",
"all",
"the",
"observers",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L104-L107
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.set_instrument
|
def set_instrument(self, channel, instr, bank=0):
"""Set the channel to the instrument _instr_."""
self.instr_event(channel, instr, bank)
self.notify_listeners(self.MSG_INSTR, {'channel': int(channel),
'instr': int(instr), 'bank': int(bank)})
|
python
|
def set_instrument(self, channel, instr, bank=0):
self.instr_event(channel, instr, bank)
self.notify_listeners(self.MSG_INSTR, {'channel': int(channel),
'instr': int(instr), 'bank': int(bank)})
|
[
"def",
"set_instrument",
"(",
"self",
",",
"channel",
",",
"instr",
",",
"bank",
"=",
"0",
")",
":",
"self",
".",
"instr_event",
"(",
"channel",
",",
"instr",
",",
"bank",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_INSTR",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'instr'",
":",
"int",
"(",
"instr",
")",
",",
"'bank'",
":",
"int",
"(",
"bank",
")",
"}",
")"
] |
Set the channel to the instrument _instr_.
|
[
"Set",
"the",
"channel",
"to",
"the",
"instrument",
"_instr_",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L109-L113
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.control_change
|
def control_change(self, channel, control, value):
"""Send a control change message.
See the MIDI specification for more information.
"""
if control < 0 or control > 128:
return False
if value < 0 or value > 128:
return False
self.cc_event(channel, control, value)
self.notify_listeners(self.MSG_CC, {'channel': int(channel),
'control': int(control), 'value': int(value)})
return True
|
python
|
def control_change(self, channel, control, value):
if control < 0 or control > 128:
return False
if value < 0 or value > 128:
return False
self.cc_event(channel, control, value)
self.notify_listeners(self.MSG_CC, {'channel': int(channel),
'control': int(control), 'value': int(value)})
return True
|
[
"def",
"control_change",
"(",
"self",
",",
"channel",
",",
"control",
",",
"value",
")",
":",
"if",
"control",
"<",
"0",
"or",
"control",
">",
"128",
":",
"return",
"False",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"128",
":",
"return",
"False",
"self",
".",
"cc_event",
"(",
"channel",
",",
"control",
",",
"value",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_CC",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'control'",
":",
"int",
"(",
"control",
")",
",",
"'value'",
":",
"int",
"(",
"value",
")",
"}",
")",
"return",
"True"
] |
Send a control change message.
See the MIDI specification for more information.
|
[
"Send",
"a",
"control",
"change",
"message",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L115-L127
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Note
|
def play_Note(self, note, channel=1, velocity=100):
"""Play a Note object on a channel with a velocity[0-127].
You can either specify the velocity and channel here as arguments or
you can set the Note.velocity and Note.channel attributes, which
will take presedence over the function arguments.
"""
if hasattr(note, 'velocity'):
velocity = note.velocity
if hasattr(note, 'channel'):
channel = note.channel
self.play_event(int(note) + 12, int(channel), int(velocity))
self.notify_listeners(self.MSG_PLAY_INT, {'channel': int(channel),
'note': int(note) + 12, 'velocity': int(velocity)})
self.notify_listeners(self.MSG_PLAY_NOTE, {'channel': int(channel),
'note': note, 'velocity': int(velocity)})
return True
|
python
|
def play_Note(self, note, channel=1, velocity=100):
if hasattr(note, 'velocity'):
velocity = note.velocity
if hasattr(note, 'channel'):
channel = note.channel
self.play_event(int(note) + 12, int(channel), int(velocity))
self.notify_listeners(self.MSG_PLAY_INT, {'channel': int(channel),
'note': int(note) + 12, 'velocity': int(velocity)})
self.notify_listeners(self.MSG_PLAY_NOTE, {'channel': int(channel),
'note': note, 'velocity': int(velocity)})
return True
|
[
"def",
"play_Note",
"(",
"self",
",",
"note",
",",
"channel",
"=",
"1",
",",
"velocity",
"=",
"100",
")",
":",
"if",
"hasattr",
"(",
"note",
",",
"'velocity'",
")",
":",
"velocity",
"=",
"note",
".",
"velocity",
"if",
"hasattr",
"(",
"note",
",",
"'channel'",
")",
":",
"channel",
"=",
"note",
".",
"channel",
"self",
".",
"play_event",
"(",
"int",
"(",
"note",
")",
"+",
"12",
",",
"int",
"(",
"channel",
")",
",",
"int",
"(",
"velocity",
")",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_INT",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"int",
"(",
"note",
")",
"+",
"12",
",",
"'velocity'",
":",
"int",
"(",
"velocity",
")",
"}",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_NOTE",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"note",
",",
"'velocity'",
":",
"int",
"(",
"velocity",
")",
"}",
")",
"return",
"True"
] |
Play a Note object on a channel with a velocity[0-127].
You can either specify the velocity and channel here as arguments or
you can set the Note.velocity and Note.channel attributes, which
will take presedence over the function arguments.
|
[
"Play",
"a",
"Note",
"object",
"on",
"a",
"channel",
"with",
"a",
"velocity",
"[",
"0",
"-",
"127",
"]",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L129-L145
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.stop_Note
|
def stop_Note(self, note, channel=1):
"""Stop a note on a channel.
If Note.channel is set, it will take presedence over the channel
argument given here.
"""
if hasattr(note, 'channel'):
channel = note.channel
self.stop_event(int(note) + 12, int(channel))
self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel),
'note': int(note) + 12})
self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel),
'note': note})
return True
|
python
|
def stop_Note(self, note, channel=1):
if hasattr(note, 'channel'):
channel = note.channel
self.stop_event(int(note) + 12, int(channel))
self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel),
'note': int(note) + 12})
self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel),
'note': note})
return True
|
[
"def",
"stop_Note",
"(",
"self",
",",
"note",
",",
"channel",
"=",
"1",
")",
":",
"if",
"hasattr",
"(",
"note",
",",
"'channel'",
")",
":",
"channel",
"=",
"note",
".",
"channel",
"self",
".",
"stop_event",
"(",
"int",
"(",
"note",
")",
"+",
"12",
",",
"int",
"(",
"channel",
")",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_STOP_INT",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"int",
"(",
"note",
")",
"+",
"12",
"}",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_STOP_NOTE",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"note",
"}",
")",
"return",
"True"
] |
Stop a note on a channel.
If Note.channel is set, it will take presedence over the channel
argument given here.
|
[
"Stop",
"a",
"note",
"on",
"a",
"channel",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L147-L160
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.stop_everything
|
def stop_everything(self):
"""Stop all the notes on all channels."""
for x in range(118):
for c in range(16):
self.stop_Note(x, c)
|
python
|
def stop_everything(self):
for x in range(118):
for c in range(16):
self.stop_Note(x, c)
|
[
"def",
"stop_everything",
"(",
"self",
")",
":",
"for",
"x",
"in",
"range",
"(",
"118",
")",
":",
"for",
"c",
"in",
"range",
"(",
"16",
")",
":",
"self",
".",
"stop_Note",
"(",
"x",
",",
"c",
")"
] |
Stop all the notes on all channels.
|
[
"Stop",
"all",
"the",
"notes",
"on",
"all",
"channels",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L162-L166
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_NoteContainer
|
def play_NoteContainer(self, nc, channel=1, velocity=100):
"""Play the Notes in the NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel, 'velocity': velocity})
if nc is None:
return True
for note in nc:
if not self.play_Note(note, channel, velocity):
return False
return True
|
python
|
def play_NoteContainer(self, nc, channel=1, velocity=100):
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel, 'velocity': velocity})
if nc is None:
return True
for note in nc:
if not self.play_Note(note, channel, velocity):
return False
return True
|
[
"def",
"play_NoteContainer",
"(",
"self",
",",
"nc",
",",
"channel",
"=",
"1",
",",
"velocity",
"=",
"100",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_NC",
",",
"{",
"'notes'",
":",
"nc",
",",
"'channel'",
":",
"channel",
",",
"'velocity'",
":",
"velocity",
"}",
")",
"if",
"nc",
"is",
"None",
":",
"return",
"True",
"for",
"note",
"in",
"nc",
":",
"if",
"not",
"self",
".",
"play_Note",
"(",
"note",
",",
"channel",
",",
"velocity",
")",
":",
"return",
"False",
"return",
"True"
] |
Play the Notes in the NoteContainer nc.
|
[
"Play",
"the",
"Notes",
"in",
"the",
"NoteContainer",
"nc",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L168-L177
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.stop_NoteContainer
|
def stop_NoteContainer(self, nc, channel=1):
"""Stop playing the notes in NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel})
if nc is None:
return True
for note in nc:
if not self.stop_Note(note, channel):
return False
return True
|
python
|
def stop_NoteContainer(self, nc, channel=1):
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel})
if nc is None:
return True
for note in nc:
if not self.stop_Note(note, channel):
return False
return True
|
[
"def",
"stop_NoteContainer",
"(",
"self",
",",
"nc",
",",
"channel",
"=",
"1",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_NC",
",",
"{",
"'notes'",
":",
"nc",
",",
"'channel'",
":",
"channel",
"}",
")",
"if",
"nc",
"is",
"None",
":",
"return",
"True",
"for",
"note",
"in",
"nc",
":",
"if",
"not",
"self",
".",
"stop_Note",
"(",
"note",
",",
"channel",
")",
":",
"return",
"False",
"return",
"True"
] |
Stop playing the notes in NoteContainer nc.
|
[
"Stop",
"playing",
"the",
"notes",
"in",
"NoteContainer",
"nc",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L179-L188
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Bar
|
def play_Bar(self, bar, channel=1, bpm=120):
"""Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer.
"""
self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel'
: channel, 'bpm': bpm})
# length of a quarter note
qn_length = 60.0 / bpm
for nc in bar:
if not self.play_NoteContainer(nc[2], channel, 100):
return {}
# Change the quarter note length if the NoteContainer has a bpm
# attribute
if hasattr(nc[2], 'bpm'):
bpm = nc[2].bpm
qn_length = 60.0 / bpm
ms = qn_length * (4.0 / nc[1])
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
self.stop_NoteContainer(nc[2], channel)
return {'bpm': bpm}
|
python
|
def play_Bar(self, bar, channel=1, bpm=120):
self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel'
: channel, 'bpm': bpm})
qn_length = 60.0 / bpm
for nc in bar:
if not self.play_NoteContainer(nc[2], channel, 100):
return {}
if hasattr(nc[2], 'bpm'):
bpm = nc[2].bpm
qn_length = 60.0 / bpm
ms = qn_length * (4.0 / nc[1])
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
self.stop_NoteContainer(nc[2], channel)
return {'bpm': bpm}
|
[
"def",
"play_Bar",
"(",
"self",
",",
"bar",
",",
"channel",
"=",
"1",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_BAR",
",",
"{",
"'bar'",
":",
"bar",
",",
"'channel'",
":",
"channel",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"# length of a quarter note",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"for",
"nc",
"in",
"bar",
":",
"if",
"not",
"self",
".",
"play_NoteContainer",
"(",
"nc",
"[",
"2",
"]",
",",
"channel",
",",
"100",
")",
":",
"return",
"{",
"}",
"# Change the quarter note length if the NoteContainer has a bpm",
"# attribute",
"if",
"hasattr",
"(",
"nc",
"[",
"2",
"]",
",",
"'bpm'",
")",
":",
"bpm",
"=",
"nc",
"[",
"2",
"]",
".",
"bpm",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"ms",
"=",
"qn_length",
"*",
"(",
"4.0",
"/",
"nc",
"[",
"1",
"]",
")",
"self",
".",
"sleep",
"(",
"ms",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_SLEEP",
",",
"{",
"'s'",
":",
"ms",
"}",
")",
"self",
".",
"stop_NoteContainer",
"(",
"nc",
"[",
"2",
"]",
",",
"channel",
")",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] |
Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer.
|
[
"Play",
"a",
"Bar",
"object",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L190-L217
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Bars
|
def play_Bars(self, bars, channels, bpm=120):
"""Play several bars (a list of Bar objects) at the same time.
A list of channels should also be provided. The tempo can be changed
by providing one or more of the NoteContainers with a bpm argument.
"""
self.notify_listeners(self.MSG_PLAY_BARS, {'bars': bars,
'channels': channels, 'bpm': bpm})
qn_length = 60.0 / bpm # length of a quarter note
tick = 0.0 # place in beat from 0.0 to bar.length
cur = [0] * len(bars) # keeps the index of the NoteContainer under
# investigation in each of the bars
playing = [] # The NoteContainers being played.
while tick < bars[0].length:
# Prepare a and play a list of NoteContainers that are ready for it.
# The list `playing_new` holds both the duration and the
# NoteContainer.
playing_new = []
for (n, x) in enumerate(cur):
(start_tick, note_length, nc) = bars[n][x]
if start_tick <= tick:
self.play_NoteContainer(nc, channels[n])
playing_new.append([note_length, n])
playing.append([note_length, nc, channels[n], n])
# Change the length of a quarter note if the NoteContainer
# has a bpm attribute
if hasattr(nc, 'bpm'):
bpm = nc.bpm
qn_length = 60.0 / bpm
# Sort the list and sleep for the shortest duration
if len(playing_new) != 0:
playing_new.sort()
shortest = playing_new[-1][0]
ms = qn_length * (4.0 / shortest)
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
else:
# If somehow, playing_new doesn't contain any notes (something
# that shouldn't happen when the bar was filled properly), we
# make sure that at least the notes that are still playing get
# handled correctly.
if len(playing) != 0:
playing.sort()
shortest = playing[-1][0]
ms = qn_length * (4.0 / shortest)
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
else:
# warning: this could lead to some strange behaviour. OTOH.
# Leaving gaps is not the way Bar works. should we do an
# integrity check on bars first?
return {}
# Add shortest interval to tick
tick += 1.0 / shortest
# This final piece adjusts the duration in `playing` and checks if a
# NoteContainer should be stopped.
new_playing = []
for (length, nc, chan, n) in playing:
duration = 1.0 / length - 1.0 / shortest
if duration >= 0.00001:
new_playing.append([1.0 / duration, nc, chan, n])
else:
self.stop_NoteContainer(nc, chan)
if cur[n] < len(bars[n]) - 1:
cur[n] += 1
playing = new_playing
for p in playing:
self.stop_NoteContainer(p[1], p[2])
playing.remove(p)
return {'bpm': bpm}
|
python
|
def play_Bars(self, bars, channels, bpm=120):
self.notify_listeners(self.MSG_PLAY_BARS, {'bars': bars,
'channels': channels, 'bpm': bpm})
qn_length = 60.0 / bpm
tick = 0.0
cur = [0] * len(bars)
playing = []
while tick < bars[0].length:
playing_new = []
for (n, x) in enumerate(cur):
(start_tick, note_length, nc) = bars[n][x]
if start_tick <= tick:
self.play_NoteContainer(nc, channels[n])
playing_new.append([note_length, n])
playing.append([note_length, nc, channels[n], n])
if hasattr(nc, 'bpm'):
bpm = nc.bpm
qn_length = 60.0 / bpm
if len(playing_new) != 0:
playing_new.sort()
shortest = playing_new[-1][0]
ms = qn_length * (4.0 / shortest)
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
else:
if len(playing) != 0:
playing.sort()
shortest = playing[-1][0]
ms = qn_length * (4.0 / shortest)
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
else:
return {}
tick += 1.0 / shortest
new_playing = []
for (length, nc, chan, n) in playing:
duration = 1.0 / length - 1.0 / shortest
if duration >= 0.00001:
new_playing.append([1.0 / duration, nc, chan, n])
else:
self.stop_NoteContainer(nc, chan)
if cur[n] < len(bars[n]) - 1:
cur[n] += 1
playing = new_playing
for p in playing:
self.stop_NoteContainer(p[1], p[2])
playing.remove(p)
return {'bpm': bpm}
|
[
"def",
"play_Bars",
"(",
"self",
",",
"bars",
",",
"channels",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_BARS",
",",
"{",
"'bars'",
":",
"bars",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"# length of a quarter note",
"tick",
"=",
"0.0",
"# place in beat from 0.0 to bar.length",
"cur",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"bars",
")",
"# keeps the index of the NoteContainer under",
"# investigation in each of the bars",
"playing",
"=",
"[",
"]",
"# The NoteContainers being played.",
"while",
"tick",
"<",
"bars",
"[",
"0",
"]",
".",
"length",
":",
"# Prepare a and play a list of NoteContainers that are ready for it.",
"# The list `playing_new` holds both the duration and the",
"# NoteContainer.",
"playing_new",
"=",
"[",
"]",
"for",
"(",
"n",
",",
"x",
")",
"in",
"enumerate",
"(",
"cur",
")",
":",
"(",
"start_tick",
",",
"note_length",
",",
"nc",
")",
"=",
"bars",
"[",
"n",
"]",
"[",
"x",
"]",
"if",
"start_tick",
"<=",
"tick",
":",
"self",
".",
"play_NoteContainer",
"(",
"nc",
",",
"channels",
"[",
"n",
"]",
")",
"playing_new",
".",
"append",
"(",
"[",
"note_length",
",",
"n",
"]",
")",
"playing",
".",
"append",
"(",
"[",
"note_length",
",",
"nc",
",",
"channels",
"[",
"n",
"]",
",",
"n",
"]",
")",
"# Change the length of a quarter note if the NoteContainer",
"# has a bpm attribute",
"if",
"hasattr",
"(",
"nc",
",",
"'bpm'",
")",
":",
"bpm",
"=",
"nc",
".",
"bpm",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"# Sort the list and sleep for the shortest duration",
"if",
"len",
"(",
"playing_new",
")",
"!=",
"0",
":",
"playing_new",
".",
"sort",
"(",
")",
"shortest",
"=",
"playing_new",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"ms",
"=",
"qn_length",
"*",
"(",
"4.0",
"/",
"shortest",
")",
"self",
".",
"sleep",
"(",
"ms",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_SLEEP",
",",
"{",
"'s'",
":",
"ms",
"}",
")",
"else",
":",
"# If somehow, playing_new doesn't contain any notes (something",
"# that shouldn't happen when the bar was filled properly), we",
"# make sure that at least the notes that are still playing get",
"# handled correctly.",
"if",
"len",
"(",
"playing",
")",
"!=",
"0",
":",
"playing",
".",
"sort",
"(",
")",
"shortest",
"=",
"playing",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"ms",
"=",
"qn_length",
"*",
"(",
"4.0",
"/",
"shortest",
")",
"self",
".",
"sleep",
"(",
"ms",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_SLEEP",
",",
"{",
"'s'",
":",
"ms",
"}",
")",
"else",
":",
"# warning: this could lead to some strange behaviour. OTOH.",
"# Leaving gaps is not the way Bar works. should we do an",
"# integrity check on bars first?",
"return",
"{",
"}",
"# Add shortest interval to tick",
"tick",
"+=",
"1.0",
"/",
"shortest",
"# This final piece adjusts the duration in `playing` and checks if a",
"# NoteContainer should be stopped.",
"new_playing",
"=",
"[",
"]",
"for",
"(",
"length",
",",
"nc",
",",
"chan",
",",
"n",
")",
"in",
"playing",
":",
"duration",
"=",
"1.0",
"/",
"length",
"-",
"1.0",
"/",
"shortest",
"if",
"duration",
">=",
"0.00001",
":",
"new_playing",
".",
"append",
"(",
"[",
"1.0",
"/",
"duration",
",",
"nc",
",",
"chan",
",",
"n",
"]",
")",
"else",
":",
"self",
".",
"stop_NoteContainer",
"(",
"nc",
",",
"chan",
")",
"if",
"cur",
"[",
"n",
"]",
"<",
"len",
"(",
"bars",
"[",
"n",
"]",
")",
"-",
"1",
":",
"cur",
"[",
"n",
"]",
"+=",
"1",
"playing",
"=",
"new_playing",
"for",
"p",
"in",
"playing",
":",
"self",
".",
"stop_NoteContainer",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"playing",
".",
"remove",
"(",
"p",
")",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] |
Play several bars (a list of Bar objects) at the same time.
A list of channels should also be provided. The tempo can be changed
by providing one or more of the NoteContainers with a bpm argument.
|
[
"Play",
"several",
"bars",
"(",
"a",
"list",
"of",
"Bar",
"objects",
")",
"at",
"the",
"same",
"time",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L219-L294
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Track
|
def play_Track(self, track, channel=1, bpm=120):
"""Play a Track object."""
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel'
: channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
return {'bpm': bpm}
|
python
|
def play_Track(self, track, channel=1, bpm=120):
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel'
: channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
return {'bpm': bpm}
|
[
"def",
"play_Track",
"(",
"self",
",",
"track",
",",
"channel",
"=",
"1",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_TRACK",
",",
"{",
"'track'",
":",
"track",
",",
"'channel'",
":",
"channel",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"for",
"bar",
"in",
"track",
":",
"res",
"=",
"self",
".",
"play_Bar",
"(",
"bar",
",",
"channel",
",",
"bpm",
")",
"if",
"res",
"!=",
"{",
"}",
":",
"bpm",
"=",
"res",
"[",
"'bpm'",
"]",
"else",
":",
"return",
"{",
"}",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] |
Play a Track object.
|
[
"Play",
"a",
"Track",
"object",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L296-L306
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Tracks
|
def play_Tracks(self, tracks, channels, bpm=120):
"""Play a list of Tracks.
If an instance of MidiInstrument is used then the instrument will be
set automatically.
"""
self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks,
'channels': channels, 'bpm': bpm})
# Set the right instruments
for x in range(len(tracks)):
instr = tracks[x].instrument
if isinstance(instr, MidiInstrument):
try:
i = instr.names.index(instr.name)
except:
i = 1
self.set_instrument(channels[x], i)
else:
self.set_instrument(channels[x], 1)
current_bar = 0
max_bar = len(tracks[0])
# Play the bars
while current_bar < max_bar:
playbars = []
for tr in tracks:
playbars.append(tr[current_bar])
res = self.play_Bars(playbars, channels, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
current_bar += 1
return {'bpm': bpm}
|
python
|
def play_Tracks(self, tracks, channels, bpm=120):
self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks,
'channels': channels, 'bpm': bpm})
for x in range(len(tracks)):
instr = tracks[x].instrument
if isinstance(instr, MidiInstrument):
try:
i = instr.names.index(instr.name)
except:
i = 1
self.set_instrument(channels[x], i)
else:
self.set_instrument(channels[x], 1)
current_bar = 0
max_bar = len(tracks[0])
while current_bar < max_bar:
playbars = []
for tr in tracks:
playbars.append(tr[current_bar])
res = self.play_Bars(playbars, channels, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
current_bar += 1
return {'bpm': bpm}
|
[
"def",
"play_Tracks",
"(",
"self",
",",
"tracks",
",",
"channels",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_TRACKS",
",",
"{",
"'tracks'",
":",
"tracks",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"# Set the right instruments",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"tracks",
")",
")",
":",
"instr",
"=",
"tracks",
"[",
"x",
"]",
".",
"instrument",
"if",
"isinstance",
"(",
"instr",
",",
"MidiInstrument",
")",
":",
"try",
":",
"i",
"=",
"instr",
".",
"names",
".",
"index",
"(",
"instr",
".",
"name",
")",
"except",
":",
"i",
"=",
"1",
"self",
".",
"set_instrument",
"(",
"channels",
"[",
"x",
"]",
",",
"i",
")",
"else",
":",
"self",
".",
"set_instrument",
"(",
"channels",
"[",
"x",
"]",
",",
"1",
")",
"current_bar",
"=",
"0",
"max_bar",
"=",
"len",
"(",
"tracks",
"[",
"0",
"]",
")",
"# Play the bars",
"while",
"current_bar",
"<",
"max_bar",
":",
"playbars",
"=",
"[",
"]",
"for",
"tr",
"in",
"tracks",
":",
"playbars",
".",
"append",
"(",
"tr",
"[",
"current_bar",
"]",
")",
"res",
"=",
"self",
".",
"play_Bars",
"(",
"playbars",
",",
"channels",
",",
"bpm",
")",
"if",
"res",
"!=",
"{",
"}",
":",
"bpm",
"=",
"res",
"[",
"'bpm'",
"]",
"else",
":",
"return",
"{",
"}",
"current_bar",
"+=",
"1",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] |
Play a list of Tracks.
If an instance of MidiInstrument is used then the instrument will be
set automatically.
|
[
"Play",
"a",
"list",
"of",
"Tracks",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L308-L342
|
bspaans/python-mingus
|
mingus/midi/sequencer.py
|
Sequencer.play_Composition
|
def play_Composition(self, composition, channels=None, bpm=120):
"""Play a Composition object."""
self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition'
: composition, 'channels': channels, 'bpm': bpm})
if channels == None:
channels = map(lambda x: x + 1, range(len(composition.tracks)))
return self.play_Tracks(composition.tracks, channels, bpm)
|
python
|
def play_Composition(self, composition, channels=None, bpm=120):
self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition'
: composition, 'channels': channels, 'bpm': bpm})
if channels == None:
channels = map(lambda x: x + 1, range(len(composition.tracks)))
return self.play_Tracks(composition.tracks, channels, bpm)
|
[
"def",
"play_Composition",
"(",
"self",
",",
"composition",
",",
"channels",
"=",
"None",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_COMPOSITION",
",",
"{",
"'composition'",
":",
"composition",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"if",
"channels",
"==",
"None",
":",
"channels",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"1",
",",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
")",
"return",
"self",
".",
"play_Tracks",
"(",
"composition",
".",
"tracks",
",",
"channels",
",",
"bpm",
")"
] |
Play a Composition object.
|
[
"Play",
"a",
"Composition",
"object",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L344-L350
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
_find_log_index
|
def _find_log_index(f):
"""Look up the index of the frequency f in the frequency table.
Return the nearest index.
"""
global _last_asked, _log_cache
(begin, end) = (0, 128)
# Most calls are sequential, this keeps track of the last value asked for so
# that we need to search much, much less.
if _last_asked is not None:
(lastn, lastval) = _last_asked
if f >= lastval:
if f <= _log_cache[lastn]:
_last_asked = (lastn, f)
return lastn
elif f <= _log_cache[lastn + 1]:
_last_asked = (lastn + 1, f)
return lastn + 1
begin = lastn
# Do some range checking
if f > _log_cache[127] or f <= 0:
return 128
# Binary search related algorithm to find the index
while begin != end:
n = (begin + end) // 2
c = _log_cache[n]
cp = _log_cache[n - 1] if n != 0 else 0
if cp < f <= c:
_last_asked = (n, f)
return n
if f < c:
end = n
else:
begin = n
_last_asked = (begin, f)
return begin
|
python
|
def _find_log_index(f):
global _last_asked, _log_cache
(begin, end) = (0, 128)
if _last_asked is not None:
(lastn, lastval) = _last_asked
if f >= lastval:
if f <= _log_cache[lastn]:
_last_asked = (lastn, f)
return lastn
elif f <= _log_cache[lastn + 1]:
_last_asked = (lastn + 1, f)
return lastn + 1
begin = lastn
if f > _log_cache[127] or f <= 0:
return 128
while begin != end:
n = (begin + end) // 2
c = _log_cache[n]
cp = _log_cache[n - 1] if n != 0 else 0
if cp < f <= c:
_last_asked = (n, f)
return n
if f < c:
end = n
else:
begin = n
_last_asked = (begin, f)
return begin
|
[
"def",
"_find_log_index",
"(",
"f",
")",
":",
"global",
"_last_asked",
",",
"_log_cache",
"(",
"begin",
",",
"end",
")",
"=",
"(",
"0",
",",
"128",
")",
"# Most calls are sequential, this keeps track of the last value asked for so",
"# that we need to search much, much less.",
"if",
"_last_asked",
"is",
"not",
"None",
":",
"(",
"lastn",
",",
"lastval",
")",
"=",
"_last_asked",
"if",
"f",
">=",
"lastval",
":",
"if",
"f",
"<=",
"_log_cache",
"[",
"lastn",
"]",
":",
"_last_asked",
"=",
"(",
"lastn",
",",
"f",
")",
"return",
"lastn",
"elif",
"f",
"<=",
"_log_cache",
"[",
"lastn",
"+",
"1",
"]",
":",
"_last_asked",
"=",
"(",
"lastn",
"+",
"1",
",",
"f",
")",
"return",
"lastn",
"+",
"1",
"begin",
"=",
"lastn",
"# Do some range checking",
"if",
"f",
">",
"_log_cache",
"[",
"127",
"]",
"or",
"f",
"<=",
"0",
":",
"return",
"128",
"# Binary search related algorithm to find the index",
"while",
"begin",
"!=",
"end",
":",
"n",
"=",
"(",
"begin",
"+",
"end",
")",
"//",
"2",
"c",
"=",
"_log_cache",
"[",
"n",
"]",
"cp",
"=",
"_log_cache",
"[",
"n",
"-",
"1",
"]",
"if",
"n",
"!=",
"0",
"else",
"0",
"if",
"cp",
"<",
"f",
"<=",
"c",
":",
"_last_asked",
"=",
"(",
"n",
",",
"f",
")",
"return",
"n",
"if",
"f",
"<",
"c",
":",
"end",
"=",
"n",
"else",
":",
"begin",
"=",
"n",
"_last_asked",
"=",
"(",
"begin",
",",
"f",
")",
"return",
"begin"
] |
Look up the index of the frequency f in the frequency table.
Return the nearest index.
|
[
"Look",
"up",
"the",
"index",
"of",
"the",
"frequency",
"f",
"in",
"the",
"frequency",
"table",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L45-L83
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
find_frequencies
|
def find_frequencies(data, freq=44100, bits=16):
"""Convert audio data into a frequency-amplitude table using fast fourier
transformation.
Return a list of tuples (frequency, amplitude).
Data should only contain one channel of audio.
"""
# Fast fourier transform
n = len(data)
p = _fft(data)
uniquePts = numpy.ceil((n + 1) / 2.0)
# Scale by the length (n) and square the value to get the amplitude
p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]
p[0] = p[0] / 2
if n % 2 == 0:
p[-1] = p[-1] / 2
# Generate the frequencies and zip with the amplitudes
s = freq / float(n)
freqArray = numpy.arange(0, uniquePts * s, s)
return zip(freqArray, p)
|
python
|
def find_frequencies(data, freq=44100, bits=16):
n = len(data)
p = _fft(data)
uniquePts = numpy.ceil((n + 1) / 2.0)
p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]
p[0] = p[0] / 2
if n % 2 == 0:
p[-1] = p[-1] / 2
s = freq / float(n)
freqArray = numpy.arange(0, uniquePts * s, s)
return zip(freqArray, p)
|
[
"def",
"find_frequencies",
"(",
"data",
",",
"freq",
"=",
"44100",
",",
"bits",
"=",
"16",
")",
":",
"# Fast fourier transform",
"n",
"=",
"len",
"(",
"data",
")",
"p",
"=",
"_fft",
"(",
"data",
")",
"uniquePts",
"=",
"numpy",
".",
"ceil",
"(",
"(",
"n",
"+",
"1",
")",
"/",
"2.0",
")",
"# Scale by the length (n) and square the value to get the amplitude",
"p",
"=",
"[",
"(",
"abs",
"(",
"x",
")",
"/",
"float",
"(",
"n",
")",
")",
"**",
"2",
"*",
"2",
"for",
"x",
"in",
"p",
"[",
"0",
":",
"uniquePts",
"]",
"]",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"0",
"]",
"/",
"2",
"if",
"n",
"%",
"2",
"==",
"0",
":",
"p",
"[",
"-",
"1",
"]",
"=",
"p",
"[",
"-",
"1",
"]",
"/",
"2",
"# Generate the frequencies and zip with the amplitudes",
"s",
"=",
"freq",
"/",
"float",
"(",
"n",
")",
"freqArray",
"=",
"numpy",
".",
"arange",
"(",
"0",
",",
"uniquePts",
"*",
"s",
",",
"s",
")",
"return",
"zip",
"(",
"freqArray",
",",
"p",
")"
] |
Convert audio data into a frequency-amplitude table using fast fourier
transformation.
Return a list of tuples (frequency, amplitude).
Data should only contain one channel of audio.
|
[
"Convert",
"audio",
"data",
"into",
"a",
"frequency",
"-",
"amplitude",
"table",
"using",
"fast",
"fourier",
"transformation",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L85-L107
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
find_notes
|
def find_notes(freqTable, maxNote=100):
"""Convert the (frequencies, amplitude) list to a (Note, amplitude) list."""
res = [0] * 129
n = Note()
for (freq, ampl) in freqTable:
if freq > 0 and ampl > 0:
f = _find_log_index(freq)
if f < maxNote:
res[f] += ampl
else:
res[128] += ampl
return [(Note().from_int(x) if x < 128 else None, n) for (x, n) in
enumerate(res)]
|
python
|
def find_notes(freqTable, maxNote=100):
res = [0] * 129
n = Note()
for (freq, ampl) in freqTable:
if freq > 0 and ampl > 0:
f = _find_log_index(freq)
if f < maxNote:
res[f] += ampl
else:
res[128] += ampl
return [(Note().from_int(x) if x < 128 else None, n) for (x, n) in
enumerate(res)]
|
[
"def",
"find_notes",
"(",
"freqTable",
",",
"maxNote",
"=",
"100",
")",
":",
"res",
"=",
"[",
"0",
"]",
"*",
"129",
"n",
"=",
"Note",
"(",
")",
"for",
"(",
"freq",
",",
"ampl",
")",
"in",
"freqTable",
":",
"if",
"freq",
">",
"0",
"and",
"ampl",
">",
"0",
":",
"f",
"=",
"_find_log_index",
"(",
"freq",
")",
"if",
"f",
"<",
"maxNote",
":",
"res",
"[",
"f",
"]",
"+=",
"ampl",
"else",
":",
"res",
"[",
"128",
"]",
"+=",
"ampl",
"return",
"[",
"(",
"Note",
"(",
")",
".",
"from_int",
"(",
"x",
")",
"if",
"x",
"<",
"128",
"else",
"None",
",",
"n",
")",
"for",
"(",
"x",
",",
"n",
")",
"in",
"enumerate",
"(",
"res",
")",
"]"
] |
Convert the (frequencies, amplitude) list to a (Note, amplitude) list.
|
[
"Convert",
"the",
"(",
"frequencies",
"amplitude",
")",
"list",
"to",
"a",
"(",
"Note",
"amplitude",
")",
"list",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L109-L121
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
data_from_file
|
def data_from_file(file):
"""Return (first channel data, sample frequency, sample width) from a .wav
file."""
fp = wave.open(file, 'r')
data = fp.readframes(fp.getnframes())
channels = fp.getnchannels()
freq = fp.getframerate()
bits = fp.getsampwidth()
# Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32
# bit not supported.
data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)
# Only use first channel
channel1 = []
n = 0
for d in data:
if n % channels == 0:
channel1.append(d)
n += 1
fp.close()
return (channel1, freq, bits)
|
python
|
def data_from_file(file):
fp = wave.open(file, 'r')
data = fp.readframes(fp.getnframes())
channels = fp.getnchannels()
freq = fp.getframerate()
bits = fp.getsampwidth()
data = struct.unpack(('%sh' % fp.getnframes()) * channels, data)
channel1 = []
n = 0
for d in data:
if n % channels == 0:
channel1.append(d)
n += 1
fp.close()
return (channel1, freq, bits)
|
[
"def",
"data_from_file",
"(",
"file",
")",
":",
"fp",
"=",
"wave",
".",
"open",
"(",
"file",
",",
"'r'",
")",
"data",
"=",
"fp",
".",
"readframes",
"(",
"fp",
".",
"getnframes",
"(",
")",
")",
"channels",
"=",
"fp",
".",
"getnchannels",
"(",
")",
"freq",
"=",
"fp",
".",
"getframerate",
"(",
")",
"bits",
"=",
"fp",
".",
"getsampwidth",
"(",
")",
"# Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32",
"# bit not supported.",
"data",
"=",
"struct",
".",
"unpack",
"(",
"(",
"'%sh'",
"%",
"fp",
".",
"getnframes",
"(",
")",
")",
"*",
"channels",
",",
"data",
")",
"# Only use first channel",
"channel1",
"=",
"[",
"]",
"n",
"=",
"0",
"for",
"d",
"in",
"data",
":",
"if",
"n",
"%",
"channels",
"==",
"0",
":",
"channel1",
".",
"append",
"(",
"d",
")",
"n",
"+=",
"1",
"fp",
".",
"close",
"(",
")",
"return",
"(",
"channel1",
",",
"freq",
",",
"bits",
")"
] |
Return (first channel data, sample frequency, sample width) from a .wav
file.
|
[
"Return",
"(",
"first",
"channel",
"data",
"sample",
"frequency",
"sample",
"width",
")",
"from",
"a",
".",
"wav",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L123-L144
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
find_Note
|
def find_Note(data, freq, bits):
"""Get the frequencies, feed them to find_notes and the return the Note
with the highest amplitude."""
data = find_frequencies(data, freq, bits)
return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0]
|
python
|
def find_Note(data, freq, bits):
data = find_frequencies(data, freq, bits)
return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0]
|
[
"def",
"find_Note",
"(",
"data",
",",
"freq",
",",
"bits",
")",
":",
"data",
"=",
"find_frequencies",
"(",
"data",
",",
"freq",
",",
"bits",
")",
"return",
"sorted",
"(",
"find_notes",
"(",
"data",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]"
] |
Get the frequencies, feed them to find_notes and the return the Note
with the highest amplitude.
|
[
"Get",
"the",
"frequencies",
"feed",
"them",
"to",
"find_notes",
"and",
"the",
"return",
"the",
"Note",
"with",
"the",
"highest",
"amplitude",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L146-L150
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
analyze_chunks
|
def analyze_chunks(data, freq, bits, chunksize=512):
"""Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest.
"""
res = []
while data != []:
f = find_frequencies(data[:chunksize], freq, bits)
res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0])
data = data[chunksize:]
return res
|
python
|
def analyze_chunks(data, freq, bits, chunksize=512):
res = []
while data != []:
f = find_frequencies(data[:chunksize], freq, bits)
res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0])
data = data[chunksize:]
return res
|
[
"def",
"analyze_chunks",
"(",
"data",
",",
"freq",
",",
"bits",
",",
"chunksize",
"=",
"512",
")",
":",
"res",
"=",
"[",
"]",
"while",
"data",
"!=",
"[",
"]",
":",
"f",
"=",
"find_frequencies",
"(",
"data",
"[",
":",
"chunksize",
"]",
",",
"freq",
",",
"bits",
")",
"res",
".",
"append",
"(",
"sorted",
"(",
"find_notes",
"(",
"f",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"data",
"=",
"data",
"[",
"chunksize",
":",
"]",
"return",
"res"
] |
Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest.
|
[
"Cut",
"the",
"one",
"channel",
"data",
"in",
"chunks",
"and",
"analyzes",
"them",
"separately",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L152-L162
|
bspaans/python-mingus
|
mingus/extra/fft.py
|
find_melody
|
def find_melody(file='440_480_clean.wav', chunksize=512):
"""Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped together.
This is an experimental function.
"""
(data, freq, bits) = data_from_file(file)
res = []
for d in analyze_chunks(data, freq, bits, chunksize):
if res != []:
if res[-1][0] == d:
val = res[-1][1]
res[-1] = (d, val + 1)
else:
res.append((d, 1))
else:
res.append((d, 1))
return [(x, freq) for (x, freq) in res]
|
python
|
def find_melody(file='440_480_clean.wav', chunksize=512):
(data, freq, bits) = data_from_file(file)
res = []
for d in analyze_chunks(data, freq, bits, chunksize):
if res != []:
if res[-1][0] == d:
val = res[-1][1]
res[-1] = (d, val + 1)
else:
res.append((d, 1))
else:
res.append((d, 1))
return [(x, freq) for (x, freq) in res]
|
[
"def",
"find_melody",
"(",
"file",
"=",
"'440_480_clean.wav'",
",",
"chunksize",
"=",
"512",
")",
":",
"(",
"data",
",",
"freq",
",",
"bits",
")",
"=",
"data_from_file",
"(",
"file",
")",
"res",
"=",
"[",
"]",
"for",
"d",
"in",
"analyze_chunks",
"(",
"data",
",",
"freq",
",",
"bits",
",",
"chunksize",
")",
":",
"if",
"res",
"!=",
"[",
"]",
":",
"if",
"res",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"d",
":",
"val",
"=",
"res",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"res",
"[",
"-",
"1",
"]",
"=",
"(",
"d",
",",
"val",
"+",
"1",
")",
"else",
":",
"res",
".",
"append",
"(",
"(",
"d",
",",
"1",
")",
")",
"else",
":",
"res",
".",
"append",
"(",
"(",
"d",
",",
"1",
")",
")",
"return",
"[",
"(",
"x",
",",
"freq",
")",
"for",
"(",
"x",
",",
"freq",
")",
"in",
"res",
"]"
] |
Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped together.
This is an experimental function.
|
[
"Cut",
"the",
"sample",
"into",
"chunks",
"and",
"analyze",
"each",
"chunk",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L164-L186
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
write_Note
|
def write_Note(file, note, bpm=120, repeat=0, verbose=False):
"""Expect a Note object from mingus.containers and save it into a MIDI
file, specified in file.
You can set the velocity and channel in Note.velocity and Note.channel.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_Note(note)
t.set_deltatime("\x48")
t.stop_Note(note)
repeat -= 1
return m.write_file(file, verbose)
|
python
|
def write_Note(file, note, bpm=120, repeat=0, verbose=False):
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_Note(note)
t.set_deltatime("\x48")
t.stop_Note(note)
repeat -= 1
return m.write_file(file, verbose)
|
[
"def",
"write_Note",
"(",
"file",
",",
"note",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"set_deltatime",
"(",
"'\\x00'",
")",
"t",
".",
"play_Note",
"(",
"note",
")",
"t",
".",
"set_deltatime",
"(",
"\"\\x48\"",
")",
"t",
".",
"stop_Note",
"(",
"note",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] |
Expect a Note object from mingus.containers and save it into a MIDI
file, specified in file.
You can set the velocity and channel in Note.velocity and Note.channel.
|
[
"Expect",
"a",
"Note",
"object",
"from",
"mingus",
".",
"containers",
"and",
"save",
"it",
"into",
"a",
"MIDI",
"file",
"specified",
"in",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L71-L86
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
write_NoteContainer
|
def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False):
"""Write a mingus.NoteContainer to a MIDI file."""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_NoteContainer(notecontainer)
t.set_deltatime("\x48")
t.stop_NoteContainer(notecontainer)
repeat -= 1
return m.write_file(file, verbose)
|
python
|
def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False):
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_NoteContainer(notecontainer)
t.set_deltatime("\x48")
t.stop_NoteContainer(notecontainer)
repeat -= 1
return m.write_file(file, verbose)
|
[
"def",
"write_NoteContainer",
"(",
"file",
",",
"notecontainer",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"set_deltatime",
"(",
"'\\x00'",
")",
"t",
".",
"play_NoteContainer",
"(",
"notecontainer",
")",
"t",
".",
"set_deltatime",
"(",
"\"\\x48\"",
")",
"t",
".",
"stop_NoteContainer",
"(",
"notecontainer",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] |
Write a mingus.NoteContainer to a MIDI file.
|
[
"Write",
"a",
"mingus",
".",
"NoteContainer",
"to",
"a",
"MIDI",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L88-L99
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
write_Bar
|
def write_Bar(file, bar, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Bar to a MIDI file.
Both the key and the meter are written to the file as well.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Bar(bar)
repeat -= 1
return m.write_file(file, verbose)
|
python
|
def write_Bar(file, bar, bpm=120, repeat=0, verbose=False):
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Bar(bar)
repeat -= 1
return m.write_file(file, verbose)
|
[
"def",
"write_Bar",
"(",
"file",
",",
"bar",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"play_Bar",
"(",
"bar",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] |
Write a mingus.Bar to a MIDI file.
Both the key and the meter are written to the file as well.
|
[
"Write",
"a",
"mingus",
".",
"Bar",
"to",
"a",
"MIDI",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L101-L112
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
write_Track
|
def write_Track(file, track, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrument has
this attribute by default.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Track(track)
repeat -= 1
return m.write_file(file, verbose)
|
python
|
def write_Track(file, track, bpm=120, repeat=0, verbose=False):
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Track(track)
repeat -= 1
return m.write_file(file, verbose)
|
[
"def",
"write_Track",
"(",
"file",
",",
"track",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"play_Track",
"(",
"track",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] |
Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrument has
this attribute by default.
|
[
"Write",
"a",
"mingus",
".",
"Track",
"to",
"a",
"MIDI",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L114-L128
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
write_Composition
|
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Composition to a MIDI file."""
m = MidiFile()
t = []
for x in range(len(composition.tracks)):
t += [MidiTrack(bpm)]
m.tracks = t
while repeat >= 0:
for i in range(len(composition.tracks)):
m.tracks[i].play_Track(composition.tracks[i])
repeat -= 1
return m.write_file(file, verbose)
|
python
|
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
m = MidiFile()
t = []
for x in range(len(composition.tracks)):
t += [MidiTrack(bpm)]
m.tracks = t
while repeat >= 0:
for i in range(len(composition.tracks)):
m.tracks[i].play_Track(composition.tracks[i])
repeat -= 1
return m.write_file(file, verbose)
|
[
"def",
"write_Composition",
"(",
"file",
",",
"composition",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
":",
"t",
"+=",
"[",
"MidiTrack",
"(",
"bpm",
")",
"]",
"m",
".",
"tracks",
"=",
"t",
"while",
"repeat",
">=",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
":",
"m",
".",
"tracks",
"[",
"i",
"]",
".",
"play_Track",
"(",
"composition",
".",
"tracks",
"[",
"i",
"]",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] |
Write a mingus.Composition to a MIDI file.
|
[
"Write",
"a",
"mingus",
".",
"Composition",
"to",
"a",
"MIDI",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L130-L141
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
MidiFile.get_midi_data
|
def get_midi_data(self):
"""Collect and return the raw, binary MIDI data from the tracks."""
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks)
|
python
|
def get_midi_data(self):
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks)
|
[
"def",
"get_midi_data",
"(",
"self",
")",
":",
"tracks",
"=",
"[",
"t",
".",
"get_midi_data",
"(",
")",
"for",
"t",
"in",
"self",
".",
"tracks",
"if",
"t",
".",
"track_data",
"!=",
"''",
"]",
"return",
"self",
".",
"header",
"(",
")",
"+",
"''",
".",
"join",
"(",
"tracks",
")"
] |
Collect and return the raw, binary MIDI data from the tracks.
|
[
"Collect",
"and",
"return",
"the",
"raw",
"binary",
"MIDI",
"data",
"from",
"the",
"tracks",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L37-L40
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
MidiFile.header
|
def header(self):
"""Return a header for type 1 MIDI file."""
tracks = a2b_hex('%04x' % len([t for t in self.tracks if
t.track_data != '']))
return 'MThd\x00\x00\x00\x06\x00\x01' + tracks + self.time_division
|
python
|
def header(self):
tracks = a2b_hex('%04x' % len([t for t in self.tracks if
t.track_data != '']))
return 'MThd\x00\x00\x00\x06\x00\x01' + tracks + self.time_division
|
[
"def",
"header",
"(",
"self",
")",
":",
"tracks",
"=",
"a2b_hex",
"(",
"'%04x'",
"%",
"len",
"(",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"tracks",
"if",
"t",
".",
"track_data",
"!=",
"''",
"]",
")",
")",
"return",
"'MThd\\x00\\x00\\x00\\x06\\x00\\x01'",
"+",
"tracks",
"+",
"self",
".",
"time_division"
] |
Return a header for type 1 MIDI file.
|
[
"Return",
"a",
"header",
"for",
"type",
"1",
"MIDI",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L42-L46
|
bspaans/python-mingus
|
mingus/midi/midi_file_out.py
|
MidiFile.write_file
|
def write_file(self, file, verbose=False):
"""Collect the data from get_midi_data and write to file."""
dat = self.get_midi_data()
try:
f = open(file, 'wb')
except:
print "Couldn't open '%s' for writing." % file
return False
try:
f.write(dat)
except:
print 'An error occured while writing data to %s.' % file
return False
f.close()
if verbose:
print 'Written %d bytes to %s.' % (len(dat), file)
return True
|
python
|
def write_file(self, file, verbose=False):
dat = self.get_midi_data()
try:
f = open(file, 'wb')
except:
print "Couldn't open '%s' for writing." % file
return False
try:
f.write(dat)
except:
print 'An error occured while writing data to %s.' % file
return False
f.close()
if verbose:
print 'Written %d bytes to %s.' % (len(dat), file)
return True
|
[
"def",
"write_file",
"(",
"self",
",",
"file",
",",
"verbose",
"=",
"False",
")",
":",
"dat",
"=",
"self",
".",
"get_midi_data",
"(",
")",
"try",
":",
"f",
"=",
"open",
"(",
"file",
",",
"'wb'",
")",
"except",
":",
"print",
"\"Couldn't open '%s' for writing.\"",
"%",
"file",
"return",
"False",
"try",
":",
"f",
".",
"write",
"(",
"dat",
")",
"except",
":",
"print",
"'An error occured while writing data to %s.'",
"%",
"file",
"return",
"False",
"f",
".",
"close",
"(",
")",
"if",
"verbose",
":",
"print",
"'Written %d bytes to %s.'",
"%",
"(",
"len",
"(",
"dat",
")",
",",
"file",
")",
"return",
"True"
] |
Collect the data from get_midi_data and write to file.
|
[
"Collect",
"the",
"data",
"from",
"get_midi_data",
"and",
"write",
"to",
"file",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L52-L68
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
fingers_needed
|
def fingers_needed(fingering):
"""Return the number of fingers needed to play the given fingering."""
split = False # True if an open string must be played, thereby making any
# subsequent strings impossible to bar with the index finger
indexfinger = False # True if the index finger was already accounted for
# in the count
minimum = min(finger for finger in fingering if finger) # the index finger
# plays the lowest
# finger position
result = 0
for finger in reversed(fingering):
if finger == 0: # an open string is played
split = True # subsequent strings are impossible to bar with the
# index finger
else:
if not split and finger == minimum: # if an open string hasn't been
# played and this is a job for
# the index finger:
if not indexfinger: # if the index finger hasn't been accounted
# for:
result += 1
indexfinger = True # index finger has now been accounted for
else:
result += 1
return result
|
python
|
def fingers_needed(fingering):
split = False
indexfinger = False
minimum = min(finger for finger in fingering if finger)
result = 0
for finger in reversed(fingering):
if finger == 0:
split = True
else:
if not split and finger == minimum:
if not indexfinger:
result += 1
indexfinger = True
else:
result += 1
return result
|
[
"def",
"fingers_needed",
"(",
"fingering",
")",
":",
"split",
"=",
"False",
"# True if an open string must be played, thereby making any",
"# subsequent strings impossible to bar with the index finger",
"indexfinger",
"=",
"False",
"# True if the index finger was already accounted for",
"# in the count",
"minimum",
"=",
"min",
"(",
"finger",
"for",
"finger",
"in",
"fingering",
"if",
"finger",
")",
"# the index finger",
"# plays the lowest",
"# finger position",
"result",
"=",
"0",
"for",
"finger",
"in",
"reversed",
"(",
"fingering",
")",
":",
"if",
"finger",
"==",
"0",
":",
"# an open string is played",
"split",
"=",
"True",
"# subsequent strings are impossible to bar with the",
"# index finger",
"else",
":",
"if",
"not",
"split",
"and",
"finger",
"==",
"minimum",
":",
"# if an open string hasn't been",
"# played and this is a job for",
"# the index finger:",
"if",
"not",
"indexfinger",
":",
"# if the index finger hasn't been accounted",
"# for:",
"result",
"+=",
"1",
"indexfinger",
"=",
"True",
"# index finger has now been accounted for",
"else",
":",
"result",
"+=",
"1",
"return",
"result"
] |
Return the number of fingers needed to play the given fingering.
|
[
"Return",
"the",
"number",
"of",
"fingers",
"needed",
"to",
"play",
"the",
"given",
"fingering",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L337-L361
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
add_tuning
|
def add_tuning(instrument, description, tuning):
"""Add a new tuning to the index.
The instrument and description parameters should be strings; tuning
should be a list of strings or a list of lists to denote courses.
Example:
>>> std_strings = ['E-2', 'A-2', 'D-3', 'G-3', 'B-3', 'E-4']
>>> tuning.add_tuning('Guitar', 'standard', std_strings)
>>> tw_strings = [['E-2', 'E-3'], ['A-2', 'A-3'], ...........]
>>> tuning.add_tuning('Guitar', 'twelve string', tw_string)
"""
t = StringTuning(instrument, description, tuning)
if _known.has_key(str.upper(instrument)):
_known[str.upper(instrument)][1][str.upper(description)] = t
else:
_known[str.upper(instrument)] = (instrument,
{str.upper(description): t})
|
python
|
def add_tuning(instrument, description, tuning):
t = StringTuning(instrument, description, tuning)
if _known.has_key(str.upper(instrument)):
_known[str.upper(instrument)][1][str.upper(description)] = t
else:
_known[str.upper(instrument)] = (instrument,
{str.upper(description): t})
|
[
"def",
"add_tuning",
"(",
"instrument",
",",
"description",
",",
"tuning",
")",
":",
"t",
"=",
"StringTuning",
"(",
"instrument",
",",
"description",
",",
"tuning",
")",
"if",
"_known",
".",
"has_key",
"(",
"str",
".",
"upper",
"(",
"instrument",
")",
")",
":",
"_known",
"[",
"str",
".",
"upper",
"(",
"instrument",
")",
"]",
"[",
"1",
"]",
"[",
"str",
".",
"upper",
"(",
"description",
")",
"]",
"=",
"t",
"else",
":",
"_known",
"[",
"str",
".",
"upper",
"(",
"instrument",
")",
"]",
"=",
"(",
"instrument",
",",
"{",
"str",
".",
"upper",
"(",
"description",
")",
":",
"t",
"}",
")"
] |
Add a new tuning to the index.
The instrument and description parameters should be strings; tuning
should be a list of strings or a list of lists to denote courses.
Example:
>>> std_strings = ['E-2', 'A-2', 'D-3', 'G-3', 'B-3', 'E-4']
>>> tuning.add_tuning('Guitar', 'standard', std_strings)
>>> tw_strings = [['E-2', 'E-3'], ['A-2', 'A-3'], ...........]
>>> tuning.add_tuning('Guitar', 'twelve string', tw_string)
|
[
"Add",
"a",
"new",
"tuning",
"to",
"the",
"index",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L366-L383
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
get_tuning
|
def get_tuning(instrument, description, nr_of_strings=None, nr_of_courses=None):
"""Get the first tuning that satisfies the constraints.
The instrument and description arguments are treated like
case-insensitive prefixes. So search for 'bass' is the same is
'Bass Guitar'.
Example:
>>> tunings.get_tuning('guitar', 'standard')
<tunings.StringTuning instance at 0x139ac20>
"""
searchi = str.upper(instrument)
searchd = str.upper(description)
keys = _known.keys()
for x in keys:
if (searchi not in keys and x.find(searchi) == 0 or searchi in keys and
x == searchi):
for (desc, tun) in _known[x][1].iteritems():
if desc.find(searchd) == 0:
if nr_of_strings is None and nr_of_courses is None:
return tun
elif nr_of_strings is not None and nr_of_courses is None:
if tun.count_strings() == nr_of_strings:
return tun
elif nr_of_strings is None and nr_of_courses is not None:
if tun.count_courses() == nr_of_courses:
return tun
else:
if tun.count_courses() == nr_of_courses\
and tun.count_strings() == nr_of_strings:
return tun
|
python
|
def get_tuning(instrument, description, nr_of_strings=None, nr_of_courses=None):
searchi = str.upper(instrument)
searchd = str.upper(description)
keys = _known.keys()
for x in keys:
if (searchi not in keys and x.find(searchi) == 0 or searchi in keys and
x == searchi):
for (desc, tun) in _known[x][1].iteritems():
if desc.find(searchd) == 0:
if nr_of_strings is None and nr_of_courses is None:
return tun
elif nr_of_strings is not None and nr_of_courses is None:
if tun.count_strings() == nr_of_strings:
return tun
elif nr_of_strings is None and nr_of_courses is not None:
if tun.count_courses() == nr_of_courses:
return tun
else:
if tun.count_courses() == nr_of_courses\
and tun.count_strings() == nr_of_strings:
return tun
|
[
"def",
"get_tuning",
"(",
"instrument",
",",
"description",
",",
"nr_of_strings",
"=",
"None",
",",
"nr_of_courses",
"=",
"None",
")",
":",
"searchi",
"=",
"str",
".",
"upper",
"(",
"instrument",
")",
"searchd",
"=",
"str",
".",
"upper",
"(",
"description",
")",
"keys",
"=",
"_known",
".",
"keys",
"(",
")",
"for",
"x",
"in",
"keys",
":",
"if",
"(",
"searchi",
"not",
"in",
"keys",
"and",
"x",
".",
"find",
"(",
"searchi",
")",
"==",
"0",
"or",
"searchi",
"in",
"keys",
"and",
"x",
"==",
"searchi",
")",
":",
"for",
"(",
"desc",
",",
"tun",
")",
"in",
"_known",
"[",
"x",
"]",
"[",
"1",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"desc",
".",
"find",
"(",
"searchd",
")",
"==",
"0",
":",
"if",
"nr_of_strings",
"is",
"None",
"and",
"nr_of_courses",
"is",
"None",
":",
"return",
"tun",
"elif",
"nr_of_strings",
"is",
"not",
"None",
"and",
"nr_of_courses",
"is",
"None",
":",
"if",
"tun",
".",
"count_strings",
"(",
")",
"==",
"nr_of_strings",
":",
"return",
"tun",
"elif",
"nr_of_strings",
"is",
"None",
"and",
"nr_of_courses",
"is",
"not",
"None",
":",
"if",
"tun",
".",
"count_courses",
"(",
")",
"==",
"nr_of_courses",
":",
"return",
"tun",
"else",
":",
"if",
"tun",
".",
"count_courses",
"(",
")",
"==",
"nr_of_courses",
"and",
"tun",
".",
"count_strings",
"(",
")",
"==",
"nr_of_strings",
":",
"return",
"tun"
] |
Get the first tuning that satisfies the constraints.
The instrument and description arguments are treated like
case-insensitive prefixes. So search for 'bass' is the same is
'Bass Guitar'.
Example:
>>> tunings.get_tuning('guitar', 'standard')
<tunings.StringTuning instance at 0x139ac20>
|
[
"Get",
"the",
"first",
"tuning",
"that",
"satisfies",
"the",
"constraints",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L385-L415
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
get_tunings
|
def get_tunings(instrument=None, nr_of_strings=None, nr_of_courses=None):
"""Search tunings on instrument, strings, courses or a combination.
The instrument is actually treated like a case-insensitive prefix. So
asking for 'bass' yields the same tunings as 'Bass Guitar'; the string
'ba' yields all the instruments starting with 'ba'.
Example:
>>> tunings.get_tunings(nr_of_string = 4)
>>> tunings.get_tunings('bass')
"""
search = ''
if instrument is not None:
search = str.upper(instrument)
result = []
keys = _known.keys()
inkeys = search in keys
for x in keys:
if (instrument is None or not inkeys and x.find(search) == 0 or
inkeys and search == x):
if nr_of_strings is None and nr_of_courses is None:
result += _known[x][1].values()
elif nr_of_strings is not None and nr_of_courses is None:
result += [y for y in _known[x][1].itervalues()
if y.count_strings() == nr_of_strings]
elif nr_of_strings is None and nr_of_courses is not None:
result += [y for y in _known[x][1].itervalues()
if y.count_courses() == nr_of_courses]
else:
result += [y for y in _known[x][1].itervalues()
if y.count_strings() == nr_of_strings
and y.count_courses() == nr_of_courses]
return result
|
python
|
def get_tunings(instrument=None, nr_of_strings=None, nr_of_courses=None):
search = ''
if instrument is not None:
search = str.upper(instrument)
result = []
keys = _known.keys()
inkeys = search in keys
for x in keys:
if (instrument is None or not inkeys and x.find(search) == 0 or
inkeys and search == x):
if nr_of_strings is None and nr_of_courses is None:
result += _known[x][1].values()
elif nr_of_strings is not None and nr_of_courses is None:
result += [y for y in _known[x][1].itervalues()
if y.count_strings() == nr_of_strings]
elif nr_of_strings is None and nr_of_courses is not None:
result += [y for y in _known[x][1].itervalues()
if y.count_courses() == nr_of_courses]
else:
result += [y for y in _known[x][1].itervalues()
if y.count_strings() == nr_of_strings
and y.count_courses() == nr_of_courses]
return result
|
[
"def",
"get_tunings",
"(",
"instrument",
"=",
"None",
",",
"nr_of_strings",
"=",
"None",
",",
"nr_of_courses",
"=",
"None",
")",
":",
"search",
"=",
"''",
"if",
"instrument",
"is",
"not",
"None",
":",
"search",
"=",
"str",
".",
"upper",
"(",
"instrument",
")",
"result",
"=",
"[",
"]",
"keys",
"=",
"_known",
".",
"keys",
"(",
")",
"inkeys",
"=",
"search",
"in",
"keys",
"for",
"x",
"in",
"keys",
":",
"if",
"(",
"instrument",
"is",
"None",
"or",
"not",
"inkeys",
"and",
"x",
".",
"find",
"(",
"search",
")",
"==",
"0",
"or",
"inkeys",
"and",
"search",
"==",
"x",
")",
":",
"if",
"nr_of_strings",
"is",
"None",
"and",
"nr_of_courses",
"is",
"None",
":",
"result",
"+=",
"_known",
"[",
"x",
"]",
"[",
"1",
"]",
".",
"values",
"(",
")",
"elif",
"nr_of_strings",
"is",
"not",
"None",
"and",
"nr_of_courses",
"is",
"None",
":",
"result",
"+=",
"[",
"y",
"for",
"y",
"in",
"_known",
"[",
"x",
"]",
"[",
"1",
"]",
".",
"itervalues",
"(",
")",
"if",
"y",
".",
"count_strings",
"(",
")",
"==",
"nr_of_strings",
"]",
"elif",
"nr_of_strings",
"is",
"None",
"and",
"nr_of_courses",
"is",
"not",
"None",
":",
"result",
"+=",
"[",
"y",
"for",
"y",
"in",
"_known",
"[",
"x",
"]",
"[",
"1",
"]",
".",
"itervalues",
"(",
")",
"if",
"y",
".",
"count_courses",
"(",
")",
"==",
"nr_of_courses",
"]",
"else",
":",
"result",
"+=",
"[",
"y",
"for",
"y",
"in",
"_known",
"[",
"x",
"]",
"[",
"1",
"]",
".",
"itervalues",
"(",
")",
"if",
"y",
".",
"count_strings",
"(",
")",
"==",
"nr_of_strings",
"and",
"y",
".",
"count_courses",
"(",
")",
"==",
"nr_of_courses",
"]",
"return",
"result"
] |
Search tunings on instrument, strings, courses or a combination.
The instrument is actually treated like a case-insensitive prefix. So
asking for 'bass' yields the same tunings as 'Bass Guitar'; the string
'ba' yields all the instruments starting with 'ba'.
Example:
>>> tunings.get_tunings(nr_of_string = 4)
>>> tunings.get_tunings('bass')
|
[
"Search",
"tunings",
"on",
"instrument",
"strings",
"courses",
"or",
"a",
"combination",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L417-L449
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.count_courses
|
def count_courses(self):
"""Return the average number of courses per string."""
c = 0
for x in self.tuning:
if type(x) == list:
c += len(x)
else:
c += 1
return float(c) / len(self.tuning)
|
python
|
def count_courses(self):
c = 0
for x in self.tuning:
if type(x) == list:
c += len(x)
else:
c += 1
return float(c) / len(self.tuning)
|
[
"def",
"count_courses",
"(",
"self",
")",
":",
"c",
"=",
"0",
"for",
"x",
"in",
"self",
".",
"tuning",
":",
"if",
"type",
"(",
"x",
")",
"==",
"list",
":",
"c",
"+=",
"len",
"(",
"x",
")",
"else",
":",
"c",
"+=",
"1",
"return",
"float",
"(",
"c",
")",
"/",
"len",
"(",
"self",
".",
"tuning",
")"
] |
Return the average number of courses per string.
|
[
"Return",
"the",
"average",
"number",
"of",
"courses",
"per",
"string",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L56-L64
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.find_frets
|
def find_frets(self, note, maxfret=24):
"""Return a list with for each string the fret on which the note is
played or None if it can't be played on that particular string.
The maxfret parameter is the highest fret that can be played; note
should either be a string or a Note object.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'E-4'])
>>> t.find_frets(Note('C-4')
[3, None]
>>> t.find_frets(Note('A-4')
[12, 5]
"""
result = []
if type(note) == str:
note = Note(note)
for x in self.tuning:
if type(x) == list:
base = x[0]
else:
base = x
diff = base.measure(note)
if 0 <= diff <= maxfret:
result.append(diff)
else:
result.append(None)
return result
|
python
|
def find_frets(self, note, maxfret=24):
result = []
if type(note) == str:
note = Note(note)
for x in self.tuning:
if type(x) == list:
base = x[0]
else:
base = x
diff = base.measure(note)
if 0 <= diff <= maxfret:
result.append(diff)
else:
result.append(None)
return result
|
[
"def",
"find_frets",
"(",
"self",
",",
"note",
",",
"maxfret",
"=",
"24",
")",
":",
"result",
"=",
"[",
"]",
"if",
"type",
"(",
"note",
")",
"==",
"str",
":",
"note",
"=",
"Note",
"(",
"note",
")",
"for",
"x",
"in",
"self",
".",
"tuning",
":",
"if",
"type",
"(",
"x",
")",
"==",
"list",
":",
"base",
"=",
"x",
"[",
"0",
"]",
"else",
":",
"base",
"=",
"x",
"diff",
"=",
"base",
".",
"measure",
"(",
"note",
")",
"if",
"0",
"<=",
"diff",
"<=",
"maxfret",
":",
"result",
".",
"append",
"(",
"diff",
")",
"else",
":",
"result",
".",
"append",
"(",
"None",
")",
"return",
"result"
] |
Return a list with for each string the fret on which the note is
played or None if it can't be played on that particular string.
The maxfret parameter is the highest fret that can be played; note
should either be a string or a Note object.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'E-4'])
>>> t.find_frets(Note('C-4')
[3, None]
>>> t.find_frets(Note('A-4')
[12, 5]
|
[
"Return",
"a",
"list",
"with",
"for",
"each",
"string",
"the",
"fret",
"on",
"which",
"the",
"note",
"is",
"played",
"or",
"None",
"if",
"it",
"can",
"t",
"be",
"played",
"on",
"that",
"particular",
"string",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L66-L93
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.find_fingering
|
def find_fingering(self, notes, max_distance=4, not_strings=[]):
"""Return a list [(string, fret)] of possible fingerings for
'notes'.
The notes parameter should be a list of strings or Notes or a
NoteContainer; max_distance denotes the maximum distance between
frets; not_strings can be used to disclude certain strings and is
used internally to recurse.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'E-4', 'A-5'])
>>> t.find_fingering(['E-4', 'B-4'])
[[(0, 7), (1, 7)], [(1, 0), (0, 14)]]
"""
if notes is None:
return []
if len(notes) == 0:
return []
first = notes[0]
notes = notes[1:]
frets = self.find_frets(first)
result = []
for (string, fret) in enumerate(frets):
if fret is not None and string not in not_strings:
if len(notes) > 0:
# recursively find fingerings for
# remaining notes
r = self.find_fingering(notes, max_distance, not_strings
+ [string])
if r != []:
for f in r:
result.append([(string, fret)] + f)
else:
result.append([(string, fret)])
# filter impossible fingerings and sort
res = []
for r in result:
(min, max) = (1000, -1)
frets = 0
for (string, fret) in r:
if fret > max:
max = fret
if fret < min and fret != 0:
min = fret
frets += fret
if 0 <= max - min < max_distance or min == 1000 or max == -1:
res.append((frets, r))
return [r for (_, r) in sorted(res)]
|
python
|
def find_fingering(self, notes, max_distance=4, not_strings=[]):
if notes is None:
return []
if len(notes) == 0:
return []
first = notes[0]
notes = notes[1:]
frets = self.find_frets(first)
result = []
for (string, fret) in enumerate(frets):
if fret is not None and string not in not_strings:
if len(notes) > 0:
r = self.find_fingering(notes, max_distance, not_strings
+ [string])
if r != []:
for f in r:
result.append([(string, fret)] + f)
else:
result.append([(string, fret)])
res = []
for r in result:
(min, max) = (1000, -1)
frets = 0
for (string, fret) in r:
if fret > max:
max = fret
if fret < min and fret != 0:
min = fret
frets += fret
if 0 <= max - min < max_distance or min == 1000 or max == -1:
res.append((frets, r))
return [r for (_, r) in sorted(res)]
|
[
"def",
"find_fingering",
"(",
"self",
",",
"notes",
",",
"max_distance",
"=",
"4",
",",
"not_strings",
"=",
"[",
"]",
")",
":",
"if",
"notes",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"notes",
")",
"==",
"0",
":",
"return",
"[",
"]",
"first",
"=",
"notes",
"[",
"0",
"]",
"notes",
"=",
"notes",
"[",
"1",
":",
"]",
"frets",
"=",
"self",
".",
"find_frets",
"(",
"first",
")",
"result",
"=",
"[",
"]",
"for",
"(",
"string",
",",
"fret",
")",
"in",
"enumerate",
"(",
"frets",
")",
":",
"if",
"fret",
"is",
"not",
"None",
"and",
"string",
"not",
"in",
"not_strings",
":",
"if",
"len",
"(",
"notes",
")",
">",
"0",
":",
"# recursively find fingerings for",
"# remaining notes",
"r",
"=",
"self",
".",
"find_fingering",
"(",
"notes",
",",
"max_distance",
",",
"not_strings",
"+",
"[",
"string",
"]",
")",
"if",
"r",
"!=",
"[",
"]",
":",
"for",
"f",
"in",
"r",
":",
"result",
".",
"append",
"(",
"[",
"(",
"string",
",",
"fret",
")",
"]",
"+",
"f",
")",
"else",
":",
"result",
".",
"append",
"(",
"[",
"(",
"string",
",",
"fret",
")",
"]",
")",
"# filter impossible fingerings and sort",
"res",
"=",
"[",
"]",
"for",
"r",
"in",
"result",
":",
"(",
"min",
",",
"max",
")",
"=",
"(",
"1000",
",",
"-",
"1",
")",
"frets",
"=",
"0",
"for",
"(",
"string",
",",
"fret",
")",
"in",
"r",
":",
"if",
"fret",
">",
"max",
":",
"max",
"=",
"fret",
"if",
"fret",
"<",
"min",
"and",
"fret",
"!=",
"0",
":",
"min",
"=",
"fret",
"frets",
"+=",
"fret",
"if",
"0",
"<=",
"max",
"-",
"min",
"<",
"max_distance",
"or",
"min",
"==",
"1000",
"or",
"max",
"==",
"-",
"1",
":",
"res",
".",
"append",
"(",
"(",
"frets",
",",
"r",
")",
")",
"return",
"[",
"r",
"for",
"(",
"_",
",",
"r",
")",
"in",
"sorted",
"(",
"res",
")",
"]"
] |
Return a list [(string, fret)] of possible fingerings for
'notes'.
The notes parameter should be a list of strings or Notes or a
NoteContainer; max_distance denotes the maximum distance between
frets; not_strings can be used to disclude certain strings and is
used internally to recurse.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'E-4', 'A-5'])
>>> t.find_fingering(['E-4', 'B-4'])
[[(0, 7), (1, 7)], [(1, 0), (0, 14)]]
|
[
"Return",
"a",
"list",
"[",
"(",
"string",
"fret",
")",
"]",
"of",
"possible",
"fingerings",
"for",
"notes",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L95-L143
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.find_chord_fingering
|
def find_chord_fingering(self, notes, max_distance=4, maxfret=18,
max_fingers=4, return_best_as_NoteContainer=False):
"""Return a list of fret lists that are considered possible fingerings.
This function only looks at and matches on the note _names_ so it
does more than find_fingering.
Example:
>>> t = tunings.get_tuning('guitar', 'standard', 6, 1)
>>> t.find_chord_fingering(NoteContainer().from_chord('Am'))
[[0, 0, 2, 2, 1, 0], [0, 3, 2, 2, 1, 0], ......]
"""
def follow(string, next, name, prev=-1):
"""Follow the fret 'next' on 'string'; build result on the way."""
if string >= len(self.tuning) - 1:
return [[(next, name)]]
result = []
cur = res[string][next]
if cur != []:
for y in cur[1]:
for sub in follow(string + 1, y[0], y[1]):
if prev < 0:
result.append([(next, name)] + sub)
else:
if sub[0][0] == 0 or abs(sub[0][0] - prev)\
< max_distance:
result.append([(next, name)] + sub)
for s in follow(string + 1, maxfret + 1, None, next):
result.append([(next, name)] + s)
return [[(next, name)]] if result == [] else result
def make_lookup_table():
"""Prepare the lookup table.
table[string][fret] = (name, dest_frets)
"""
res = [[[] for x in xrange(maxfret + 2)] for x in
xrange(len(self.tuning) - 1)]
for x in xrange(0, len(self.tuning) - 1):
addedNone = -1
next = fretdict[x + 1]
for (fret, name) in fretdict[x]:
for (f2, n2) in next:
if n2 != name and (f2 == 0 or abs(fret - f2)
< max_distance):
if res[x][fret] != []:
res[x][fret][1].append((f2, n2))
else:
res[x][fret] = (name, [(f2, n2)])
if addedNone < x:
if res[x][maxfret + 1] != []:
res[x][maxfret + 1][1].append((f2, n2))
else:
res[x][maxfret + 1] = (None, [(f2, n2)])
addedNone = x
return res
# Convert to NoteContainer if necessary
n = notes
if notes != [] and type(notes) == list and type(notes[0]) == str:
n = NoteContainer(notes)
# Check number of note names.
notenames = [x.name for x in n]
if len(notenames) == 0 or len(notenames) > len(self.tuning):
return []
# Make string-fret dictionary
fretdict = []
for x in xrange(0, len(self.tuning)):
fretdict.append(self.find_note_names(notes, x, maxfret))
# Build table
res = make_lookup_table()
# Build result using table
result = []
# For each fret on the first string
for (i, y) in enumerate(res[0]):
if y != []:
(yname, next) = (y[0], y[1])
# For each destination fret in y
for (fret, name) in next:
# For each followed result
for s in follow(1, fret, name):
subresult = [(i, yname)] + s
# Get boundaries
(mi, ma, names) = (1000, -1000, [])
for (f, n) in subresult:
if n is not None:
if f != 0 and f <= mi:
mi = f
if f != 0 and f >= ma:
ma = f
names.append(n)
# Enforce boundaries
if abs(ma - mi) < max_distance:
# Check if all note
# names are present
covered = True
for n in notenames:
if n not in names:
covered = False
# Add to result
if covered and names != []:
result.append([y[0] if y[1]
is not None else y[1] for y in
subresult])
# Return semi-sorted list
s = sorted(result, key=lambda x: sum([t if t is not None else 1000
for (i, t) in enumerate(x)]))
s = filter(lambda a: fingers_needed(a) <= max_fingers, s)
if not return_best_as_NoteContainer:
return s
else:
rnotes = self.frets_to_NoteContainer(s[0])
for (i, x) in enumerate(rnotes):
if x.string < len(self.tuning) - 1:
if res[x.string][x.fret] != []:
rnotes[i].name = res[x.string][x.fret][0]
return rnotes
|
python
|
def find_chord_fingering(self, notes, max_distance=4, maxfret=18,
max_fingers=4, return_best_as_NoteContainer=False):
def follow(string, next, name, prev=-1):
if string >= len(self.tuning) - 1:
return [[(next, name)]]
result = []
cur = res[string][next]
if cur != []:
for y in cur[1]:
for sub in follow(string + 1, y[0], y[1]):
if prev < 0:
result.append([(next, name)] + sub)
else:
if sub[0][0] == 0 or abs(sub[0][0] - prev)\
< max_distance:
result.append([(next, name)] + sub)
for s in follow(string + 1, maxfret + 1, None, next):
result.append([(next, name)] + s)
return [[(next, name)]] if result == [] else result
def make_lookup_table():
res = [[[] for x in xrange(maxfret + 2)] for x in
xrange(len(self.tuning) - 1)]
for x in xrange(0, len(self.tuning) - 1):
addedNone = -1
next = fretdict[x + 1]
for (fret, name) in fretdict[x]:
for (f2, n2) in next:
if n2 != name and (f2 == 0 or abs(fret - f2)
< max_distance):
if res[x][fret] != []:
res[x][fret][1].append((f2, n2))
else:
res[x][fret] = (name, [(f2, n2)])
if addedNone < x:
if res[x][maxfret + 1] != []:
res[x][maxfret + 1][1].append((f2, n2))
else:
res[x][maxfret + 1] = (None, [(f2, n2)])
addedNone = x
return res
n = notes
if notes != [] and type(notes) == list and type(notes[0]) == str:
n = NoteContainer(notes)
notenames = [x.name for x in n]
if len(notenames) == 0 or len(notenames) > len(self.tuning):
return []
fretdict = []
for x in xrange(0, len(self.tuning)):
fretdict.append(self.find_note_names(notes, x, maxfret))
res = make_lookup_table()
result = []
for (i, y) in enumerate(res[0]):
if y != []:
(yname, next) = (y[0], y[1])
for (fret, name) in next:
for s in follow(1, fret, name):
subresult = [(i, yname)] + s
(mi, ma, names) = (1000, -1000, [])
for (f, n) in subresult:
if n is not None:
if f != 0 and f <= mi:
mi = f
if f != 0 and f >= ma:
ma = f
names.append(n)
if abs(ma - mi) < max_distance:
covered = True
for n in notenames:
if n not in names:
covered = False
if covered and names != []:
result.append([y[0] if y[1]
is not None else y[1] for y in
subresult])
s = sorted(result, key=lambda x: sum([t if t is not None else 1000
for (i, t) in enumerate(x)]))
s = filter(lambda a: fingers_needed(a) <= max_fingers, s)
if not return_best_as_NoteContainer:
return s
else:
rnotes = self.frets_to_NoteContainer(s[0])
for (i, x) in enumerate(rnotes):
if x.string < len(self.tuning) - 1:
if res[x.string][x.fret] != []:
rnotes[i].name = res[x.string][x.fret][0]
return rnotes
|
[
"def",
"find_chord_fingering",
"(",
"self",
",",
"notes",
",",
"max_distance",
"=",
"4",
",",
"maxfret",
"=",
"18",
",",
"max_fingers",
"=",
"4",
",",
"return_best_as_NoteContainer",
"=",
"False",
")",
":",
"def",
"follow",
"(",
"string",
",",
"next",
",",
"name",
",",
"prev",
"=",
"-",
"1",
")",
":",
"\"\"\"Follow the fret 'next' on 'string'; build result on the way.\"\"\"",
"if",
"string",
">=",
"len",
"(",
"self",
".",
"tuning",
")",
"-",
"1",
":",
"return",
"[",
"[",
"(",
"next",
",",
"name",
")",
"]",
"]",
"result",
"=",
"[",
"]",
"cur",
"=",
"res",
"[",
"string",
"]",
"[",
"next",
"]",
"if",
"cur",
"!=",
"[",
"]",
":",
"for",
"y",
"in",
"cur",
"[",
"1",
"]",
":",
"for",
"sub",
"in",
"follow",
"(",
"string",
"+",
"1",
",",
"y",
"[",
"0",
"]",
",",
"y",
"[",
"1",
"]",
")",
":",
"if",
"prev",
"<",
"0",
":",
"result",
".",
"append",
"(",
"[",
"(",
"next",
",",
"name",
")",
"]",
"+",
"sub",
")",
"else",
":",
"if",
"sub",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"0",
"or",
"abs",
"(",
"sub",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"prev",
")",
"<",
"max_distance",
":",
"result",
".",
"append",
"(",
"[",
"(",
"next",
",",
"name",
")",
"]",
"+",
"sub",
")",
"for",
"s",
"in",
"follow",
"(",
"string",
"+",
"1",
",",
"maxfret",
"+",
"1",
",",
"None",
",",
"next",
")",
":",
"result",
".",
"append",
"(",
"[",
"(",
"next",
",",
"name",
")",
"]",
"+",
"s",
")",
"return",
"[",
"[",
"(",
"next",
",",
"name",
")",
"]",
"]",
"if",
"result",
"==",
"[",
"]",
"else",
"result",
"def",
"make_lookup_table",
"(",
")",
":",
"\"\"\"Prepare the lookup table.\n\n table[string][fret] = (name, dest_frets)\n \"\"\"",
"res",
"=",
"[",
"[",
"[",
"]",
"for",
"x",
"in",
"xrange",
"(",
"maxfret",
"+",
"2",
")",
"]",
"for",
"x",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"tuning",
")",
"-",
"1",
")",
"]",
"for",
"x",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"tuning",
")",
"-",
"1",
")",
":",
"addedNone",
"=",
"-",
"1",
"next",
"=",
"fretdict",
"[",
"x",
"+",
"1",
"]",
"for",
"(",
"fret",
",",
"name",
")",
"in",
"fretdict",
"[",
"x",
"]",
":",
"for",
"(",
"f2",
",",
"n2",
")",
"in",
"next",
":",
"if",
"n2",
"!=",
"name",
"and",
"(",
"f2",
"==",
"0",
"or",
"abs",
"(",
"fret",
"-",
"f2",
")",
"<",
"max_distance",
")",
":",
"if",
"res",
"[",
"x",
"]",
"[",
"fret",
"]",
"!=",
"[",
"]",
":",
"res",
"[",
"x",
"]",
"[",
"fret",
"]",
"[",
"1",
"]",
".",
"append",
"(",
"(",
"f2",
",",
"n2",
")",
")",
"else",
":",
"res",
"[",
"x",
"]",
"[",
"fret",
"]",
"=",
"(",
"name",
",",
"[",
"(",
"f2",
",",
"n2",
")",
"]",
")",
"if",
"addedNone",
"<",
"x",
":",
"if",
"res",
"[",
"x",
"]",
"[",
"maxfret",
"+",
"1",
"]",
"!=",
"[",
"]",
":",
"res",
"[",
"x",
"]",
"[",
"maxfret",
"+",
"1",
"]",
"[",
"1",
"]",
".",
"append",
"(",
"(",
"f2",
",",
"n2",
")",
")",
"else",
":",
"res",
"[",
"x",
"]",
"[",
"maxfret",
"+",
"1",
"]",
"=",
"(",
"None",
",",
"[",
"(",
"f2",
",",
"n2",
")",
"]",
")",
"addedNone",
"=",
"x",
"return",
"res",
"# Convert to NoteContainer if necessary",
"n",
"=",
"notes",
"if",
"notes",
"!=",
"[",
"]",
"and",
"type",
"(",
"notes",
")",
"==",
"list",
"and",
"type",
"(",
"notes",
"[",
"0",
"]",
")",
"==",
"str",
":",
"n",
"=",
"NoteContainer",
"(",
"notes",
")",
"# Check number of note names.",
"notenames",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"n",
"]",
"if",
"len",
"(",
"notenames",
")",
"==",
"0",
"or",
"len",
"(",
"notenames",
")",
">",
"len",
"(",
"self",
".",
"tuning",
")",
":",
"return",
"[",
"]",
"# Make string-fret dictionary",
"fretdict",
"=",
"[",
"]",
"for",
"x",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"tuning",
")",
")",
":",
"fretdict",
".",
"append",
"(",
"self",
".",
"find_note_names",
"(",
"notes",
",",
"x",
",",
"maxfret",
")",
")",
"# Build table",
"res",
"=",
"make_lookup_table",
"(",
")",
"# Build result using table",
"result",
"=",
"[",
"]",
"# For each fret on the first string",
"for",
"(",
"i",
",",
"y",
")",
"in",
"enumerate",
"(",
"res",
"[",
"0",
"]",
")",
":",
"if",
"y",
"!=",
"[",
"]",
":",
"(",
"yname",
",",
"next",
")",
"=",
"(",
"y",
"[",
"0",
"]",
",",
"y",
"[",
"1",
"]",
")",
"# For each destination fret in y",
"for",
"(",
"fret",
",",
"name",
")",
"in",
"next",
":",
"# For each followed result",
"for",
"s",
"in",
"follow",
"(",
"1",
",",
"fret",
",",
"name",
")",
":",
"subresult",
"=",
"[",
"(",
"i",
",",
"yname",
")",
"]",
"+",
"s",
"# Get boundaries",
"(",
"mi",
",",
"ma",
",",
"names",
")",
"=",
"(",
"1000",
",",
"-",
"1000",
",",
"[",
"]",
")",
"for",
"(",
"f",
",",
"n",
")",
"in",
"subresult",
":",
"if",
"n",
"is",
"not",
"None",
":",
"if",
"f",
"!=",
"0",
"and",
"f",
"<=",
"mi",
":",
"mi",
"=",
"f",
"if",
"f",
"!=",
"0",
"and",
"f",
">=",
"ma",
":",
"ma",
"=",
"f",
"names",
".",
"append",
"(",
"n",
")",
"# Enforce boundaries",
"if",
"abs",
"(",
"ma",
"-",
"mi",
")",
"<",
"max_distance",
":",
"# Check if all note",
"# names are present",
"covered",
"=",
"True",
"for",
"n",
"in",
"notenames",
":",
"if",
"n",
"not",
"in",
"names",
":",
"covered",
"=",
"False",
"# Add to result",
"if",
"covered",
"and",
"names",
"!=",
"[",
"]",
":",
"result",
".",
"append",
"(",
"[",
"y",
"[",
"0",
"]",
"if",
"y",
"[",
"1",
"]",
"is",
"not",
"None",
"else",
"y",
"[",
"1",
"]",
"for",
"y",
"in",
"subresult",
"]",
")",
"# Return semi-sorted list",
"s",
"=",
"sorted",
"(",
"result",
",",
"key",
"=",
"lambda",
"x",
":",
"sum",
"(",
"[",
"t",
"if",
"t",
"is",
"not",
"None",
"else",
"1000",
"for",
"(",
"i",
",",
"t",
")",
"in",
"enumerate",
"(",
"x",
")",
"]",
")",
")",
"s",
"=",
"filter",
"(",
"lambda",
"a",
":",
"fingers_needed",
"(",
"a",
")",
"<=",
"max_fingers",
",",
"s",
")",
"if",
"not",
"return_best_as_NoteContainer",
":",
"return",
"s",
"else",
":",
"rnotes",
"=",
"self",
".",
"frets_to_NoteContainer",
"(",
"s",
"[",
"0",
"]",
")",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"rnotes",
")",
":",
"if",
"x",
".",
"string",
"<",
"len",
"(",
"self",
".",
"tuning",
")",
"-",
"1",
":",
"if",
"res",
"[",
"x",
".",
"string",
"]",
"[",
"x",
".",
"fret",
"]",
"!=",
"[",
"]",
":",
"rnotes",
"[",
"i",
"]",
".",
"name",
"=",
"res",
"[",
"x",
".",
"string",
"]",
"[",
"x",
".",
"fret",
"]",
"[",
"0",
"]",
"return",
"rnotes"
] |
Return a list of fret lists that are considered possible fingerings.
This function only looks at and matches on the note _names_ so it
does more than find_fingering.
Example:
>>> t = tunings.get_tuning('guitar', 'standard', 6, 1)
>>> t.find_chord_fingering(NoteContainer().from_chord('Am'))
[[0, 0, 2, 2, 1, 0], [0, 3, 2, 2, 1, 0], ......]
|
[
"Return",
"a",
"list",
"of",
"fret",
"lists",
"that",
"are",
"considered",
"possible",
"fingerings",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L145-L272
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.frets_to_NoteContainer
|
def frets_to_NoteContainer(self, fingering):
"""Convert a list such as returned by find_fret to a NoteContainer."""
res = []
for (string, fret) in enumerate(fingering):
if fret is not None:
res.append(self.get_Note(string, fret))
return NoteContainer(res)
|
python
|
def frets_to_NoteContainer(self, fingering):
res = []
for (string, fret) in enumerate(fingering):
if fret is not None:
res.append(self.get_Note(string, fret))
return NoteContainer(res)
|
[
"def",
"frets_to_NoteContainer",
"(",
"self",
",",
"fingering",
")",
":",
"res",
"=",
"[",
"]",
"for",
"(",
"string",
",",
"fret",
")",
"in",
"enumerate",
"(",
"fingering",
")",
":",
"if",
"fret",
"is",
"not",
"None",
":",
"res",
".",
"append",
"(",
"self",
".",
"get_Note",
"(",
"string",
",",
"fret",
")",
")",
"return",
"NoteContainer",
"(",
"res",
")"
] |
Convert a list such as returned by find_fret to a NoteContainer.
|
[
"Convert",
"a",
"list",
"such",
"as",
"returned",
"by",
"find_fret",
"to",
"a",
"NoteContainer",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L274-L281
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.find_note_names
|
def find_note_names(self, notelist, string=0, maxfret=24):
"""Return a list [(fret, notename)] in ascending order.
Notelist should be a list of Notes, note-strings or a NoteContainer.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t.find_note_names(['A', 'C', 'E'], 0, 12)
[(0, 'E'), (5, 'A'), (8, 'C'), (12, 'E')]
"""
n = notelist
if notelist != [] and type(notelist[0]) == str:
n = NoteContainer(notelist)
result = []
names = [x.name for x in n]
int_notes = [notes.note_to_int(x) for x in names]
# Base of the string
s = int(self.tuning[string]) % 12
for x in xrange(0, maxfret + 1):
if (s + x) % 12 in int_notes:
result.append((x, names[int_notes.index((s + x) % 12)]))
return result
|
python
|
def find_note_names(self, notelist, string=0, maxfret=24):
n = notelist
if notelist != [] and type(notelist[0]) == str:
n = NoteContainer(notelist)
result = []
names = [x.name for x in n]
int_notes = [notes.note_to_int(x) for x in names]
s = int(self.tuning[string]) % 12
for x in xrange(0, maxfret + 1):
if (s + x) % 12 in int_notes:
result.append((x, names[int_notes.index((s + x) % 12)]))
return result
|
[
"def",
"find_note_names",
"(",
"self",
",",
"notelist",
",",
"string",
"=",
"0",
",",
"maxfret",
"=",
"24",
")",
":",
"n",
"=",
"notelist",
"if",
"notelist",
"!=",
"[",
"]",
"and",
"type",
"(",
"notelist",
"[",
"0",
"]",
")",
"==",
"str",
":",
"n",
"=",
"NoteContainer",
"(",
"notelist",
")",
"result",
"=",
"[",
"]",
"names",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"n",
"]",
"int_notes",
"=",
"[",
"notes",
".",
"note_to_int",
"(",
"x",
")",
"for",
"x",
"in",
"names",
"]",
"# Base of the string",
"s",
"=",
"int",
"(",
"self",
".",
"tuning",
"[",
"string",
"]",
")",
"%",
"12",
"for",
"x",
"in",
"xrange",
"(",
"0",
",",
"maxfret",
"+",
"1",
")",
":",
"if",
"(",
"s",
"+",
"x",
")",
"%",
"12",
"in",
"int_notes",
":",
"result",
".",
"append",
"(",
"(",
"x",
",",
"names",
"[",
"int_notes",
".",
"index",
"(",
"(",
"s",
"+",
"x",
")",
"%",
"12",
")",
"]",
")",
")",
"return",
"result"
] |
Return a list [(fret, notename)] in ascending order.
Notelist should be a list of Notes, note-strings or a NoteContainer.
Example:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t.find_note_names(['A', 'C', 'E'], 0, 12)
[(0, 'E'), (5, 'A'), (8, 'C'), (12, 'E')]
|
[
"Return",
"a",
"list",
"[",
"(",
"fret",
"notename",
")",
"]",
"in",
"ascending",
"order",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L283-L305
|
bspaans/python-mingus
|
mingus/extra/tunings.py
|
StringTuning.get_Note
|
def get_Note(self, string=0, fret=0, maxfret=24):
"""Return the Note on 'string', 'fret'.
Throw a RangeError if either the fret or string is unplayable.
Examples:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_Note(0, 1)
'A#-3'
>>> t.get_Note(1, 0)
'A-4'
"""
if 0 <= string < self.count_strings():
if 0 <= fret <= maxfret:
s = self.tuning[string]
if type(s) == list:
s = s[0]
n = Note(int(s) + fret)
n.string = string
n.fret = fret
return n
else:
raise RangeError("Fret '%d' on string '%d' is out of range"
% (string, fret))
else:
raise RangeError("String '%d' out of range" % string)
|
python
|
def get_Note(self, string=0, fret=0, maxfret=24):
if 0 <= string < self.count_strings():
if 0 <= fret <= maxfret:
s = self.tuning[string]
if type(s) == list:
s = s[0]
n = Note(int(s) + fret)
n.string = string
n.fret = fret
return n
else:
raise RangeError("Fret '%d' on string '%d' is out of range"
% (string, fret))
else:
raise RangeError("String '%d' out of range" % string)
|
[
"def",
"get_Note",
"(",
"self",
",",
"string",
"=",
"0",
",",
"fret",
"=",
"0",
",",
"maxfret",
"=",
"24",
")",
":",
"if",
"0",
"<=",
"string",
"<",
"self",
".",
"count_strings",
"(",
")",
":",
"if",
"0",
"<=",
"fret",
"<=",
"maxfret",
":",
"s",
"=",
"self",
".",
"tuning",
"[",
"string",
"]",
"if",
"type",
"(",
"s",
")",
"==",
"list",
":",
"s",
"=",
"s",
"[",
"0",
"]",
"n",
"=",
"Note",
"(",
"int",
"(",
"s",
")",
"+",
"fret",
")",
"n",
".",
"string",
"=",
"string",
"n",
".",
"fret",
"=",
"fret",
"return",
"n",
"else",
":",
"raise",
"RangeError",
"(",
"\"Fret '%d' on string '%d' is out of range\"",
"%",
"(",
"string",
",",
"fret",
")",
")",
"else",
":",
"raise",
"RangeError",
"(",
"\"String '%d' out of range\"",
"%",
"string",
")"
] |
Return the Note on 'string', 'fret'.
Throw a RangeError if either the fret or string is unplayable.
Examples:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_Note(0, 1)
'A#-3'
>>> t.get_Note(1, 0)
'A-4'
|
[
"Return",
"the",
"Note",
"on",
"string",
"fret",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L307-L334
|
bspaans/python-mingus
|
mingus_examples/pygame-drum/pygame-drum.py
|
load_img
|
def load_img(name):
"""Load image and return an image object"""
fullname = name
try:
image = pygame.image.load(fullname)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, message:
print "Error: couldn't load image: ", fullname
raise SystemExit, message
return (image, image.get_rect())
|
python
|
def load_img(name):
fullname = name
try:
image = pygame.image.load(fullname)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, message:
print "Error: couldn't load image: ", fullname
raise SystemExit, message
return (image, image.get_rect())
|
[
"def",
"load_img",
"(",
"name",
")",
":",
"fullname",
"=",
"name",
"try",
":",
"image",
"=",
"pygame",
".",
"image",
".",
"load",
"(",
"fullname",
")",
"if",
"image",
".",
"get_alpha",
"(",
")",
"is",
"None",
":",
"image",
"=",
"image",
".",
"convert",
"(",
")",
"else",
":",
"image",
"=",
"image",
".",
"convert_alpha",
"(",
")",
"except",
"pygame",
".",
"error",
",",
"message",
":",
"print",
"\"Error: couldn't load image: \"",
",",
"fullname",
"raise",
"SystemExit",
",",
"message",
"return",
"(",
"image",
",",
"image",
".",
"get_rect",
"(",
")",
")"
] |
Load image and return an image object
|
[
"Load",
"image",
"and",
"return",
"an",
"image",
"object"
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-drum/pygame-drum.py#L55-L68
|
bspaans/python-mingus
|
mingus_examples/pygame-drum/pygame-drum.py
|
play_note
|
def play_note(note):
"""play_note determines which pad was 'hit' and send the
play request to fluidsynth"""
index = None
if note == Note('B', 2):
index = 0
elif note == Note('A', 2):
index = 1
elif note == Note('G', 2):
index = 2
elif note == Note('E', 2):
index = 3
elif note == Note('C', 2):
index = 4
elif note == Note('A', 3):
index = 5
elif note == Note('B', 3):
index = 6
elif note == Note('A#', 2):
index = 7
elif note == Note('G#', 2):
index = 8
if index != None and status == 'record':
playing.append([index, tick])
recorded.append([index, tick, note])
recorded_buffer.append([index, tick])
fluidsynth.play_Note(note, 9, 100)
|
python
|
def play_note(note):
index = None
if note == Note('B', 2):
index = 0
elif note == Note('A', 2):
index = 1
elif note == Note('G', 2):
index = 2
elif note == Note('E', 2):
index = 3
elif note == Note('C', 2):
index = 4
elif note == Note('A', 3):
index = 5
elif note == Note('B', 3):
index = 6
elif note == Note('A
index = 7
elif note == Note('G
index = 8
if index != None and status == 'record':
playing.append([index, tick])
recorded.append([index, tick, note])
recorded_buffer.append([index, tick])
fluidsynth.play_Note(note, 9, 100)
|
[
"def",
"play_note",
"(",
"note",
")",
":",
"index",
"=",
"None",
"if",
"note",
"==",
"Note",
"(",
"'B'",
",",
"2",
")",
":",
"index",
"=",
"0",
"elif",
"note",
"==",
"Note",
"(",
"'A'",
",",
"2",
")",
":",
"index",
"=",
"1",
"elif",
"note",
"==",
"Note",
"(",
"'G'",
",",
"2",
")",
":",
"index",
"=",
"2",
"elif",
"note",
"==",
"Note",
"(",
"'E'",
",",
"2",
")",
":",
"index",
"=",
"3",
"elif",
"note",
"==",
"Note",
"(",
"'C'",
",",
"2",
")",
":",
"index",
"=",
"4",
"elif",
"note",
"==",
"Note",
"(",
"'A'",
",",
"3",
")",
":",
"index",
"=",
"5",
"elif",
"note",
"==",
"Note",
"(",
"'B'",
",",
"3",
")",
":",
"index",
"=",
"6",
"elif",
"note",
"==",
"Note",
"(",
"'A#'",
",",
"2",
")",
":",
"index",
"=",
"7",
"elif",
"note",
"==",
"Note",
"(",
"'G#'",
",",
"2",
")",
":",
"index",
"=",
"8",
"if",
"index",
"!=",
"None",
"and",
"status",
"==",
"'record'",
":",
"playing",
".",
"append",
"(",
"[",
"index",
",",
"tick",
"]",
")",
"recorded",
".",
"append",
"(",
"[",
"index",
",",
"tick",
",",
"note",
"]",
")",
"recorded_buffer",
".",
"append",
"(",
"[",
"index",
",",
"tick",
"]",
")",
"fluidsynth",
".",
"play_Note",
"(",
"note",
",",
"9",
",",
"100",
")"
] |
play_note determines which pad was 'hit' and send the
play request to fluidsynth
|
[
"play_note",
"determines",
"which",
"pad",
"was",
"hit",
"and",
"send",
"the",
"play",
"request",
"to",
"fluidsynth"
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-drum/pygame-drum.py#L88-L115
|
bspaans/python-mingus
|
mingus_examples/pygame-piano/pygame-piano.py
|
play_note
|
def play_note(note):
"""play_note determines the coordinates of a note on the keyboard image
and sends a request to play the note to the fluidsynth server"""
global text
octave_offset = (note.octave - LOWEST) * width
if note.name in WHITE_KEYS:
# Getting the x coordinate of a white key can be done automatically
w = WHITE_KEYS.index(note.name) * white_key_width
w = w + octave_offset
# Add a list containing the x coordinate, the tick at the current time
# and of course the note itself to playing_w
playing_w.append([w, tick, note])
else:
# For black keys I hard coded the x coordinates. It's ugly.
i = BLACK_KEYS.index(note.name)
if i == 0:
w = 18
elif i == 1:
w = 58
elif i == 2:
w = 115
elif i == 3:
w = 151
else:
w = 187
w = w + octave_offset
playing_b.append([w, tick, note])
# To find out what sort of chord is being played we have to look at both the
# white and black keys, obviously:
notes = playing_w + playing_b
notes.sort()
notenames = []
for n in notes:
notenames.append(n[2].name)
# Determine the chord
det = chords.determine(notenames)
if det != []:
det = det[0]
else:
det = ''
# And render it onto the text surface
t = font.render(det, 2, (0, 0, 0))
text.fill((255, 255, 255))
text.blit(t, (0, 0))
# Play the note
fluidsynth.play_Note(note, channel, 100)
|
python
|
def play_note(note):
global text
octave_offset = (note.octave - LOWEST) * width
if note.name in WHITE_KEYS:
w = WHITE_KEYS.index(note.name) * white_key_width
w = w + octave_offset
playing_w.append([w, tick, note])
else:
i = BLACK_KEYS.index(note.name)
if i == 0:
w = 18
elif i == 1:
w = 58
elif i == 2:
w = 115
elif i == 3:
w = 151
else:
w = 187
w = w + octave_offset
playing_b.append([w, tick, note])
notes = playing_w + playing_b
notes.sort()
notenames = []
for n in notes:
notenames.append(n[2].name)
det = chords.determine(notenames)
if det != []:
det = det[0]
else:
det = ''
t = font.render(det, 2, (0, 0, 0))
text.fill((255, 255, 255))
text.blit(t, (0, 0))
fluidsynth.play_Note(note, channel, 100)
|
[
"def",
"play_note",
"(",
"note",
")",
":",
"global",
"text",
"octave_offset",
"=",
"(",
"note",
".",
"octave",
"-",
"LOWEST",
")",
"*",
"width",
"if",
"note",
".",
"name",
"in",
"WHITE_KEYS",
":",
"# Getting the x coordinate of a white key can be done automatically",
"w",
"=",
"WHITE_KEYS",
".",
"index",
"(",
"note",
".",
"name",
")",
"*",
"white_key_width",
"w",
"=",
"w",
"+",
"octave_offset",
"# Add a list containing the x coordinate, the tick at the current time",
"# and of course the note itself to playing_w",
"playing_w",
".",
"append",
"(",
"[",
"w",
",",
"tick",
",",
"note",
"]",
")",
"else",
":",
"# For black keys I hard coded the x coordinates. It's ugly.",
"i",
"=",
"BLACK_KEYS",
".",
"index",
"(",
"note",
".",
"name",
")",
"if",
"i",
"==",
"0",
":",
"w",
"=",
"18",
"elif",
"i",
"==",
"1",
":",
"w",
"=",
"58",
"elif",
"i",
"==",
"2",
":",
"w",
"=",
"115",
"elif",
"i",
"==",
"3",
":",
"w",
"=",
"151",
"else",
":",
"w",
"=",
"187",
"w",
"=",
"w",
"+",
"octave_offset",
"playing_b",
".",
"append",
"(",
"[",
"w",
",",
"tick",
",",
"note",
"]",
")",
"# To find out what sort of chord is being played we have to look at both the",
"# white and black keys, obviously:",
"notes",
"=",
"playing_w",
"+",
"playing_b",
"notes",
".",
"sort",
"(",
")",
"notenames",
"=",
"[",
"]",
"for",
"n",
"in",
"notes",
":",
"notenames",
".",
"append",
"(",
"n",
"[",
"2",
"]",
".",
"name",
")",
"# Determine the chord",
"det",
"=",
"chords",
".",
"determine",
"(",
"notenames",
")",
"if",
"det",
"!=",
"[",
"]",
":",
"det",
"=",
"det",
"[",
"0",
"]",
"else",
":",
"det",
"=",
"''",
"# And render it onto the text surface",
"t",
"=",
"font",
".",
"render",
"(",
"det",
",",
"2",
",",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
"text",
".",
"fill",
"(",
"(",
"255",
",",
"255",
",",
"255",
")",
")",
"text",
".",
"blit",
"(",
"t",
",",
"(",
"0",
",",
"0",
")",
")",
"# Play the note",
"fluidsynth",
".",
"play_Note",
"(",
"note",
",",
"channel",
",",
"100",
")"
] |
play_note determines the coordinates of a note on the keyboard image
and sends a request to play the note to the fluidsynth server
|
[
"play_note",
"determines",
"the",
"coordinates",
"of",
"a",
"note",
"on",
"the",
"keyboard",
"image",
"and",
"sends",
"a",
"request",
"to",
"play",
"the",
"note",
"to",
"the",
"fluidsynth",
"server"
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-piano/pygame-piano.py#L116-L176
|
bspaans/python-mingus
|
mingus/containers/suite.py
|
Suite.add_composition
|
def add_composition(self, composition):
"""Add a composition to the suite.
Raise an UnexpectedObjectError when the supplied argument is not a
Composition object.
"""
if not hasattr(composition, 'tracks'):
raise UnexpectedObjectError("Object '%s' not expected. Expecting "
"a mingus.containers.Composition object." % composition)
self.compositions.append(composition)
return self
|
python
|
def add_composition(self, composition):
if not hasattr(composition, 'tracks'):
raise UnexpectedObjectError("Object '%s' not expected. Expecting "
"a mingus.containers.Composition object." % composition)
self.compositions.append(composition)
return self
|
[
"def",
"add_composition",
"(",
"self",
",",
"composition",
")",
":",
"if",
"not",
"hasattr",
"(",
"composition",
",",
"'tracks'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Object '%s' not expected. Expecting \"",
"\"a mingus.containers.Composition object.\"",
"%",
"composition",
")",
"self",
".",
"compositions",
".",
"append",
"(",
"composition",
")",
"return",
"self"
] |
Add a composition to the suite.
Raise an UnexpectedObjectError when the supplied argument is not a
Composition object.
|
[
"Add",
"a",
"composition",
"to",
"the",
"suite",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L39-L49
|
bspaans/python-mingus
|
mingus/containers/suite.py
|
Suite.set_author
|
def set_author(self, author, email=''):
"""Set the author of the suite."""
self.author = author
self.email = email
|
python
|
def set_author(self, author, email=''):
self.author = author
self.email = email
|
[
"def",
"set_author",
"(",
"self",
",",
"author",
",",
"email",
"=",
"''",
")",
":",
"self",
".",
"author",
"=",
"author",
"self",
".",
"email",
"=",
"email"
] |
Set the author of the suite.
|
[
"Set",
"the",
"author",
"of",
"the",
"suite",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L51-L54
|
bspaans/python-mingus
|
mingus/containers/suite.py
|
Suite.set_title
|
def set_title(self, title, subtitle=''):
"""Set the title and the subtitle of the suite."""
self.title = title
self.subtitle = subtitle
|
python
|
def set_title(self, title, subtitle=''):
self.title = title
self.subtitle = subtitle
|
[
"def",
"set_title",
"(",
"self",
",",
"title",
",",
"subtitle",
"=",
"''",
")",
":",
"self",
".",
"title",
"=",
"title",
"self",
".",
"subtitle",
"=",
"subtitle"
] |
Set the title and the subtitle of the suite.
|
[
"Set",
"the",
"title",
"and",
"the",
"subtitle",
"of",
"the",
"suite",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L56-L59
|
bspaans/python-mingus
|
mingus/containers/instrument.py
|
Instrument.set_range
|
def set_range(self, range):
"""Set the range of the instrument.
A range is a tuple of two Notes or note strings.
"""
if type(range[0]) == str:
range[0] = Note(range[0])
range[1] = Note(range[1])
if not hasattr(range[0], 'name'):
raise UnexpectedObjectError("Unexpected object '%s'. "
"Expecting a mingus.containers.Note object" % range[0])
self.range = range
|
python
|
def set_range(self, range):
if type(range[0]) == str:
range[0] = Note(range[0])
range[1] = Note(range[1])
if not hasattr(range[0], 'name'):
raise UnexpectedObjectError("Unexpected object '%s'. "
"Expecting a mingus.containers.Note object" % range[0])
self.range = range
|
[
"def",
"set_range",
"(",
"self",
",",
"range",
")",
":",
"if",
"type",
"(",
"range",
"[",
"0",
"]",
")",
"==",
"str",
":",
"range",
"[",
"0",
"]",
"=",
"Note",
"(",
"range",
"[",
"0",
"]",
")",
"range",
"[",
"1",
"]",
"=",
"Note",
"(",
"range",
"[",
"1",
"]",
")",
"if",
"not",
"hasattr",
"(",
"range",
"[",
"0",
"]",
",",
"'name'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Unexpected object '%s'. \"",
"\"Expecting a mingus.containers.Note object\"",
"%",
"range",
"[",
"0",
"]",
")",
"self",
".",
"range",
"=",
"range"
] |
Set the range of the instrument.
A range is a tuple of two Notes or note strings.
|
[
"Set",
"the",
"range",
"of",
"the",
"instrument",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L44-L55
|
bspaans/python-mingus
|
mingus/containers/instrument.py
|
Instrument.note_in_range
|
def note_in_range(self, note):
"""Test whether note is in the range of this Instrument.
Return True if so, False otherwise.
"""
if type(note) == str:
note = Note(note)
if not hasattr(note, 'name'):
raise UnexpectedObjectError("Unexpected object '%s'. "
"Expecting a mingus.containers.Note object" % note)
if note >= self.range[0] and note <= self.range[1]:
return True
return False
|
python
|
def note_in_range(self, note):
if type(note) == str:
note = Note(note)
if not hasattr(note, 'name'):
raise UnexpectedObjectError("Unexpected object '%s'. "
"Expecting a mingus.containers.Note object" % note)
if note >= self.range[0] and note <= self.range[1]:
return True
return False
|
[
"def",
"note_in_range",
"(",
"self",
",",
"note",
")",
":",
"if",
"type",
"(",
"note",
")",
"==",
"str",
":",
"note",
"=",
"Note",
"(",
"note",
")",
"if",
"not",
"hasattr",
"(",
"note",
",",
"'name'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Unexpected object '%s'. \"",
"\"Expecting a mingus.containers.Note object\"",
"%",
"note",
")",
"if",
"note",
">=",
"self",
".",
"range",
"[",
"0",
"]",
"and",
"note",
"<=",
"self",
".",
"range",
"[",
"1",
"]",
":",
"return",
"True",
"return",
"False"
] |
Test whether note is in the range of this Instrument.
Return True if so, False otherwise.
|
[
"Test",
"whether",
"note",
"is",
"in",
"the",
"range",
"of",
"this",
"Instrument",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L57-L69
|
bspaans/python-mingus
|
mingus/containers/instrument.py
|
Instrument.can_play_notes
|
def can_play_notes(self, notes):
"""Test if the notes lie within the range of the instrument.
Return True if so, False otherwise.
"""
if hasattr(notes, 'notes'):
notes = notes.notes
if type(notes) != list:
notes = [notes]
for n in notes:
if not self.note_in_range(n):
return False
return True
|
python
|
def can_play_notes(self, notes):
if hasattr(notes, 'notes'):
notes = notes.notes
if type(notes) != list:
notes = [notes]
for n in notes:
if not self.note_in_range(n):
return False
return True
|
[
"def",
"can_play_notes",
"(",
"self",
",",
"notes",
")",
":",
"if",
"hasattr",
"(",
"notes",
",",
"'notes'",
")",
":",
"notes",
"=",
"notes",
".",
"notes",
"if",
"type",
"(",
"notes",
")",
"!=",
"list",
":",
"notes",
"=",
"[",
"notes",
"]",
"for",
"n",
"in",
"notes",
":",
"if",
"not",
"self",
".",
"note_in_range",
"(",
"n",
")",
":",
"return",
"False",
"return",
"True"
] |
Test if the notes lie within the range of the instrument.
Return True if so, False otherwise.
|
[
"Test",
"if",
"the",
"notes",
"lie",
"within",
"the",
"range",
"of",
"the",
"instrument",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L75-L87
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.play_Note
|
def play_Note(self, note):
"""Convert a Note object to a midi event and adds it to the
track_data.
To set the channel on which to play this note, set Note.channel, the
same goes for Note.velocity.
"""
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocity' in note.dynamics:
velocity = note.dynamics['velocity']
if 'channel' in note.dynamics:
channel = note.dynamics['channel']
if hasattr(note, 'channel'):
channel = note.channel
if hasattr(note, 'velocity'):
velocity = note.velocity
if self.change_instrument:
self.set_instrument(channel, self.instrument)
self.change_instrument = False
self.track_data += self.note_on(channel, int(note) + 12, velocity)
|
python
|
def play_Note(self, note):
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocity' in note.dynamics:
velocity = note.dynamics['velocity']
if 'channel' in note.dynamics:
channel = note.dynamics['channel']
if hasattr(note, 'channel'):
channel = note.channel
if hasattr(note, 'velocity'):
velocity = note.velocity
if self.change_instrument:
self.set_instrument(channel, self.instrument)
self.change_instrument = False
self.track_data += self.note_on(channel, int(note) + 12, velocity)
|
[
"def",
"play_Note",
"(",
"self",
",",
"note",
")",
":",
"velocity",
"=",
"64",
"channel",
"=",
"1",
"if",
"hasattr",
"(",
"note",
",",
"'dynamics'",
")",
":",
"if",
"'velocity'",
"in",
"note",
".",
"dynamics",
":",
"velocity",
"=",
"note",
".",
"dynamics",
"[",
"'velocity'",
"]",
"if",
"'channel'",
"in",
"note",
".",
"dynamics",
":",
"channel",
"=",
"note",
".",
"dynamics",
"[",
"'channel'",
"]",
"if",
"hasattr",
"(",
"note",
",",
"'channel'",
")",
":",
"channel",
"=",
"note",
".",
"channel",
"if",
"hasattr",
"(",
"note",
",",
"'velocity'",
")",
":",
"velocity",
"=",
"note",
".",
"velocity",
"if",
"self",
".",
"change_instrument",
":",
"self",
".",
"set_instrument",
"(",
"channel",
",",
"self",
".",
"instrument",
")",
"self",
".",
"change_instrument",
"=",
"False",
"self",
".",
"track_data",
"+=",
"self",
".",
"note_on",
"(",
"channel",
",",
"int",
"(",
"note",
")",
"+",
"12",
",",
"velocity",
")"
] |
Convert a Note object to a midi event and adds it to the
track_data.
To set the channel on which to play this note, set Note.channel, the
same goes for Note.velocity.
|
[
"Convert",
"a",
"Note",
"object",
"to",
"a",
"midi",
"event",
"and",
"adds",
"it",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L54-L75
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.play_NoteContainer
|
def play_NoteContainer(self, notecontainer):
"""Convert a mingus.containers.NoteContainer to the equivalent MIDI
events and add it to the track_data.
Note.channel and Note.velocity can be set as well.
"""
if len(notecontainer) <= 1:
[self.play_Note(x) for x in notecontainer]
else:
self.play_Note(notecontainer[0])
self.set_deltatime(0)
[self.play_Note(x) for x in notecontainer[1:]]
|
python
|
def play_NoteContainer(self, notecontainer):
if len(notecontainer) <= 1:
[self.play_Note(x) for x in notecontainer]
else:
self.play_Note(notecontainer[0])
self.set_deltatime(0)
[self.play_Note(x) for x in notecontainer[1:]]
|
[
"def",
"play_NoteContainer",
"(",
"self",
",",
"notecontainer",
")",
":",
"if",
"len",
"(",
"notecontainer",
")",
"<=",
"1",
":",
"[",
"self",
".",
"play_Note",
"(",
"x",
")",
"for",
"x",
"in",
"notecontainer",
"]",
"else",
":",
"self",
".",
"play_Note",
"(",
"notecontainer",
"[",
"0",
"]",
")",
"self",
".",
"set_deltatime",
"(",
"0",
")",
"[",
"self",
".",
"play_Note",
"(",
"x",
")",
"for",
"x",
"in",
"notecontainer",
"[",
"1",
":",
"]",
"]"
] |
Convert a mingus.containers.NoteContainer to the equivalent MIDI
events and add it to the track_data.
Note.channel and Note.velocity can be set as well.
|
[
"Convert",
"a",
"mingus",
".",
"containers",
".",
"NoteContainer",
"to",
"the",
"equivalent",
"MIDI",
"events",
"and",
"add",
"it",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L77-L88
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.play_Bar
|
def play_Bar(self, bar):
"""Convert a Bar object to MIDI events and write them to the
track_data."""
self.set_deltatime(self.delay)
self.delay = 0
self.set_meter(bar.meter)
self.set_deltatime(0)
self.set_key(bar.key)
for x in bar:
tick = int(round((1.0 / x[1]) * 288))
if x[2] is None or len(x[2]) == 0:
self.delay += tick
else:
self.set_deltatime(self.delay)
self.delay = 0
if hasattr(x[2], 'bpm'):
self.set_deltatime(0)
self.set_tempo(x[2].bpm)
self.play_NoteContainer(x[2])
self.set_deltatime(self.int_to_varbyte(tick))
self.stop_NoteContainer(x[2])
|
python
|
def play_Bar(self, bar):
self.set_deltatime(self.delay)
self.delay = 0
self.set_meter(bar.meter)
self.set_deltatime(0)
self.set_key(bar.key)
for x in bar:
tick = int(round((1.0 / x[1]) * 288))
if x[2] is None or len(x[2]) == 0:
self.delay += tick
else:
self.set_deltatime(self.delay)
self.delay = 0
if hasattr(x[2], 'bpm'):
self.set_deltatime(0)
self.set_tempo(x[2].bpm)
self.play_NoteContainer(x[2])
self.set_deltatime(self.int_to_varbyte(tick))
self.stop_NoteContainer(x[2])
|
[
"def",
"play_Bar",
"(",
"self",
",",
"bar",
")",
":",
"self",
".",
"set_deltatime",
"(",
"self",
".",
"delay",
")",
"self",
".",
"delay",
"=",
"0",
"self",
".",
"set_meter",
"(",
"bar",
".",
"meter",
")",
"self",
".",
"set_deltatime",
"(",
"0",
")",
"self",
".",
"set_key",
"(",
"bar",
".",
"key",
")",
"for",
"x",
"in",
"bar",
":",
"tick",
"=",
"int",
"(",
"round",
"(",
"(",
"1.0",
"/",
"x",
"[",
"1",
"]",
")",
"*",
"288",
")",
")",
"if",
"x",
"[",
"2",
"]",
"is",
"None",
"or",
"len",
"(",
"x",
"[",
"2",
"]",
")",
"==",
"0",
":",
"self",
".",
"delay",
"+=",
"tick",
"else",
":",
"self",
".",
"set_deltatime",
"(",
"self",
".",
"delay",
")",
"self",
".",
"delay",
"=",
"0",
"if",
"hasattr",
"(",
"x",
"[",
"2",
"]",
",",
"'bpm'",
")",
":",
"self",
".",
"set_deltatime",
"(",
"0",
")",
"self",
".",
"set_tempo",
"(",
"x",
"[",
"2",
"]",
".",
"bpm",
")",
"self",
".",
"play_NoteContainer",
"(",
"x",
"[",
"2",
"]",
")",
"self",
".",
"set_deltatime",
"(",
"self",
".",
"int_to_varbyte",
"(",
"tick",
")",
")",
"self",
".",
"stop_NoteContainer",
"(",
"x",
"[",
"2",
"]",
")"
] |
Convert a Bar object to MIDI events and write them to the
track_data.
|
[
"Convert",
"a",
"Bar",
"object",
"to",
"MIDI",
"events",
"and",
"write",
"them",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L90-L110
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.play_Track
|
def play_Track(self, track):
"""Convert a Track object to MIDI events and write them to the
track_data."""
if hasattr(track, 'name'):
self.set_track_name(track.name)
self.delay = 0
instr = track.instrument
if hasattr(instr, 'instrument_nr'):
self.change_instrument = True
self.instrument = instr.instrument_nr
for bar in track:
self.play_Bar(bar)
|
python
|
def play_Track(self, track):
if hasattr(track, 'name'):
self.set_track_name(track.name)
self.delay = 0
instr = track.instrument
if hasattr(instr, 'instrument_nr'):
self.change_instrument = True
self.instrument = instr.instrument_nr
for bar in track:
self.play_Bar(bar)
|
[
"def",
"play_Track",
"(",
"self",
",",
"track",
")",
":",
"if",
"hasattr",
"(",
"track",
",",
"'name'",
")",
":",
"self",
".",
"set_track_name",
"(",
"track",
".",
"name",
")",
"self",
".",
"delay",
"=",
"0",
"instr",
"=",
"track",
".",
"instrument",
"if",
"hasattr",
"(",
"instr",
",",
"'instrument_nr'",
")",
":",
"self",
".",
"change_instrument",
"=",
"True",
"self",
".",
"instrument",
"=",
"instr",
".",
"instrument_nr",
"for",
"bar",
"in",
"track",
":",
"self",
".",
"play_Bar",
"(",
"bar",
")"
] |
Convert a Track object to MIDI events and write them to the
track_data.
|
[
"Convert",
"a",
"Track",
"object",
"to",
"MIDI",
"events",
"and",
"write",
"them",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L112-L123
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.stop_Note
|
def stop_Note(self, note):
"""Add a note_off event for note to event_track."""
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocity' in note.dynamics:
velocity = note.dynamics['velocity']
if 'channel' in note.dynamics:
channel = note.dynamics['channel']
if hasattr(note, 'channel'):
channel = note.channel
if hasattr(note, 'velocity'):
velocity = note.velocity
self.track_data += self.note_off(channel, int(note) + 12, velocity)
|
python
|
def stop_Note(self, note):
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocity' in note.dynamics:
velocity = note.dynamics['velocity']
if 'channel' in note.dynamics:
channel = note.dynamics['channel']
if hasattr(note, 'channel'):
channel = note.channel
if hasattr(note, 'velocity'):
velocity = note.velocity
self.track_data += self.note_off(channel, int(note) + 12, velocity)
|
[
"def",
"stop_Note",
"(",
"self",
",",
"note",
")",
":",
"velocity",
"=",
"64",
"channel",
"=",
"1",
"if",
"hasattr",
"(",
"note",
",",
"'dynamics'",
")",
":",
"if",
"'velocity'",
"in",
"note",
".",
"dynamics",
":",
"velocity",
"=",
"note",
".",
"dynamics",
"[",
"'velocity'",
"]",
"if",
"'channel'",
"in",
"note",
".",
"dynamics",
":",
"channel",
"=",
"note",
".",
"dynamics",
"[",
"'channel'",
"]",
"if",
"hasattr",
"(",
"note",
",",
"'channel'",
")",
":",
"channel",
"=",
"note",
".",
"channel",
"if",
"hasattr",
"(",
"note",
",",
"'velocity'",
")",
":",
"velocity",
"=",
"note",
".",
"velocity",
"self",
".",
"track_data",
"+=",
"self",
".",
"note_off",
"(",
"channel",
",",
"int",
"(",
"note",
")",
"+",
"12",
",",
"velocity",
")"
] |
Add a note_off event for note to event_track.
|
[
"Add",
"a",
"note_off",
"event",
"for",
"note",
"to",
"event_track",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L125-L138
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.stop_NoteContainer
|
def stop_NoteContainer(self, notecontainer):
"""Add note_off events for each note in the NoteContainer to the
track_data."""
# if there is more than one note in the container, the deltatime should
# be set back to zero after the first one has been stopped
if len(notecontainer) <= 1:
[self.stop_Note(x) for x in notecontainer]
else:
self.stop_Note(notecontainer[0])
self.set_deltatime(0)
[self.stop_Note(x) for x in notecontainer[1:]]
|
python
|
def stop_NoteContainer(self, notecontainer):
if len(notecontainer) <= 1:
[self.stop_Note(x) for x in notecontainer]
else:
self.stop_Note(notecontainer[0])
self.set_deltatime(0)
[self.stop_Note(x) for x in notecontainer[1:]]
|
[
"def",
"stop_NoteContainer",
"(",
"self",
",",
"notecontainer",
")",
":",
"# if there is more than one note in the container, the deltatime should",
"# be set back to zero after the first one has been stopped",
"if",
"len",
"(",
"notecontainer",
")",
"<=",
"1",
":",
"[",
"self",
".",
"stop_Note",
"(",
"x",
")",
"for",
"x",
"in",
"notecontainer",
"]",
"else",
":",
"self",
".",
"stop_Note",
"(",
"notecontainer",
"[",
"0",
"]",
")",
"self",
".",
"set_deltatime",
"(",
"0",
")",
"[",
"self",
".",
"stop_Note",
"(",
"x",
")",
"for",
"x",
"in",
"notecontainer",
"[",
"1",
":",
"]",
"]"
] |
Add note_off events for each note in the NoteContainer to the
track_data.
|
[
"Add",
"note_off",
"events",
"for",
"each",
"note",
"in",
"the",
"NoteContainer",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L140-L150
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.set_instrument
|
def set_instrument(self, channel, instr, bank=1):
"""Add a program change and bank select event to the track_data."""
self.track_data += self.select_bank(channel, bank)
self.track_data += self.program_change_event(channel, instr)
|
python
|
def set_instrument(self, channel, instr, bank=1):
self.track_data += self.select_bank(channel, bank)
self.track_data += self.program_change_event(channel, instr)
|
[
"def",
"set_instrument",
"(",
"self",
",",
"channel",
",",
"instr",
",",
"bank",
"=",
"1",
")",
":",
"self",
".",
"track_data",
"+=",
"self",
".",
"select_bank",
"(",
"channel",
",",
"bank",
")",
"self",
".",
"track_data",
"+=",
"self",
".",
"program_change_event",
"(",
"channel",
",",
"instr",
")"
] |
Add a program change and bank select event to the track_data.
|
[
"Add",
"a",
"program",
"change",
"and",
"bank",
"select",
"event",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L152-L155
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.header
|
def header(self):
"""Return the bytes for the header of track.
The header contains the length of the track_data, so you'll have to
call this function when you're done adding data (when you're not
using get_midi_data).
"""
chunk_size = a2b_hex('%08x' % (len(self.track_data)
+ len(self.end_of_track())))
return TRACK_HEADER + chunk_size
|
python
|
def header(self):
chunk_size = a2b_hex('%08x' % (len(self.track_data)
+ len(self.end_of_track())))
return TRACK_HEADER + chunk_size
|
[
"def",
"header",
"(",
"self",
")",
":",
"chunk_size",
"=",
"a2b_hex",
"(",
"'%08x'",
"%",
"(",
"len",
"(",
"self",
".",
"track_data",
")",
"+",
"len",
"(",
"self",
".",
"end_of_track",
"(",
")",
")",
")",
")",
"return",
"TRACK_HEADER",
"+",
"chunk_size"
] |
Return the bytes for the header of track.
The header contains the length of the track_data, so you'll have to
call this function when you're done adding data (when you're not
using get_midi_data).
|
[
"Return",
"the",
"bytes",
"for",
"the",
"header",
"of",
"track",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L157-L166
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.midi_event
|
def midi_event(self, event_type, channel, param1, param2=None):
"""Convert and return the paraters as a MIDI event in bytes."""
assert event_type < 0x80 and event_type >= 0
assert channel < 16 and channel >= 0
tc = a2b_hex('%x%x' % (event_type, channel))
if param2 is None:
params = a2b_hex('%02x' % param1)
else:
params = a2b_hex('%02x%02x' % (param1, param2))
return self.delta_time + tc + params
|
python
|
def midi_event(self, event_type, channel, param1, param2=None):
assert event_type < 0x80 and event_type >= 0
assert channel < 16 and channel >= 0
tc = a2b_hex('%x%x' % (event_type, channel))
if param2 is None:
params = a2b_hex('%02x' % param1)
else:
params = a2b_hex('%02x%02x' % (param1, param2))
return self.delta_time + tc + params
|
[
"def",
"midi_event",
"(",
"self",
",",
"event_type",
",",
"channel",
",",
"param1",
",",
"param2",
"=",
"None",
")",
":",
"assert",
"event_type",
"<",
"0x80",
"and",
"event_type",
">=",
"0",
"assert",
"channel",
"<",
"16",
"and",
"channel",
">=",
"0",
"tc",
"=",
"a2b_hex",
"(",
"'%x%x'",
"%",
"(",
"event_type",
",",
"channel",
")",
")",
"if",
"param2",
"is",
"None",
":",
"params",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"param1",
")",
"else",
":",
"params",
"=",
"a2b_hex",
"(",
"'%02x%02x'",
"%",
"(",
"param1",
",",
"param2",
")",
")",
"return",
"self",
".",
"delta_time",
"+",
"tc",
"+",
"params"
] |
Convert and return the paraters as a MIDI event in bytes.
|
[
"Convert",
"and",
"return",
"the",
"paraters",
"as",
"a",
"MIDI",
"event",
"in",
"bytes",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L175-L184
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.note_off
|
def note_off(self, channel, note, velocity):
"""Return bytes for a 'note off' event."""
return self.midi_event(NOTE_OFF, channel, note, velocity)
|
python
|
def note_off(self, channel, note, velocity):
return self.midi_event(NOTE_OFF, channel, note, velocity)
|
[
"def",
"note_off",
"(",
"self",
",",
"channel",
",",
"note",
",",
"velocity",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"NOTE_OFF",
",",
"channel",
",",
"note",
",",
"velocity",
")"
] |
Return bytes for a 'note off' event.
|
[
"Return",
"bytes",
"for",
"a",
"note",
"off",
"event",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L186-L188
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.note_on
|
def note_on(self, channel, note, velocity):
"""Return bytes for a 'note_on' event."""
return self.midi_event(NOTE_ON, channel, note, velocity)
|
python
|
def note_on(self, channel, note, velocity):
return self.midi_event(NOTE_ON, channel, note, velocity)
|
[
"def",
"note_on",
"(",
"self",
",",
"channel",
",",
"note",
",",
"velocity",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"NOTE_ON",
",",
"channel",
",",
"note",
",",
"velocity",
")"
] |
Return bytes for a 'note_on' event.
|
[
"Return",
"bytes",
"for",
"a",
"note_on",
"event",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L190-L192
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.controller_event
|
def controller_event(self, channel, contr_nr, contr_val):
"""Return the bytes for a MIDI controller event."""
return self.midi_event(CONTROLLER, channel, contr_nr, contr_val)
|
python
|
def controller_event(self, channel, contr_nr, contr_val):
return self.midi_event(CONTROLLER, channel, contr_nr, contr_val)
|
[
"def",
"controller_event",
"(",
"self",
",",
"channel",
",",
"contr_nr",
",",
"contr_val",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"CONTROLLER",
",",
"channel",
",",
"contr_nr",
",",
"contr_val",
")"
] |
Return the bytes for a MIDI controller event.
|
[
"Return",
"the",
"bytes",
"for",
"a",
"MIDI",
"controller",
"event",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L194-L196
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.set_deltatime
|
def set_deltatime(self, delta_time):
"""Set the delta_time.
Can be an integer or a variable length byte.
"""
if type(delta_time) == int:
delta_time = self.int_to_varbyte(delta_time)
self.delta_time = delta_time
|
python
|
def set_deltatime(self, delta_time):
if type(delta_time) == int:
delta_time = self.int_to_varbyte(delta_time)
self.delta_time = delta_time
|
[
"def",
"set_deltatime",
"(",
"self",
",",
"delta_time",
")",
":",
"if",
"type",
"(",
"delta_time",
")",
"==",
"int",
":",
"delta_time",
"=",
"self",
".",
"int_to_varbyte",
"(",
"delta_time",
")",
"self",
".",
"delta_time",
"=",
"delta_time"
] |
Set the delta_time.
Can be an integer or a variable length byte.
|
[
"Set",
"the",
"delta_time",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L203-L210
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.set_tempo
|
def set_tempo(self, bpm):
"""Convert the bpm to a midi event and write it to the track_data."""
self.bpm = bpm
self.track_data += self.set_tempo_event(self.bpm)
|
python
|
def set_tempo(self, bpm):
self.bpm = bpm
self.track_data += self.set_tempo_event(self.bpm)
|
[
"def",
"set_tempo",
"(",
"self",
",",
"bpm",
")",
":",
"self",
".",
"bpm",
"=",
"bpm",
"self",
".",
"track_data",
"+=",
"self",
".",
"set_tempo_event",
"(",
"self",
".",
"bpm",
")"
] |
Convert the bpm to a midi event and write it to the track_data.
|
[
"Convert",
"the",
"bpm",
"to",
"a",
"midi",
"event",
"and",
"write",
"it",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L220-L223
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.set_tempo_event
|
def set_tempo_event(self, bpm):
"""Calculate the microseconds per quarter note."""
ms_per_min = 60000000
mpqn = a2b_hex('%06x' % (ms_per_min / bpm))
return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
|
python
|
def set_tempo_event(self, bpm):
ms_per_min = 60000000
mpqn = a2b_hex('%06x' % (ms_per_min / bpm))
return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
|
[
"def",
"set_tempo_event",
"(",
"self",
",",
"bpm",
")",
":",
"ms_per_min",
"=",
"60000000",
"mpqn",
"=",
"a2b_hex",
"(",
"'%06x'",
"%",
"(",
"ms_per_min",
"/",
"bpm",
")",
")",
"return",
"self",
".",
"delta_time",
"+",
"META_EVENT",
"+",
"SET_TEMPO",
"+",
"'\\x03'",
"+",
"mpqn"
] |
Calculate the microseconds per quarter note.
|
[
"Calculate",
"the",
"microseconds",
"per",
"quarter",
"note",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L225-L229
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.time_signature_event
|
def time_signature_event(self, meter=(4, 4)):
"""Return a time signature event for meter."""
numer = a2b_hex('%02x' % meter[0])
denom = a2b_hex('%02x' % int(log(meter[1], 2)))
return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\
+ denom + '\x18\x08'
|
python
|
def time_signature_event(self, meter=(4, 4)):
numer = a2b_hex('%02x' % meter[0])
denom = a2b_hex('%02x' % int(log(meter[1], 2)))
return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\
+ denom + '\x18\x08'
|
[
"def",
"time_signature_event",
"(",
"self",
",",
"meter",
"=",
"(",
"4",
",",
"4",
")",
")",
":",
"numer",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"meter",
"[",
"0",
"]",
")",
"denom",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"int",
"(",
"log",
"(",
"meter",
"[",
"1",
"]",
",",
"2",
")",
")",
")",
"return",
"self",
".",
"delta_time",
"+",
"META_EVENT",
"+",
"TIME_SIGNATURE",
"+",
"'\\x04'",
"+",
"numer",
"+",
"denom",
"+",
"'\\x18\\x08'"
] |
Return a time signature event for meter.
|
[
"Return",
"a",
"time",
"signature",
"event",
"for",
"meter",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L235-L240
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.set_key
|
def set_key(self, key='C'):
"""Add a key signature event to the track_data."""
if isinstance(key, Key):
key = key.name[0]
self.track_data += self.key_signature_event(key)
|
python
|
def set_key(self, key='C'):
if isinstance(key, Key):
key = key.name[0]
self.track_data += self.key_signature_event(key)
|
[
"def",
"set_key",
"(",
"self",
",",
"key",
"=",
"'C'",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"Key",
")",
":",
"key",
"=",
"key",
".",
"name",
"[",
"0",
"]",
"self",
".",
"track_data",
"+=",
"self",
".",
"key_signature_event",
"(",
"key",
")"
] |
Add a key signature event to the track_data.
|
[
"Add",
"a",
"key",
"signature",
"event",
"to",
"the",
"track_data",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L242-L246
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.key_signature_event
|
def key_signature_event(self, key='C'):
"""Return the bytes for a key signature event."""
if key.islower():
val = minor_keys.index(key) - 7
mode = '\x01'
else:
val = major_keys.index(key) - 7
mode = '\x00'
if val < 0:
val = 256 + val
key = a2b_hex('%02x' % val)
return '{0}{1}{2}\x02{3}{4}'.format(self.delta_time, META_EVENT,
KEY_SIGNATURE, key, mode)
|
python
|
def key_signature_event(self, key='C'):
if key.islower():
val = minor_keys.index(key) - 7
mode = '\x01'
else:
val = major_keys.index(key) - 7
mode = '\x00'
if val < 0:
val = 256 + val
key = a2b_hex('%02x' % val)
return '{0}{1}{2}\x02{3}{4}'.format(self.delta_time, META_EVENT,
KEY_SIGNATURE, key, mode)
|
[
"def",
"key_signature_event",
"(",
"self",
",",
"key",
"=",
"'C'",
")",
":",
"if",
"key",
".",
"islower",
"(",
")",
":",
"val",
"=",
"minor_keys",
".",
"index",
"(",
"key",
")",
"-",
"7",
"mode",
"=",
"'\\x01'",
"else",
":",
"val",
"=",
"major_keys",
".",
"index",
"(",
"key",
")",
"-",
"7",
"mode",
"=",
"'\\x00'",
"if",
"val",
"<",
"0",
":",
"val",
"=",
"256",
"+",
"val",
"key",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"val",
")",
"return",
"'{0}{1}{2}\\x02{3}{4}'",
".",
"format",
"(",
"self",
".",
"delta_time",
",",
"META_EVENT",
",",
"KEY_SIGNATURE",
",",
"key",
",",
"mode",
")"
] |
Return the bytes for a key signature event.
|
[
"Return",
"the",
"bytes",
"for",
"a",
"key",
"signature",
"event",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L248-L260
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.track_name_event
|
def track_name_event(self, name):
"""Return the bytes for a track name meta event."""
l = self.int_to_varbyte(len(name))
return '\x00' + META_EVENT + TRACK_NAME + l + name
|
python
|
def track_name_event(self, name):
l = self.int_to_varbyte(len(name))
return '\x00' + META_EVENT + TRACK_NAME + l + name
|
[
"def",
"track_name_event",
"(",
"self",
",",
"name",
")",
":",
"l",
"=",
"self",
".",
"int_to_varbyte",
"(",
"len",
"(",
"name",
")",
")",
"return",
"'\\x00'",
"+",
"META_EVENT",
"+",
"TRACK_NAME",
"+",
"l",
"+",
"name"
] |
Return the bytes for a track name meta event.
|
[
"Return",
"the",
"bytes",
"for",
"a",
"track",
"name",
"meta",
"event",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L266-L269
|
bspaans/python-mingus
|
mingus/midi/midi_track.py
|
MidiTrack.int_to_varbyte
|
def int_to_varbyte(self, value):
"""Convert an integer into a variable length byte.
How it works: the bytes are stored in big-endian (significant bit
first), the highest bit of the byte (mask 0x80) is set when there
are more bytes following. The remaining 7 bits (mask 0x7F) are used
to store the value.
"""
# Warning: bit kung-fu ahead. The length of the integer in bytes
length = int(log(max(value, 1), 0x80)) + 1
# Remove the highest bit and move the bits to the right if length > 1
bytes = [value >> i * 7 & 0x7F for i in range(length)]
bytes.reverse()
# Set the first bit on every one but the last bit.
for i in range(len(bytes) - 1):
bytes[i] = bytes[i] | 0x80
return pack('%sB' % len(bytes), *bytes)
|
python
|
def int_to_varbyte(self, value):
length = int(log(max(value, 1), 0x80)) + 1
bytes = [value >> i * 7 & 0x7F for i in range(length)]
bytes.reverse()
for i in range(len(bytes) - 1):
bytes[i] = bytes[i] | 0x80
return pack('%sB' % len(bytes), *bytes)
|
[
"def",
"int_to_varbyte",
"(",
"self",
",",
"value",
")",
":",
"# Warning: bit kung-fu ahead. The length of the integer in bytes",
"length",
"=",
"int",
"(",
"log",
"(",
"max",
"(",
"value",
",",
"1",
")",
",",
"0x80",
")",
")",
"+",
"1",
"# Remove the highest bit and move the bits to the right if length > 1",
"bytes",
"=",
"[",
"value",
">>",
"i",
"*",
"7",
"&",
"0x7F",
"for",
"i",
"in",
"range",
"(",
"length",
")",
"]",
"bytes",
".",
"reverse",
"(",
")",
"# Set the first bit on every one but the last bit.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"bytes",
")",
"-",
"1",
")",
":",
"bytes",
"[",
"i",
"]",
"=",
"bytes",
"[",
"i",
"]",
"|",
"0x80",
"return",
"pack",
"(",
"'%sB'",
"%",
"len",
"(",
"bytes",
")",
",",
"*",
"bytes",
")"
] |
Convert an integer into a variable length byte.
How it works: the bytes are stored in big-endian (significant bit
first), the highest bit of the byte (mask 0x80) is set when there
are more bytes following. The remaining 7 bits (mask 0x7F) are used
to store the value.
|
[
"Convert",
"an",
"integer",
"into",
"a",
"variable",
"length",
"byte",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L271-L289
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
to_chords
|
def to_chords(progression, key='C'):
"""Convert a list of chord functions or a string to a list of chords.
Examples:
>>> to_chords(['I', 'V7'])
[['C', 'E', 'G'], ['G', 'B', 'D', 'F']]
>>> to_chords('I7')
[['C', 'E', 'G', 'B']]
Any number of accidentals can be used as prefix to augment or diminish;
for example: bIV or #I.
All the chord abbreviations in the chord module can be used as suffixes;
for example: Im7, IVdim7, etc.
You can combine prefixes and suffixes to manage complex progressions:
#vii7, #iidim7, iii7, etc.
Using 7 as suffix is ambiguous, since it is classicly used to denote the
seventh chord when talking about progressions instead of just the
dominant seventh chord. We have taken the classic route; I7 will get
you a major seventh chord. If you specifically want a dominanth seventh,
use Idom7.
"""
if type(progression) == str:
progression = [progression]
result = []
for chord in progression:
# strip preceding accidentals from the string
(roman_numeral, acc, suffix) = parse_string(chord)
# There is no roman numeral parsing, just a simple check. Sorry to
# disappoint. warning Should throw exception
if roman_numeral not in numerals:
return []
# These suffixes don't need any post processing
if suffix == '7' or suffix == '':
roman_numeral += suffix
# ahh Python. Everything is a dict.
r = chords.__dict__[roman_numeral](key)
else:
r = chords.__dict__[roman_numeral](key)
r = chords.chord_shorthand[suffix](r[0])
while acc < 0:
r = map(notes.diminish, r)
acc += 1
while acc > 0:
r = map(notes.augment, r)
acc -= 1
result.append(r)
return result
|
python
|
def to_chords(progression, key='C'):
if type(progression) == str:
progression = [progression]
result = []
for chord in progression:
(roman_numeral, acc, suffix) = parse_string(chord)
if roman_numeral not in numerals:
return []
if suffix == '7' or suffix == '':
roman_numeral += suffix
r = chords.__dict__[roman_numeral](key)
else:
r = chords.__dict__[roman_numeral](key)
r = chords.chord_shorthand[suffix](r[0])
while acc < 0:
r = map(notes.diminish, r)
acc += 1
while acc > 0:
r = map(notes.augment, r)
acc -= 1
result.append(r)
return result
|
[
"def",
"to_chords",
"(",
"progression",
",",
"key",
"=",
"'C'",
")",
":",
"if",
"type",
"(",
"progression",
")",
"==",
"str",
":",
"progression",
"=",
"[",
"progression",
"]",
"result",
"=",
"[",
"]",
"for",
"chord",
"in",
"progression",
":",
"# strip preceding accidentals from the string",
"(",
"roman_numeral",
",",
"acc",
",",
"suffix",
")",
"=",
"parse_string",
"(",
"chord",
")",
"# There is no roman numeral parsing, just a simple check. Sorry to",
"# disappoint. warning Should throw exception",
"if",
"roman_numeral",
"not",
"in",
"numerals",
":",
"return",
"[",
"]",
"# These suffixes don't need any post processing",
"if",
"suffix",
"==",
"'7'",
"or",
"suffix",
"==",
"''",
":",
"roman_numeral",
"+=",
"suffix",
"# ahh Python. Everything is a dict.",
"r",
"=",
"chords",
".",
"__dict__",
"[",
"roman_numeral",
"]",
"(",
"key",
")",
"else",
":",
"r",
"=",
"chords",
".",
"__dict__",
"[",
"roman_numeral",
"]",
"(",
"key",
")",
"r",
"=",
"chords",
".",
"chord_shorthand",
"[",
"suffix",
"]",
"(",
"r",
"[",
"0",
"]",
")",
"while",
"acc",
"<",
"0",
":",
"r",
"=",
"map",
"(",
"notes",
".",
"diminish",
",",
"r",
")",
"acc",
"+=",
"1",
"while",
"acc",
">",
"0",
":",
"r",
"=",
"map",
"(",
"notes",
".",
"augment",
",",
"r",
")",
"acc",
"-=",
"1",
"result",
".",
"append",
"(",
"r",
")",
"return",
"result"
] |
Convert a list of chord functions or a string to a list of chords.
Examples:
>>> to_chords(['I', 'V7'])
[['C', 'E', 'G'], ['G', 'B', 'D', 'F']]
>>> to_chords('I7')
[['C', 'E', 'G', 'B']]
Any number of accidentals can be used as prefix to augment or diminish;
for example: bIV or #I.
All the chord abbreviations in the chord module can be used as suffixes;
for example: Im7, IVdim7, etc.
You can combine prefixes and suffixes to manage complex progressions:
#vii7, #iidim7, iii7, etc.
Using 7 as suffix is ambiguous, since it is classicly used to denote the
seventh chord when talking about progressions instead of just the
dominant seventh chord. We have taken the classic route; I7 will get
you a major seventh chord. If you specifically want a dominanth seventh,
use Idom7.
|
[
"Convert",
"a",
"list",
"of",
"chord",
"functions",
"or",
"a",
"string",
"to",
"a",
"list",
"of",
"chords",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L38-L91
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
determine
|
def determine(chord, key, shorthand=False):
"""Determine the harmonic function of chord in key.
This function can also deal with lists of chords.
Examples:
>>> determine(['C', 'E', 'G'], 'C')
['tonic']
>>> determine(['G', 'B', 'D'], 'C')
['dominant']
>>> determine(['G', 'B', 'D', 'F'], 'C', True)
['V7']
>>> determine([['C', 'E', 'G'], ['G', 'B', 'D']], 'C', True)
[['I'], ['V']]
"""
result = []
# Handle lists of chords
if type(chord[0]) == list:
for c in chord:
result.append(determine(c, key, shorthand))
return result
func_dict = {
'I': 'tonic',
'ii': 'supertonic',
'iii': 'mediant',
'IV': 'subdominant',
'V': 'dominant',
'vi': 'submediant',
'vii': 'subtonic',
}
expected_chord = [
['I', 'M', 'M7'],
['ii', 'm', 'm7'],
['iii', 'm', 'm7'],
['IV', 'M', 'M7'],
['V', 'M', '7'],
['vi', 'm', 'm7'],
['vii', 'dim', 'm7b5'],
]
type_of_chord = chords.determine(chord, True, False, True)
for chord in type_of_chord:
name = chord[0]
# Get accidentals
a = 1
for n in chord[1:]:
if n == 'b':
name += 'b'
elif n == '#':
name += '#'
else:
break
a += 1
chord_type = chord[a:]
# Determine chord function
(interval_type, interval) = intervals.determine(key, name).split(' ')
if interval == 'unison':
func = 'I'
elif interval == 'second':
func = 'ii'
elif interval == 'third':
func = 'iii'
elif interval == 'fourth':
func = 'IV'
elif interval == 'fifth':
func = 'V'
elif interval == 'sixth':
func = 'vi'
elif interval == 'seventh':
func = 'vii'
# Check whether the chord is altered or not
for x in expected_chord:
if x[0] == func:
# Triads
if chord_type == x[1]:
if not shorthand:
func = func_dict[func]
elif chord_type == x[2]:
# Sevenths
if shorthand:
func += '7'
else:
func = func_dict[func] + ' seventh'
else:
# Other
if shorthand:
func += chord_type
else:
func = func_dict[func]\
+ chords.chord_shorthand_meaning[chord_type]
# Handle b's and #'s (for instance Dbm in key C is bII)
if shorthand:
if interval_type == 'minor':
func = 'b' + func
elif interval_type == 'augmented':
func = '#' + func
elif interval_type == 'diminished':
func = 'bb' + func
else:
if interval_type == 'minor':
func = 'minor ' + func
elif interval_type == 'augmented':
func = 'augmented ' + func
elif interval_type == 'diminished':
func = 'diminished ' + func
# Add to results
result.append(func)
return result
|
python
|
def determine(chord, key, shorthand=False):
result = []
if type(chord[0]) == list:
for c in chord:
result.append(determine(c, key, shorthand))
return result
func_dict = {
'I': 'tonic',
'ii': 'supertonic',
'iii': 'mediant',
'IV': 'subdominant',
'V': 'dominant',
'vi': 'submediant',
'vii': 'subtonic',
}
expected_chord = [
['I', 'M', 'M7'],
['ii', 'm', 'm7'],
['iii', 'm', 'm7'],
['IV', 'M', 'M7'],
['V', 'M', '7'],
['vi', 'm', 'm7'],
['vii', 'dim', 'm7b5'],
]
type_of_chord = chords.determine(chord, True, False, True)
for chord in type_of_chord:
name = chord[0]
a = 1
for n in chord[1:]:
if n == 'b':
name += 'b'
elif n == '
name += '
else:
break
a += 1
chord_type = chord[a:]
(interval_type, interval) = intervals.determine(key, name).split(' ')
if interval == 'unison':
func = 'I'
elif interval == 'second':
func = 'ii'
elif interval == 'third':
func = 'iii'
elif interval == 'fourth':
func = 'IV'
elif interval == 'fifth':
func = 'V'
elif interval == 'sixth':
func = 'vi'
elif interval == 'seventh':
func = 'vii'
for x in expected_chord:
if x[0] == func:
if chord_type == x[1]:
if not shorthand:
func = func_dict[func]
elif chord_type == x[2]:
if shorthand:
func += '7'
else:
func = func_dict[func] + ' seventh'
else:
if shorthand:
func += chord_type
else:
func = func_dict[func]\
+ chords.chord_shorthand_meaning[chord_type]
if shorthand:
if interval_type == 'minor':
func = 'b' + func
elif interval_type == 'augmented':
func = '
elif interval_type == 'diminished':
func = 'bb' + func
else:
if interval_type == 'minor':
func = 'minor ' + func
elif interval_type == 'augmented':
func = 'augmented ' + func
elif interval_type == 'diminished':
func = 'diminished ' + func
result.append(func)
return result
|
[
"def",
"determine",
"(",
"chord",
",",
"key",
",",
"shorthand",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"# Handle lists of chords",
"if",
"type",
"(",
"chord",
"[",
"0",
"]",
")",
"==",
"list",
":",
"for",
"c",
"in",
"chord",
":",
"result",
".",
"append",
"(",
"determine",
"(",
"c",
",",
"key",
",",
"shorthand",
")",
")",
"return",
"result",
"func_dict",
"=",
"{",
"'I'",
":",
"'tonic'",
",",
"'ii'",
":",
"'supertonic'",
",",
"'iii'",
":",
"'mediant'",
",",
"'IV'",
":",
"'subdominant'",
",",
"'V'",
":",
"'dominant'",
",",
"'vi'",
":",
"'submediant'",
",",
"'vii'",
":",
"'subtonic'",
",",
"}",
"expected_chord",
"=",
"[",
"[",
"'I'",
",",
"'M'",
",",
"'M7'",
"]",
",",
"[",
"'ii'",
",",
"'m'",
",",
"'m7'",
"]",
",",
"[",
"'iii'",
",",
"'m'",
",",
"'m7'",
"]",
",",
"[",
"'IV'",
",",
"'M'",
",",
"'M7'",
"]",
",",
"[",
"'V'",
",",
"'M'",
",",
"'7'",
"]",
",",
"[",
"'vi'",
",",
"'m'",
",",
"'m7'",
"]",
",",
"[",
"'vii'",
",",
"'dim'",
",",
"'m7b5'",
"]",
",",
"]",
"type_of_chord",
"=",
"chords",
".",
"determine",
"(",
"chord",
",",
"True",
",",
"False",
",",
"True",
")",
"for",
"chord",
"in",
"type_of_chord",
":",
"name",
"=",
"chord",
"[",
"0",
"]",
"# Get accidentals",
"a",
"=",
"1",
"for",
"n",
"in",
"chord",
"[",
"1",
":",
"]",
":",
"if",
"n",
"==",
"'b'",
":",
"name",
"+=",
"'b'",
"elif",
"n",
"==",
"'#'",
":",
"name",
"+=",
"'#'",
"else",
":",
"break",
"a",
"+=",
"1",
"chord_type",
"=",
"chord",
"[",
"a",
":",
"]",
"# Determine chord function",
"(",
"interval_type",
",",
"interval",
")",
"=",
"intervals",
".",
"determine",
"(",
"key",
",",
"name",
")",
".",
"split",
"(",
"' '",
")",
"if",
"interval",
"==",
"'unison'",
":",
"func",
"=",
"'I'",
"elif",
"interval",
"==",
"'second'",
":",
"func",
"=",
"'ii'",
"elif",
"interval",
"==",
"'third'",
":",
"func",
"=",
"'iii'",
"elif",
"interval",
"==",
"'fourth'",
":",
"func",
"=",
"'IV'",
"elif",
"interval",
"==",
"'fifth'",
":",
"func",
"=",
"'V'",
"elif",
"interval",
"==",
"'sixth'",
":",
"func",
"=",
"'vi'",
"elif",
"interval",
"==",
"'seventh'",
":",
"func",
"=",
"'vii'",
"# Check whether the chord is altered or not",
"for",
"x",
"in",
"expected_chord",
":",
"if",
"x",
"[",
"0",
"]",
"==",
"func",
":",
"# Triads",
"if",
"chord_type",
"==",
"x",
"[",
"1",
"]",
":",
"if",
"not",
"shorthand",
":",
"func",
"=",
"func_dict",
"[",
"func",
"]",
"elif",
"chord_type",
"==",
"x",
"[",
"2",
"]",
":",
"# Sevenths",
"if",
"shorthand",
":",
"func",
"+=",
"'7'",
"else",
":",
"func",
"=",
"func_dict",
"[",
"func",
"]",
"+",
"' seventh'",
"else",
":",
"# Other",
"if",
"shorthand",
":",
"func",
"+=",
"chord_type",
"else",
":",
"func",
"=",
"func_dict",
"[",
"func",
"]",
"+",
"chords",
".",
"chord_shorthand_meaning",
"[",
"chord_type",
"]",
"# Handle b's and #'s (for instance Dbm in key C is bII)",
"if",
"shorthand",
":",
"if",
"interval_type",
"==",
"'minor'",
":",
"func",
"=",
"'b'",
"+",
"func",
"elif",
"interval_type",
"==",
"'augmented'",
":",
"func",
"=",
"'#'",
"+",
"func",
"elif",
"interval_type",
"==",
"'diminished'",
":",
"func",
"=",
"'bb'",
"+",
"func",
"else",
":",
"if",
"interval_type",
"==",
"'minor'",
":",
"func",
"=",
"'minor '",
"+",
"func",
"elif",
"interval_type",
"==",
"'augmented'",
":",
"func",
"=",
"'augmented '",
"+",
"func",
"elif",
"interval_type",
"==",
"'diminished'",
":",
"func",
"=",
"'diminished '",
"+",
"func",
"# Add to results",
"result",
".",
"append",
"(",
"func",
")",
"return",
"result"
] |
Determine the harmonic function of chord in key.
This function can also deal with lists of chords.
Examples:
>>> determine(['C', 'E', 'G'], 'C')
['tonic']
>>> determine(['G', 'B', 'D'], 'C')
['dominant']
>>> determine(['G', 'B', 'D', 'F'], 'C', True)
['V7']
>>> determine([['C', 'E', 'G'], ['G', 'B', 'D']], 'C', True)
[['I'], ['V']]
|
[
"Determine",
"the",
"harmonic",
"function",
"of",
"chord",
"in",
"key",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L93-L206
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
parse_string
|
def parse_string(progression):
"""Return a tuple (roman numeral, accidentals, chord suffix).
Examples:
>>> parse_string('I')
('I', 0, '')
>>> parse_string('bIM7')
('I', -1, 'M7')
"""
acc = 0
roman_numeral = ''
suffix = ''
i = 0
for c in progression:
if c == '#':
acc += 1
elif c == 'b':
acc -= 1
elif c.upper() == 'I' or c.upper() == 'V':
roman_numeral += c.upper()
else:
break
i += 1
suffix = progression[i:]
return (roman_numeral, acc, suffix)
|
python
|
def parse_string(progression):
acc = 0
roman_numeral = ''
suffix = ''
i = 0
for c in progression:
if c == '
acc += 1
elif c == 'b':
acc -= 1
elif c.upper() == 'I' or c.upper() == 'V':
roman_numeral += c.upper()
else:
break
i += 1
suffix = progression[i:]
return (roman_numeral, acc, suffix)
|
[
"def",
"parse_string",
"(",
"progression",
")",
":",
"acc",
"=",
"0",
"roman_numeral",
"=",
"''",
"suffix",
"=",
"''",
"i",
"=",
"0",
"for",
"c",
"in",
"progression",
":",
"if",
"c",
"==",
"'#'",
":",
"acc",
"+=",
"1",
"elif",
"c",
"==",
"'b'",
":",
"acc",
"-=",
"1",
"elif",
"c",
".",
"upper",
"(",
")",
"==",
"'I'",
"or",
"c",
".",
"upper",
"(",
")",
"==",
"'V'",
":",
"roman_numeral",
"+=",
"c",
".",
"upper",
"(",
")",
"else",
":",
"break",
"i",
"+=",
"1",
"suffix",
"=",
"progression",
"[",
"i",
":",
"]",
"return",
"(",
"roman_numeral",
",",
"acc",
",",
"suffix",
")"
] |
Return a tuple (roman numeral, accidentals, chord suffix).
Examples:
>>> parse_string('I')
('I', 0, '')
>>> parse_string('bIM7')
('I', -1, 'M7')
|
[
"Return",
"a",
"tuple",
"(",
"roman",
"numeral",
"accidentals",
"chord",
"suffix",
")",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L208-L232
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
tuple_to_string
|
def tuple_to_string(prog_tuple):
"""Create a string from tuples returned by parse_string."""
(roman, acc, suff) = prog_tuple
if acc > 6:
acc = 0 - acc % 6
elif acc < -6:
acc = acc % 6
while acc < 0:
roman = 'b' + roman
acc += 1
while acc > 0:
roman = '#' + roman
acc -= 1
return roman + suff
|
python
|
def tuple_to_string(prog_tuple):
(roman, acc, suff) = prog_tuple
if acc > 6:
acc = 0 - acc % 6
elif acc < -6:
acc = acc % 6
while acc < 0:
roman = 'b' + roman
acc += 1
while acc > 0:
roman = '
acc -= 1
return roman + suff
|
[
"def",
"tuple_to_string",
"(",
"prog_tuple",
")",
":",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"prog_tuple",
"if",
"acc",
">",
"6",
":",
"acc",
"=",
"0",
"-",
"acc",
"%",
"6",
"elif",
"acc",
"<",
"-",
"6",
":",
"acc",
"=",
"acc",
"%",
"6",
"while",
"acc",
"<",
"0",
":",
"roman",
"=",
"'b'",
"+",
"roman",
"acc",
"+=",
"1",
"while",
"acc",
">",
"0",
":",
"roman",
"=",
"'#'",
"+",
"roman",
"acc",
"-=",
"1",
"return",
"roman",
"+",
"suff"
] |
Create a string from tuples returned by parse_string.
|
[
"Create",
"a",
"string",
"from",
"tuples",
"returned",
"by",
"parse_string",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L234-L247
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
substitute_harmonic
|
def substitute_harmonic(progression, substitute_index, ignore_suffix=False):
"""Do simple harmonic substitutions. Return a list of possible substitions
for progression[substitute_index].
If ignore_suffix is set to True the suffix of the chord being
substituted will be ignored. Otherwise only progressions without a
suffix, or with suffix '7' will be substituted.
The following table is used to convert progressions:
|| I || III ||
|| I || VI ||
|| IV || II ||
|| IV || VI ||
|| V || VII ||
"""
simple_substitutions = [('I', 'III'), ('I', 'VI'), ('IV', 'II'),
('IV', 'VI'), ('V', 'VII')]
res = []
(roman, acc, suff) = parse_string(progression[substitute_index])
if suff == '' or suff == '7' or ignore_suffix:
for subs in simple_substitutions:
r = subs[1] if roman == subs[0] else None
if r == None:
r = subs[0] if roman == subs[1] else None
if r != None:
suff = suff if suff == '7' else ''
res.append(tuple_to_string((r, acc, suff)))
return res
|
python
|
def substitute_harmonic(progression, substitute_index, ignore_suffix=False):
simple_substitutions = [('I', 'III'), ('I', 'VI'), ('IV', 'II'),
('IV', 'VI'), ('V', 'VII')]
res = []
(roman, acc, suff) = parse_string(progression[substitute_index])
if suff == '' or suff == '7' or ignore_suffix:
for subs in simple_substitutions:
r = subs[1] if roman == subs[0] else None
if r == None:
r = subs[0] if roman == subs[1] else None
if r != None:
suff = suff if suff == '7' else ''
res.append(tuple_to_string((r, acc, suff)))
return res
|
[
"def",
"substitute_harmonic",
"(",
"progression",
",",
"substitute_index",
",",
"ignore_suffix",
"=",
"False",
")",
":",
"simple_substitutions",
"=",
"[",
"(",
"'I'",
",",
"'III'",
")",
",",
"(",
"'I'",
",",
"'VI'",
")",
",",
"(",
"'IV'",
",",
"'II'",
")",
",",
"(",
"'IV'",
",",
"'VI'",
")",
",",
"(",
"'V'",
",",
"'VII'",
")",
"]",
"res",
"=",
"[",
"]",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"parse_string",
"(",
"progression",
"[",
"substitute_index",
"]",
")",
"if",
"suff",
"==",
"''",
"or",
"suff",
"==",
"'7'",
"or",
"ignore_suffix",
":",
"for",
"subs",
"in",
"simple_substitutions",
":",
"r",
"=",
"subs",
"[",
"1",
"]",
"if",
"roman",
"==",
"subs",
"[",
"0",
"]",
"else",
"None",
"if",
"r",
"==",
"None",
":",
"r",
"=",
"subs",
"[",
"0",
"]",
"if",
"roman",
"==",
"subs",
"[",
"1",
"]",
"else",
"None",
"if",
"r",
"!=",
"None",
":",
"suff",
"=",
"suff",
"if",
"suff",
"==",
"'7'",
"else",
"''",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"r",
",",
"acc",
",",
"suff",
")",
")",
")",
"return",
"res"
] |
Do simple harmonic substitutions. Return a list of possible substitions
for progression[substitute_index].
If ignore_suffix is set to True the suffix of the chord being
substituted will be ignored. Otherwise only progressions without a
suffix, or with suffix '7' will be substituted.
The following table is used to convert progressions:
|| I || III ||
|| I || VI ||
|| IV || II ||
|| IV || VI ||
|| V || VII ||
|
[
"Do",
"simple",
"harmonic",
"substitutions",
".",
"Return",
"a",
"list",
"of",
"possible",
"substitions",
"for",
"progression",
"[",
"substitute_index",
"]",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L249-L276
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
substitute_minor_for_major
|
def substitute_minor_for_major(progression, substitute_index,
ignore_suffix=False):
"""Substitute minor chords for its major equivalent.
'm' and 'm7' suffixes recognized, and ['II', 'III', 'VI'] if there is no
suffix.
Examples:
>>> substitute_minor_for_major(['VI'], 0)
['I']
>>> substitute_minor_for_major(['Vm'], 0)
['bVIIM']
>>> substitute_minor_for_major(['VIm7'], 0)
['IM7']
"""
(roman, acc, suff) = parse_string(progression[substitute_index])
res = []
# Minor to major substitution
if suff == 'm' or suff == 'm7' or suff == '' and roman in ['II', 'III', 'VI'
] or ignore_suffix:
n = skip(roman, 2)
a = interval_diff(roman, n, 3) + acc
if suff == 'm' or ignore_suffix:
res.append(tuple_to_string((n, a, 'M')))
elif suff == 'm7' or ignore_suffix:
res.append(tuple_to_string((n, a, 'M7')))
elif suff == '' or ignore_suffix:
res.append(tuple_to_string((n, a, '')))
return res
|
python
|
def substitute_minor_for_major(progression, substitute_index,
ignore_suffix=False):
(roman, acc, suff) = parse_string(progression[substitute_index])
res = []
if suff == 'm' or suff == 'm7' or suff == '' and roman in ['II', 'III', 'VI'
] or ignore_suffix:
n = skip(roman, 2)
a = interval_diff(roman, n, 3) + acc
if suff == 'm' or ignore_suffix:
res.append(tuple_to_string((n, a, 'M')))
elif suff == 'm7' or ignore_suffix:
res.append(tuple_to_string((n, a, 'M7')))
elif suff == '' or ignore_suffix:
res.append(tuple_to_string((n, a, '')))
return res
|
[
"def",
"substitute_minor_for_major",
"(",
"progression",
",",
"substitute_index",
",",
"ignore_suffix",
"=",
"False",
")",
":",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"parse_string",
"(",
"progression",
"[",
"substitute_index",
"]",
")",
"res",
"=",
"[",
"]",
"# Minor to major substitution",
"if",
"suff",
"==",
"'m'",
"or",
"suff",
"==",
"'m7'",
"or",
"suff",
"==",
"''",
"and",
"roman",
"in",
"[",
"'II'",
",",
"'III'",
",",
"'VI'",
"]",
"or",
"ignore_suffix",
":",
"n",
"=",
"skip",
"(",
"roman",
",",
"2",
")",
"a",
"=",
"interval_diff",
"(",
"roman",
",",
"n",
",",
"3",
")",
"+",
"acc",
"if",
"suff",
"==",
"'m'",
"or",
"ignore_suffix",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'M'",
")",
")",
")",
"elif",
"suff",
"==",
"'m7'",
"or",
"ignore_suffix",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'M7'",
")",
")",
")",
"elif",
"suff",
"==",
"''",
"or",
"ignore_suffix",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"''",
")",
")",
")",
"return",
"res"
] |
Substitute minor chords for its major equivalent.
'm' and 'm7' suffixes recognized, and ['II', 'III', 'VI'] if there is no
suffix.
Examples:
>>> substitute_minor_for_major(['VI'], 0)
['I']
>>> substitute_minor_for_major(['Vm'], 0)
['bVIIM']
>>> substitute_minor_for_major(['VIm7'], 0)
['IM7']
|
[
"Substitute",
"minor",
"chords",
"for",
"its",
"major",
"equivalent",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L278-L307
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
substitute_diminished_for_diminished
|
def substitute_diminished_for_diminished(progression, substitute_index,
ignore_suffix=False):
"""Substitute a diminished chord for another diminished chord.
'dim' and 'dim7' suffixes recognized, and 'VI' if there is no suffix.
Example:
>>> substitute_diminished_for_diminished(['VII'], 0)
['IIdim', 'bIVdim', 'bbVIdim']
"""
(roman, acc, suff) = parse_string(progression[substitute_index])
res = []
# Diminished progressions
if suff == 'dim7' or suff == 'dim' or suff == '' and roman in ['VII']\
or ignore_suffix:
if suff == '':
suff = 'dim'
# Add diminished chord
last = roman
for x in range(3):
next = skip(last, 2)
acc += interval_diff(last, next, 3)
res.append(tuple_to_string((next, acc, suff)))
last = next
return res
|
python
|
def substitute_diminished_for_diminished(progression, substitute_index,
ignore_suffix=False):
(roman, acc, suff) = parse_string(progression[substitute_index])
res = []
if suff == 'dim7' or suff == 'dim' or suff == '' and roman in ['VII']\
or ignore_suffix:
if suff == '':
suff = 'dim'
last = roman
for x in range(3):
next = skip(last, 2)
acc += interval_diff(last, next, 3)
res.append(tuple_to_string((next, acc, suff)))
last = next
return res
|
[
"def",
"substitute_diminished_for_diminished",
"(",
"progression",
",",
"substitute_index",
",",
"ignore_suffix",
"=",
"False",
")",
":",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"parse_string",
"(",
"progression",
"[",
"substitute_index",
"]",
")",
"res",
"=",
"[",
"]",
"# Diminished progressions",
"if",
"suff",
"==",
"'dim7'",
"or",
"suff",
"==",
"'dim'",
"or",
"suff",
"==",
"''",
"and",
"roman",
"in",
"[",
"'VII'",
"]",
"or",
"ignore_suffix",
":",
"if",
"suff",
"==",
"''",
":",
"suff",
"=",
"'dim'",
"# Add diminished chord",
"last",
"=",
"roman",
"for",
"x",
"in",
"range",
"(",
"3",
")",
":",
"next",
"=",
"skip",
"(",
"last",
",",
"2",
")",
"acc",
"+=",
"interval_diff",
"(",
"last",
",",
"next",
",",
"3",
")",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"next",
",",
"acc",
",",
"suff",
")",
")",
")",
"last",
"=",
"next",
"return",
"res"
] |
Substitute a diminished chord for another diminished chord.
'dim' and 'dim7' suffixes recognized, and 'VI' if there is no suffix.
Example:
>>> substitute_diminished_for_diminished(['VII'], 0)
['IIdim', 'bIVdim', 'bbVIdim']
|
[
"Substitute",
"a",
"diminished",
"chord",
"for",
"another",
"diminished",
"chord",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L338-L364
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
substitute
|
def substitute(progression, substitute_index, depth=0):
"""Give a list of possible substitutions for progression[substitute_index].
If depth > 0 the substitutions of each result will be recursively added
as well.
Example:
>>> substitute(['I', 'IV', 'V', 'I'], 0)
['III', 'III7', 'VI', 'VI7', 'I7']
"""
res = []
simple_substitutions = [
('I', 'III'),
('I', 'VI'),
('IV', 'II'),
('IV', 'VI'),
('V', 'VII'),
('V', 'VIIdim7'),
('V', 'IIdim7'),
('V', 'IVdim7'),
('V', 'bVIIdim7'),
]
p = progression[substitute_index]
(roman, acc, suff) = parse_string(p)
# Do the simple harmonic substitutions
if suff == '' or suff == '7':
for subs in simple_substitutions:
r = None
if roman == subs[0]:
r = subs[1]
elif roman == subs[1]:
r = subs[0]
if r != None:
res.append(tuple_to_string((r, acc, '')))
# Add seventh or triad depending on r
if r[-1] != '7':
res.append(tuple_to_string((r, acc, '7')))
else:
res.append(tuple_to_string((r[:-1], acc, '')))
if suff == '' or suff == 'M' or suff == 'm':
res.append(tuple_to_string((roman, acc, suff + '7')))
if suff == 'm' or suff == 'm7':
n = skip(roman, 2)
a = interval_diff(roman, n, 3) + acc
res.append(tuple_to_string((n, a, 'M')))
res.append(tuple_to_string((n, a, 'M7')))
# Major to minor substitution
if suff == 'M' or suff == 'M7':
n = skip(roman, 5)
a = interval_diff(roman, n, 9) + acc
res.append(tuple_to_string((n, a, 'm')))
res.append(tuple_to_string((n, a, 'm7')))
if suff == 'dim7' or suff == 'dim':
# Add the corresponding dominant seventh
res.append(tuple_to_string((skip(roman, 5), acc, 'dom7')))
n = skip(roman, 1)
res.append(tuple_to_string((n, acc + interval_diff(roman, n, 1),
'dom7')))
# Add diminished chord
last = roman
for x in range(4):
next = skip(last, 2)
acc += interval_diff(last, next, 3)
res.append(tuple_to_string((next, acc, suff)))
last = next
res2 = []
if depth > 0:
for x in res:
new_progr = progression
new_progr[substitute_index] = x
res2 += substitute(new_progr, substitute_index, depth - 1)
return res + res2
|
python
|
def substitute(progression, substitute_index, depth=0):
res = []
simple_substitutions = [
('I', 'III'),
('I', 'VI'),
('IV', 'II'),
('IV', 'VI'),
('V', 'VII'),
('V', 'VIIdim7'),
('V', 'IIdim7'),
('V', 'IVdim7'),
('V', 'bVIIdim7'),
]
p = progression[substitute_index]
(roman, acc, suff) = parse_string(p)
if suff == '' or suff == '7':
for subs in simple_substitutions:
r = None
if roman == subs[0]:
r = subs[1]
elif roman == subs[1]:
r = subs[0]
if r != None:
res.append(tuple_to_string((r, acc, '')))
if r[-1] != '7':
res.append(tuple_to_string((r, acc, '7')))
else:
res.append(tuple_to_string((r[:-1], acc, '')))
if suff == '' or suff == 'M' or suff == 'm':
res.append(tuple_to_string((roman, acc, suff + '7')))
if suff == 'm' or suff == 'm7':
n = skip(roman, 2)
a = interval_diff(roman, n, 3) + acc
res.append(tuple_to_string((n, a, 'M')))
res.append(tuple_to_string((n, a, 'M7')))
if suff == 'M' or suff == 'M7':
n = skip(roman, 5)
a = interval_diff(roman, n, 9) + acc
res.append(tuple_to_string((n, a, 'm')))
res.append(tuple_to_string((n, a, 'm7')))
if suff == 'dim7' or suff == 'dim':
res.append(tuple_to_string((skip(roman, 5), acc, 'dom7')))
n = skip(roman, 1)
res.append(tuple_to_string((n, acc + interval_diff(roman, n, 1),
'dom7')))
last = roman
for x in range(4):
next = skip(last, 2)
acc += interval_diff(last, next, 3)
res.append(tuple_to_string((next, acc, suff)))
last = next
res2 = []
if depth > 0:
for x in res:
new_progr = progression
new_progr[substitute_index] = x
res2 += substitute(new_progr, substitute_index, depth - 1)
return res + res2
|
[
"def",
"substitute",
"(",
"progression",
",",
"substitute_index",
",",
"depth",
"=",
"0",
")",
":",
"res",
"=",
"[",
"]",
"simple_substitutions",
"=",
"[",
"(",
"'I'",
",",
"'III'",
")",
",",
"(",
"'I'",
",",
"'VI'",
")",
",",
"(",
"'IV'",
",",
"'II'",
")",
",",
"(",
"'IV'",
",",
"'VI'",
")",
",",
"(",
"'V'",
",",
"'VII'",
")",
",",
"(",
"'V'",
",",
"'VIIdim7'",
")",
",",
"(",
"'V'",
",",
"'IIdim7'",
")",
",",
"(",
"'V'",
",",
"'IVdim7'",
")",
",",
"(",
"'V'",
",",
"'bVIIdim7'",
")",
",",
"]",
"p",
"=",
"progression",
"[",
"substitute_index",
"]",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"parse_string",
"(",
"p",
")",
"# Do the simple harmonic substitutions",
"if",
"suff",
"==",
"''",
"or",
"suff",
"==",
"'7'",
":",
"for",
"subs",
"in",
"simple_substitutions",
":",
"r",
"=",
"None",
"if",
"roman",
"==",
"subs",
"[",
"0",
"]",
":",
"r",
"=",
"subs",
"[",
"1",
"]",
"elif",
"roman",
"==",
"subs",
"[",
"1",
"]",
":",
"r",
"=",
"subs",
"[",
"0",
"]",
"if",
"r",
"!=",
"None",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"r",
",",
"acc",
",",
"''",
")",
")",
")",
"# Add seventh or triad depending on r",
"if",
"r",
"[",
"-",
"1",
"]",
"!=",
"'7'",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"r",
",",
"acc",
",",
"'7'",
")",
")",
")",
"else",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"r",
"[",
":",
"-",
"1",
"]",
",",
"acc",
",",
"''",
")",
")",
")",
"if",
"suff",
"==",
"''",
"or",
"suff",
"==",
"'M'",
"or",
"suff",
"==",
"'m'",
":",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"roman",
",",
"acc",
",",
"suff",
"+",
"'7'",
")",
")",
")",
"if",
"suff",
"==",
"'m'",
"or",
"suff",
"==",
"'m7'",
":",
"n",
"=",
"skip",
"(",
"roman",
",",
"2",
")",
"a",
"=",
"interval_diff",
"(",
"roman",
",",
"n",
",",
"3",
")",
"+",
"acc",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'M'",
")",
")",
")",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'M7'",
")",
")",
")",
"# Major to minor substitution",
"if",
"suff",
"==",
"'M'",
"or",
"suff",
"==",
"'M7'",
":",
"n",
"=",
"skip",
"(",
"roman",
",",
"5",
")",
"a",
"=",
"interval_diff",
"(",
"roman",
",",
"n",
",",
"9",
")",
"+",
"acc",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'m'",
")",
")",
")",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"a",
",",
"'m7'",
")",
")",
")",
"if",
"suff",
"==",
"'dim7'",
"or",
"suff",
"==",
"'dim'",
":",
"# Add the corresponding dominant seventh",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"skip",
"(",
"roman",
",",
"5",
")",
",",
"acc",
",",
"'dom7'",
")",
")",
")",
"n",
"=",
"skip",
"(",
"roman",
",",
"1",
")",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"n",
",",
"acc",
"+",
"interval_diff",
"(",
"roman",
",",
"n",
",",
"1",
")",
",",
"'dom7'",
")",
")",
")",
"# Add diminished chord",
"last",
"=",
"roman",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"next",
"=",
"skip",
"(",
"last",
",",
"2",
")",
"acc",
"+=",
"interval_diff",
"(",
"last",
",",
"next",
",",
"3",
")",
"res",
".",
"append",
"(",
"tuple_to_string",
"(",
"(",
"next",
",",
"acc",
",",
"suff",
")",
")",
")",
"last",
"=",
"next",
"res2",
"=",
"[",
"]",
"if",
"depth",
">",
"0",
":",
"for",
"x",
"in",
"res",
":",
"new_progr",
"=",
"progression",
"new_progr",
"[",
"substitute_index",
"]",
"=",
"x",
"res2",
"+=",
"substitute",
"(",
"new_progr",
",",
"substitute_index",
",",
"depth",
"-",
"1",
")",
"return",
"res",
"+",
"res2"
] |
Give a list of possible substitutions for progression[substitute_index].
If depth > 0 the substitutions of each result will be recursively added
as well.
Example:
>>> substitute(['I', 'IV', 'V', 'I'], 0)
['III', 'III7', 'VI', 'VI7', 'I7']
|
[
"Give",
"a",
"list",
"of",
"possible",
"substitutions",
"for",
"progression",
"[",
"substitute_index",
"]",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L387-L466
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
interval_diff
|
def interval_diff(progression1, progression2, interval):
"""Return the number of half steps progression2 needs to be diminished or
augmented until the interval between progression1 and progression2 is
interval."""
i = numeral_intervals[numerals.index(progression1)]
j = numeral_intervals[numerals.index(progression2)]
acc = 0
if j < i:
j += 12
while j - i > interval:
acc -= 1
j -= 1
while j - i < interval:
acc += 1
j += 1
return acc
|
python
|
def interval_diff(progression1, progression2, interval):
i = numeral_intervals[numerals.index(progression1)]
j = numeral_intervals[numerals.index(progression2)]
acc = 0
if j < i:
j += 12
while j - i > interval:
acc -= 1
j -= 1
while j - i < interval:
acc += 1
j += 1
return acc
|
[
"def",
"interval_diff",
"(",
"progression1",
",",
"progression2",
",",
"interval",
")",
":",
"i",
"=",
"numeral_intervals",
"[",
"numerals",
".",
"index",
"(",
"progression1",
")",
"]",
"j",
"=",
"numeral_intervals",
"[",
"numerals",
".",
"index",
"(",
"progression2",
")",
"]",
"acc",
"=",
"0",
"if",
"j",
"<",
"i",
":",
"j",
"+=",
"12",
"while",
"j",
"-",
"i",
">",
"interval",
":",
"acc",
"-=",
"1",
"j",
"-=",
"1",
"while",
"j",
"-",
"i",
"<",
"interval",
":",
"acc",
"+=",
"1",
"j",
"+=",
"1",
"return",
"acc"
] |
Return the number of half steps progression2 needs to be diminished or
augmented until the interval between progression1 and progression2 is
interval.
|
[
"Return",
"the",
"number",
"of",
"half",
"steps",
"progression2",
"needs",
"to",
"be",
"diminished",
"or",
"augmented",
"until",
"the",
"interval",
"between",
"progression1",
"and",
"progression2",
"is",
"interval",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L468-L483
|
bspaans/python-mingus
|
mingus/core/progressions.py
|
skip
|
def skip(roman_numeral, skip=1):
"""Skip the given places to the next roman numeral.
Examples:
>>> skip('I')
'II'
>>> skip('VII')
'I'
>>> skip('I', 2)
'III'
"""
i = numerals.index(roman_numeral) + skip
return numerals[i % 7]
|
python
|
def skip(roman_numeral, skip=1):
i = numerals.index(roman_numeral) + skip
return numerals[i % 7]
|
[
"def",
"skip",
"(",
"roman_numeral",
",",
"skip",
"=",
"1",
")",
":",
"i",
"=",
"numerals",
".",
"index",
"(",
"roman_numeral",
")",
"+",
"skip",
"return",
"numerals",
"[",
"i",
"%",
"7",
"]"
] |
Skip the given places to the next roman numeral.
Examples:
>>> skip('I')
'II'
>>> skip('VII')
'I'
>>> skip('I', 2)
'III'
|
[
"Skip",
"the",
"given",
"places",
"to",
"the",
"next",
"roman",
"numeral",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L485-L497
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.add_note
|
def add_note(self, note, octave=None, dynamics={}):
"""Add a note to the container and sorts the notes from low to high.
The note can either be a string, in which case you could also use
the octave and dynamics arguments, or a Note object.
"""
if type(note) == str:
if octave is not None:
note = Note(note, octave, dynamics)
elif len(self.notes) == 0:
note = Note(note, 4, dynamics)
else:
if Note(note, self.notes[-1].octave) < self.notes[-1]:
note = Note(note, self.notes[-1].octave + 1, dynamics)
else:
note = Note(note, self.notes[-1].octave, dynamics)
if not hasattr(note, 'name'):
raise UnexpectedObjectError("Object '%s' was not expected. "
"Expecting a mingus.containers.Note object." % note)
if note not in self.notes:
self.notes.append(note)
self.notes.sort()
return self.notes
|
python
|
def add_note(self, note, octave=None, dynamics={}):
if type(note) == str:
if octave is not None:
note = Note(note, octave, dynamics)
elif len(self.notes) == 0:
note = Note(note, 4, dynamics)
else:
if Note(note, self.notes[-1].octave) < self.notes[-1]:
note = Note(note, self.notes[-1].octave + 1, dynamics)
else:
note = Note(note, self.notes[-1].octave, dynamics)
if not hasattr(note, 'name'):
raise UnexpectedObjectError("Object '%s' was not expected. "
"Expecting a mingus.containers.Note object." % note)
if note not in self.notes:
self.notes.append(note)
self.notes.sort()
return self.notes
|
[
"def",
"add_note",
"(",
"self",
",",
"note",
",",
"octave",
"=",
"None",
",",
"dynamics",
"=",
"{",
"}",
")",
":",
"if",
"type",
"(",
"note",
")",
"==",
"str",
":",
"if",
"octave",
"is",
"not",
"None",
":",
"note",
"=",
"Note",
"(",
"note",
",",
"octave",
",",
"dynamics",
")",
"elif",
"len",
"(",
"self",
".",
"notes",
")",
"==",
"0",
":",
"note",
"=",
"Note",
"(",
"note",
",",
"4",
",",
"dynamics",
")",
"else",
":",
"if",
"Note",
"(",
"note",
",",
"self",
".",
"notes",
"[",
"-",
"1",
"]",
".",
"octave",
")",
"<",
"self",
".",
"notes",
"[",
"-",
"1",
"]",
":",
"note",
"=",
"Note",
"(",
"note",
",",
"self",
".",
"notes",
"[",
"-",
"1",
"]",
".",
"octave",
"+",
"1",
",",
"dynamics",
")",
"else",
":",
"note",
"=",
"Note",
"(",
"note",
",",
"self",
".",
"notes",
"[",
"-",
"1",
"]",
".",
"octave",
",",
"dynamics",
")",
"if",
"not",
"hasattr",
"(",
"note",
",",
"'name'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Object '%s' was not expected. \"",
"\"Expecting a mingus.containers.Note object.\"",
"%",
"note",
")",
"if",
"note",
"not",
"in",
"self",
".",
"notes",
":",
"self",
".",
"notes",
".",
"append",
"(",
"note",
")",
"self",
".",
"notes",
".",
"sort",
"(",
")",
"return",
"self",
".",
"notes"
] |
Add a note to the container and sorts the notes from low to high.
The note can either be a string, in which case you could also use
the octave and dynamics arguments, or a Note object.
|
[
"Add",
"a",
"note",
"to",
"the",
"container",
"and",
"sorts",
"the",
"notes",
"from",
"low",
"to",
"high",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L45-L67
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.add_notes
|
def add_notes(self, notes):
"""Feed notes to self.add_note.
The notes can either be an other NoteContainer, a list of Note
objects or strings or a list of lists formatted like this:
>>> notes = [['C', 5], ['E', 5], ['G', 6]]
or even:
>>> notes = [['C', 5, {'volume': 20}], ['E', 6, {'volume': 20}]]
"""
if hasattr(notes, 'notes'):
for x in notes.notes:
self.add_note(x)
return self.notes
elif hasattr(notes, 'name'):
self.add_note(notes)
return self.notes
elif type(notes) == str:
self.add_note(notes)
return self.notes
for x in notes:
if type(x) == list and len(x) != 1:
if len(x) == 2:
self.add_note(x[0], x[1])
else:
self.add_note(x[0], x[1], x[2])
else:
self.add_note(x)
return self.notes
|
python
|
def add_notes(self, notes):
if hasattr(notes, 'notes'):
for x in notes.notes:
self.add_note(x)
return self.notes
elif hasattr(notes, 'name'):
self.add_note(notes)
return self.notes
elif type(notes) == str:
self.add_note(notes)
return self.notes
for x in notes:
if type(x) == list and len(x) != 1:
if len(x) == 2:
self.add_note(x[0], x[1])
else:
self.add_note(x[0], x[1], x[2])
else:
self.add_note(x)
return self.notes
|
[
"def",
"add_notes",
"(",
"self",
",",
"notes",
")",
":",
"if",
"hasattr",
"(",
"notes",
",",
"'notes'",
")",
":",
"for",
"x",
"in",
"notes",
".",
"notes",
":",
"self",
".",
"add_note",
"(",
"x",
")",
"return",
"self",
".",
"notes",
"elif",
"hasattr",
"(",
"notes",
",",
"'name'",
")",
":",
"self",
".",
"add_note",
"(",
"notes",
")",
"return",
"self",
".",
"notes",
"elif",
"type",
"(",
"notes",
")",
"==",
"str",
":",
"self",
".",
"add_note",
"(",
"notes",
")",
"return",
"self",
".",
"notes",
"for",
"x",
"in",
"notes",
":",
"if",
"type",
"(",
"x",
")",
"==",
"list",
"and",
"len",
"(",
"x",
")",
"!=",
"1",
":",
"if",
"len",
"(",
"x",
")",
"==",
"2",
":",
"self",
".",
"add_note",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
")",
"else",
":",
"self",
".",
"add_note",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
",",
"x",
"[",
"2",
"]",
")",
"else",
":",
"self",
".",
"add_note",
"(",
"x",
")",
"return",
"self",
".",
"notes"
] |
Feed notes to self.add_note.
The notes can either be an other NoteContainer, a list of Note
objects or strings or a list of lists formatted like this:
>>> notes = [['C', 5], ['E', 5], ['G', 6]]
or even:
>>> notes = [['C', 5, {'volume': 20}], ['E', 6, {'volume': 20}]]
|
[
"Feed",
"notes",
"to",
"self",
".",
"add_note",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L69-L97
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.from_chord_shorthand
|
def from_chord_shorthand(self, shorthand):
"""Empty the container and add the notes in the shorthand.
See mingus.core.chords.from_shorthand for an up to date list of
recognized format.
Example:
>>> NoteContainer().from_chord_shorthand('Am')
['A-4', 'C-5', 'E-5']
"""
self.empty()
self.add_notes(chords.from_shorthand(shorthand))
return self
|
python
|
def from_chord_shorthand(self, shorthand):
self.empty()
self.add_notes(chords.from_shorthand(shorthand))
return self
|
[
"def",
"from_chord_shorthand",
"(",
"self",
",",
"shorthand",
")",
":",
"self",
".",
"empty",
"(",
")",
"self",
".",
"add_notes",
"(",
"chords",
".",
"from_shorthand",
"(",
"shorthand",
")",
")",
"return",
"self"
] |
Empty the container and add the notes in the shorthand.
See mingus.core.chords.from_shorthand for an up to date list of
recognized format.
Example:
>>> NoteContainer().from_chord_shorthand('Am')
['A-4', 'C-5', 'E-5']
|
[
"Empty",
"the",
"container",
"and",
"add",
"the",
"notes",
"in",
"the",
"shorthand",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L103-L115
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.from_interval
|
def from_interval(self, startnote, shorthand, up=True):
"""Shortcut to from_interval_shorthand."""
return self.from_interval_shorthand(startnote, shorthand, up)
|
python
|
def from_interval(self, startnote, shorthand, up=True):
return self.from_interval_shorthand(startnote, shorthand, up)
|
[
"def",
"from_interval",
"(",
"self",
",",
"startnote",
",",
"shorthand",
",",
"up",
"=",
"True",
")",
":",
"return",
"self",
".",
"from_interval_shorthand",
"(",
"startnote",
",",
"shorthand",
",",
"up",
")"
] |
Shortcut to from_interval_shorthand.
|
[
"Shortcut",
"to",
"from_interval_shorthand",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L117-L119
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.from_interval_shorthand
|
def from_interval_shorthand(self, startnote, shorthand, up=True):
"""Empty the container and add the note described in the startnote and
shorthand.
See core.intervals for the recognized format.
Examples:
>>> nc = NoteContainer()
>>> nc.from_interval_shorthand('C', '5')
['C-4', 'G-4']
>>> nc.from_interval_shorthand('C', '5', False)
['F-3', 'C-4']
"""
self.empty()
if type(startnote) == str:
startnote = Note(startnote)
n = Note(startnote.name, startnote.octave, startnote.dynamics)
n.transpose(shorthand, up)
self.add_notes([startnote, n])
return self
|
python
|
def from_interval_shorthand(self, startnote, shorthand, up=True):
self.empty()
if type(startnote) == str:
startnote = Note(startnote)
n = Note(startnote.name, startnote.octave, startnote.dynamics)
n.transpose(shorthand, up)
self.add_notes([startnote, n])
return self
|
[
"def",
"from_interval_shorthand",
"(",
"self",
",",
"startnote",
",",
"shorthand",
",",
"up",
"=",
"True",
")",
":",
"self",
".",
"empty",
"(",
")",
"if",
"type",
"(",
"startnote",
")",
"==",
"str",
":",
"startnote",
"=",
"Note",
"(",
"startnote",
")",
"n",
"=",
"Note",
"(",
"startnote",
".",
"name",
",",
"startnote",
".",
"octave",
",",
"startnote",
".",
"dynamics",
")",
"n",
".",
"transpose",
"(",
"shorthand",
",",
"up",
")",
"self",
".",
"add_notes",
"(",
"[",
"startnote",
",",
"n",
"]",
")",
"return",
"self"
] |
Empty the container and add the note described in the startnote and
shorthand.
See core.intervals for the recognized format.
Examples:
>>> nc = NoteContainer()
>>> nc.from_interval_shorthand('C', '5')
['C-4', 'G-4']
>>> nc.from_interval_shorthand('C', '5', False)
['F-3', 'C-4']
|
[
"Empty",
"the",
"container",
"and",
"add",
"the",
"note",
"described",
"in",
"the",
"startnote",
"and",
"shorthand",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L121-L140
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.from_progression_shorthand
|
def from_progression_shorthand(self, shorthand, key='C'):
"""Empty the container and add the notes described in the progressions
shorthand (eg. 'IIm6', 'V7', etc).
See mingus.core.progressions for all the recognized format.
Example:
>>> NoteContainer().from_progression_shorthand('VI')
['A-4', 'C-5', 'E-5']
"""
self.empty()
chords = progressions.to_chords(shorthand, key)
# warning Throw error, not a valid shorthand
if chords == []:
return False
notes = chords[0]
self.add_notes(notes)
return self
|
python
|
def from_progression_shorthand(self, shorthand, key='C'):
self.empty()
chords = progressions.to_chords(shorthand, key)
if chords == []:
return False
notes = chords[0]
self.add_notes(notes)
return self
|
[
"def",
"from_progression_shorthand",
"(",
"self",
",",
"shorthand",
",",
"key",
"=",
"'C'",
")",
":",
"self",
".",
"empty",
"(",
")",
"chords",
"=",
"progressions",
".",
"to_chords",
"(",
"shorthand",
",",
"key",
")",
"# warning Throw error, not a valid shorthand",
"if",
"chords",
"==",
"[",
"]",
":",
"return",
"False",
"notes",
"=",
"chords",
"[",
"0",
"]",
"self",
".",
"add_notes",
"(",
"notes",
")",
"return",
"self"
] |
Empty the container and add the notes described in the progressions
shorthand (eg. 'IIm6', 'V7', etc).
See mingus.core.progressions for all the recognized format.
Example:
>>> NoteContainer().from_progression_shorthand('VI')
['A-4', 'C-5', 'E-5']
|
[
"Empty",
"the",
"container",
"and",
"add",
"the",
"notes",
"described",
"in",
"the",
"progressions",
"shorthand",
"(",
"eg",
".",
"IIm6",
"V7",
"etc",
")",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L146-L164
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.remove_note
|
def remove_note(self, note, octave=-1):
"""Remove note from container.
The note can either be a Note object or a string representing the
note's name. If no specific octave is given, the note gets removed
in every octave.
"""
res = []
for x in self.notes:
if type(note) == str:
if x.name != note:
res.append(x)
else:
if x.octave != octave and octave != -1:
res.append(x)
else:
if x != note:
res.append(x)
self.notes = res
return res
|
python
|
def remove_note(self, note, octave=-1):
res = []
for x in self.notes:
if type(note) == str:
if x.name != note:
res.append(x)
else:
if x.octave != octave and octave != -1:
res.append(x)
else:
if x != note:
res.append(x)
self.notes = res
return res
|
[
"def",
"remove_note",
"(",
"self",
",",
"note",
",",
"octave",
"=",
"-",
"1",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"notes",
":",
"if",
"type",
"(",
"note",
")",
"==",
"str",
":",
"if",
"x",
".",
"name",
"!=",
"note",
":",
"res",
".",
"append",
"(",
"x",
")",
"else",
":",
"if",
"x",
".",
"octave",
"!=",
"octave",
"and",
"octave",
"!=",
"-",
"1",
":",
"res",
".",
"append",
"(",
"x",
")",
"else",
":",
"if",
"x",
"!=",
"note",
":",
"res",
".",
"append",
"(",
"x",
")",
"self",
".",
"notes",
"=",
"res",
"return",
"res"
] |
Remove note from container.
The note can either be a Note object or a string representing the
note's name. If no specific octave is given, the note gets removed
in every octave.
|
[
"Remove",
"note",
"from",
"container",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L213-L232
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.remove_notes
|
def remove_notes(self, notes):
"""Remove notes from the containers.
This function accepts a list of Note objects or notes as strings and
also single strings or Note objects.
"""
if type(notes) == str:
return self.remove_note(notes)
elif hasattr(notes, 'name'):
return self.remove_note(notes)
else:
map(lambda x: self.remove_note(x), notes)
return self.notes
|
python
|
def remove_notes(self, notes):
if type(notes) == str:
return self.remove_note(notes)
elif hasattr(notes, 'name'):
return self.remove_note(notes)
else:
map(lambda x: self.remove_note(x), notes)
return self.notes
|
[
"def",
"remove_notes",
"(",
"self",
",",
"notes",
")",
":",
"if",
"type",
"(",
"notes",
")",
"==",
"str",
":",
"return",
"self",
".",
"remove_note",
"(",
"notes",
")",
"elif",
"hasattr",
"(",
"notes",
",",
"'name'",
")",
":",
"return",
"self",
".",
"remove_note",
"(",
"notes",
")",
"else",
":",
"map",
"(",
"lambda",
"x",
":",
"self",
".",
"remove_note",
"(",
"x",
")",
",",
"notes",
")",
"return",
"self",
".",
"notes"
] |
Remove notes from the containers.
This function accepts a list of Note objects or notes as strings and
also single strings or Note objects.
|
[
"Remove",
"notes",
"from",
"the",
"containers",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L234-L246
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.remove_duplicate_notes
|
def remove_duplicate_notes(self):
"""Remove duplicate and enharmonic notes from the container."""
res = []
for x in self.notes:
if x not in res:
res.append(x)
self.notes = res
return res
|
python
|
def remove_duplicate_notes(self):
res = []
for x in self.notes:
if x not in res:
res.append(x)
self.notes = res
return res
|
[
"def",
"remove_duplicate_notes",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"notes",
":",
"if",
"x",
"not",
"in",
"res",
":",
"res",
".",
"append",
"(",
"x",
")",
"self",
".",
"notes",
"=",
"res",
"return",
"res"
] |
Remove duplicate and enharmonic notes from the container.
|
[
"Remove",
"duplicate",
"and",
"enharmonic",
"notes",
"from",
"the",
"container",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L248-L255
|
bspaans/python-mingus
|
mingus/containers/note_container.py
|
NoteContainer.transpose
|
def transpose(self, interval, up=True):
"""Transpose all the notes in the container up or down the given
interval."""
for n in self.notes:
n.transpose(interval, up)
return self
|
python
|
def transpose(self, interval, up=True):
for n in self.notes:
n.transpose(interval, up)
return self
|
[
"def",
"transpose",
"(",
"self",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"for",
"n",
"in",
"self",
".",
"notes",
":",
"n",
".",
"transpose",
"(",
"interval",
",",
"up",
")",
"return",
"self"
] |
Transpose all the notes in the container up or down the given
interval.
|
[
"Transpose",
"all",
"the",
"notes",
"in",
"the",
"container",
"up",
"or",
"down",
"the",
"given",
"interval",
"."
] |
train
|
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L276-L281
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.