id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,400 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L42-L46 |
3,401 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L52-L68 |
3,402 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L337-L361 |
3,403 | 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):
"""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}) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L366-L383 |
3,404 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L385-L415 |
3,405 | 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 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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L417-L449 |
3,406 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L56-L64 |
3,407 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L66-L93 |
3,408 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L274-L281 |
3,409 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L307-L334 |
3,410 | 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):
"""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()) | [
"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"
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-drum/pygame-drum.py#L55-L68 |
3,411 | 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):
"""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) | [
"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"
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-drum/pygame-drum.py#L88-L115 |
3,412 | 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):
"""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) | [
"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"
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus_examples/pygame-piano/pygame-piano.py#L116-L176 |
3,413 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L39-L49 |
3,414 | 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=''):
"""Set the author of the suite."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L51-L54 |
3,415 | 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=''):
"""Set the title and the subtitle of the suite."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/suite.py#L56-L59 |
3,416 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L44-L55 |
3,417 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L57-L69 |
3,418 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/instrument.py#L75-L87 |
3,419 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L54-L75 |
3,420 | 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):
"""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:]] | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L77-L88 |
3,421 | 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):
"""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]) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L90-L110 |
3,422 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L112-L123 |
3,423 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L125-L138 |
3,424 | 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):
"""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:]] | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L140-L150 |
3,425 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L152-L155 |
3,426 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L157-L166 |
3,427 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L175-L184 |
3,428 | 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 bytes for a 'note off' event."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L186-L188 |
3,429 | 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 bytes for a 'note_on' event."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L190-L192 |
3,430 | 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 the bytes for a MIDI controller event."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L194-L196 |
3,431 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L203-L210 |
3,432 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L220-L223 |
3,433 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L225-L229 |
3,434 | 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)):
"""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' | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L235-L240 |
3,435 | 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'):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L242-L246 |
3,436 | 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'):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L248-L260 |
3,437 | 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):
"""Return the bytes for a track name meta event."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L266-L269 |
3,438 | 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):
"""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) | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L271-L289 |
3,439 | 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'):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L38-L91 |
3,440 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L93-L206 |
3,441 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L234-L247 |
3,442 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L278-L307 |
3,443 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L338-L364 |
3,444 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L468-L483 |
3,445 | 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):
"""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] | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/progressions.py#L485-L497 |
3,446 | 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={}):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L45-L67 |
3,447 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L69-L97 |
3,448 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L103-L115 |
3,449 | 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):
"""Shortcut to from_interval_shorthand."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L117-L119 |
3,450 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L121-L140 |
3,451 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L213-L232 |
3,452 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L234-L246 |
3,453 | 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):
"""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 | [
"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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L248-L255 |
3,454 | 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):
"""Transpose all the notes in the container up or down the given
interval."""
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",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L276-L281 |
3,455 | bspaans/python-mingus | mingus/containers/note_container.py | NoteContainer.get_note_names | def get_note_names(self):
"""Return a list with all the note names in the current container.
Every name will only be mentioned once.
"""
res = []
for n in self.notes:
if n.name not in res:
res.append(n.name)
return res | python | def get_note_names(self):
"""Return a list with all the note names in the current container.
Every name will only be mentioned once.
"""
res = []
for n in self.notes:
if n.name not in res:
res.append(n.name)
return res | [
"def",
"get_note_names",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"n",
"in",
"self",
".",
"notes",
":",
"if",
"n",
".",
"name",
"not",
"in",
"res",
":",
"res",
".",
"append",
"(",
"n",
".",
"name",
")",
"return",
"res"
] | Return a list with all the note names in the current container.
Every name will only be mentioned once. | [
"Return",
"a",
"list",
"with",
"all",
"the",
"note",
"names",
"in",
"the",
"current",
"container",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note_container.py#L283-L292 |
3,456 | bspaans/python-mingus | mingus/core/scales.py | determine | def determine(notes):
"""Determine the scales containing the notes.
All major and minor scales are recognized.
Example:
>>> determine(['A', 'Bb', 'E', 'F#', 'G'])
['G melodic minor', 'G Bachian', 'D harmonic major']
"""
notes = set(notes)
res = []
for key in keys:
for scale in _Scale.__subclasses__():
if scale.type == 'major':
if (notes <= set(scale(key[0]).ascending()) or
notes <= set(scale(key[0]).descending())):
res.append(scale(key[0]).name)
elif scale.type == 'minor':
if (notes <= set(scale(get_notes(key[1])[0]).ascending()) or
notes <= set(scale(get_notes(key[1])[0]).descending())):
res.append(scale(get_notes(key[1])[0]).name)
return res | python | def determine(notes):
"""Determine the scales containing the notes.
All major and minor scales are recognized.
Example:
>>> determine(['A', 'Bb', 'E', 'F#', 'G'])
['G melodic minor', 'G Bachian', 'D harmonic major']
"""
notes = set(notes)
res = []
for key in keys:
for scale in _Scale.__subclasses__():
if scale.type == 'major':
if (notes <= set(scale(key[0]).ascending()) or
notes <= set(scale(key[0]).descending())):
res.append(scale(key[0]).name)
elif scale.type == 'minor':
if (notes <= set(scale(get_notes(key[1])[0]).ascending()) or
notes <= set(scale(get_notes(key[1])[0]).descending())):
res.append(scale(get_notes(key[1])[0]).name)
return res | [
"def",
"determine",
"(",
"notes",
")",
":",
"notes",
"=",
"set",
"(",
"notes",
")",
"res",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"for",
"scale",
"in",
"_Scale",
".",
"__subclasses__",
"(",
")",
":",
"if",
"scale",
".",
"type",
"==",
"'major'",
":",
"if",
"(",
"notes",
"<=",
"set",
"(",
"scale",
"(",
"key",
"[",
"0",
"]",
")",
".",
"ascending",
"(",
")",
")",
"or",
"notes",
"<=",
"set",
"(",
"scale",
"(",
"key",
"[",
"0",
"]",
")",
".",
"descending",
"(",
")",
")",
")",
":",
"res",
".",
"append",
"(",
"scale",
"(",
"key",
"[",
"0",
"]",
")",
".",
"name",
")",
"elif",
"scale",
".",
"type",
"==",
"'minor'",
":",
"if",
"(",
"notes",
"<=",
"set",
"(",
"scale",
"(",
"get_notes",
"(",
"key",
"[",
"1",
"]",
")",
"[",
"0",
"]",
")",
".",
"ascending",
"(",
")",
")",
"or",
"notes",
"<=",
"set",
"(",
"scale",
"(",
"get_notes",
"(",
"key",
"[",
"1",
"]",
")",
"[",
"0",
"]",
")",
".",
"descending",
"(",
")",
")",
")",
":",
"res",
".",
"append",
"(",
"scale",
"(",
"get_notes",
"(",
"key",
"[",
"1",
"]",
")",
"[",
"0",
"]",
")",
".",
"name",
")",
"return",
"res"
] | Determine the scales containing the notes.
All major and minor scales are recognized.
Example:
>>> determine(['A', 'Bb', 'E', 'F#', 'G'])
['G melodic minor', 'G Bachian', 'D harmonic major'] | [
"Determine",
"the",
"scales",
"containing",
"the",
"notes",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/scales.py#L60-L82 |
3,457 | bspaans/python-mingus | mingus/core/scales.py | _Scale.degree | def degree(self, degree_number, direction='a'):
"""Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending.
"""
if degree_number < 1:
raise RangeError("degree '%s' out of range" % degree_number)
if direction == 'a':
notes = self.ascending()[:-1]
return notes[degree_number-1]
elif direction == 'd':
notes = reversed(self.descending())[:-1]
return notes[degree_number-1]
else:
raise FormatError("Unrecognised direction '%s'" % direction) | python | def degree(self, degree_number, direction='a'):
"""Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending.
"""
if degree_number < 1:
raise RangeError("degree '%s' out of range" % degree_number)
if direction == 'a':
notes = self.ascending()[:-1]
return notes[degree_number-1]
elif direction == 'd':
notes = reversed(self.descending())[:-1]
return notes[degree_number-1]
else:
raise FormatError("Unrecognised direction '%s'" % direction) | [
"def",
"degree",
"(",
"self",
",",
"degree_number",
",",
"direction",
"=",
"'a'",
")",
":",
"if",
"degree_number",
"<",
"1",
":",
"raise",
"RangeError",
"(",
"\"degree '%s' out of range\"",
"%",
"degree_number",
")",
"if",
"direction",
"==",
"'a'",
":",
"notes",
"=",
"self",
".",
"ascending",
"(",
")",
"[",
":",
"-",
"1",
"]",
"return",
"notes",
"[",
"degree_number",
"-",
"1",
"]",
"elif",
"direction",
"==",
"'d'",
":",
"notes",
"=",
"reversed",
"(",
"self",
".",
"descending",
"(",
")",
")",
"[",
":",
"-",
"1",
"]",
"return",
"notes",
"[",
"degree_number",
"-",
"1",
"]",
"else",
":",
"raise",
"FormatError",
"(",
"\"Unrecognised direction '%s'\"",
"%",
"direction",
")"
] | Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending. | [
"Return",
"the",
"asked",
"scale",
"degree",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/scales.py#L126-L141 |
3,458 | bspaans/python-mingus | mingus/extra/tablature.py | begin_track | def begin_track(tuning, padding=2):
"""Helper function that builds the first few characters of every bar."""
# find longest shorthand tuning base
names = [x.to_shorthand() for x in tuning.tuning]
basesize = len(max(names)) + 3
# Build result
res = []
for x in names:
r = ' %s' % x
spaces = basesize - len(r)
r += ' ' * spaces + '||' + '-' * padding
res.append(r)
return res | python | def begin_track(tuning, padding=2):
"""Helper function that builds the first few characters of every bar."""
# find longest shorthand tuning base
names = [x.to_shorthand() for x in tuning.tuning]
basesize = len(max(names)) + 3
# Build result
res = []
for x in names:
r = ' %s' % x
spaces = basesize - len(r)
r += ' ' * spaces + '||' + '-' * padding
res.append(r)
return res | [
"def",
"begin_track",
"(",
"tuning",
",",
"padding",
"=",
"2",
")",
":",
"# find longest shorthand tuning base",
"names",
"=",
"[",
"x",
".",
"to_shorthand",
"(",
")",
"for",
"x",
"in",
"tuning",
".",
"tuning",
"]",
"basesize",
"=",
"len",
"(",
"max",
"(",
"names",
")",
")",
"+",
"3",
"# Build result",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"names",
":",
"r",
"=",
"' %s'",
"%",
"x",
"spaces",
"=",
"basesize",
"-",
"len",
"(",
"r",
")",
"r",
"+=",
"' '",
"*",
"spaces",
"+",
"'||'",
"+",
"'-'",
"*",
"padding",
"res",
".",
"append",
"(",
"r",
")",
"return",
"res"
] | Helper function that builds the first few characters of every bar. | [
"Helper",
"function",
"that",
"builds",
"the",
"first",
"few",
"characters",
"of",
"every",
"bar",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L28-L41 |
3,459 | bspaans/python-mingus | mingus/extra/tablature.py | add_headers | def add_headers(width=80, title='Untitled', subtitle='', author='', email='',
description='', tunings=[]):
"""Create a nice header in the form of a list of strings using the
information that has been filled in.
All arguments except 'width' and 'tunings' should be strings. 'width'
should be an integer and 'tunings' a list of tunings representing the
instruments.
"""
result = ['']
title = str.upper(title)
result += [str.center(' '.join(title), width)]
if subtitle != '':
result += ['', str.center(str.title(subtitle), width)]
if author != '' or email != '':
result += ['', '']
if email != '':
result += [str.center('Written by: %s <%s>' % (author, email),
width)]
else:
result += [str.center('Written by: %s' % author, width)]
if description != '':
result += ['', '']
words = description.split()
lines = []
line = []
last = 0
for word in words:
if len(word) + last < width - 10:
line.append(word)
last += len(word) + 1
else:
lines.append(line)
line = [word]
last = len(word) + 1
lines.append(line)
for line in lines:
result += [str.center(' '.join(line), width)]
if tunings != []:
result += ['', '', str.center('Instruments', width)]
for (i, tuning) in enumerate(tunings):
result += ['', str.center('%d. %s' % (i + 1, tuning.instrument),
width), str.center(tuning.description, width)]
result += ['', '']
return result | python | def add_headers(width=80, title='Untitled', subtitle='', author='', email='',
description='', tunings=[]):
"""Create a nice header in the form of a list of strings using the
information that has been filled in.
All arguments except 'width' and 'tunings' should be strings. 'width'
should be an integer and 'tunings' a list of tunings representing the
instruments.
"""
result = ['']
title = str.upper(title)
result += [str.center(' '.join(title), width)]
if subtitle != '':
result += ['', str.center(str.title(subtitle), width)]
if author != '' or email != '':
result += ['', '']
if email != '':
result += [str.center('Written by: %s <%s>' % (author, email),
width)]
else:
result += [str.center('Written by: %s' % author, width)]
if description != '':
result += ['', '']
words = description.split()
lines = []
line = []
last = 0
for word in words:
if len(word) + last < width - 10:
line.append(word)
last += len(word) + 1
else:
lines.append(line)
line = [word]
last = len(word) + 1
lines.append(line)
for line in lines:
result += [str.center(' '.join(line), width)]
if tunings != []:
result += ['', '', str.center('Instruments', width)]
for (i, tuning) in enumerate(tunings):
result += ['', str.center('%d. %s' % (i + 1, tuning.instrument),
width), str.center(tuning.description, width)]
result += ['', '']
return result | [
"def",
"add_headers",
"(",
"width",
"=",
"80",
",",
"title",
"=",
"'Untitled'",
",",
"subtitle",
"=",
"''",
",",
"author",
"=",
"''",
",",
"email",
"=",
"''",
",",
"description",
"=",
"''",
",",
"tunings",
"=",
"[",
"]",
")",
":",
"result",
"=",
"[",
"''",
"]",
"title",
"=",
"str",
".",
"upper",
"(",
"title",
")",
"result",
"+=",
"[",
"str",
".",
"center",
"(",
"' '",
".",
"join",
"(",
"title",
")",
",",
"width",
")",
"]",
"if",
"subtitle",
"!=",
"''",
":",
"result",
"+=",
"[",
"''",
",",
"str",
".",
"center",
"(",
"str",
".",
"title",
"(",
"subtitle",
")",
",",
"width",
")",
"]",
"if",
"author",
"!=",
"''",
"or",
"email",
"!=",
"''",
":",
"result",
"+=",
"[",
"''",
",",
"''",
"]",
"if",
"email",
"!=",
"''",
":",
"result",
"+=",
"[",
"str",
".",
"center",
"(",
"'Written by: %s <%s>'",
"%",
"(",
"author",
",",
"email",
")",
",",
"width",
")",
"]",
"else",
":",
"result",
"+=",
"[",
"str",
".",
"center",
"(",
"'Written by: %s'",
"%",
"author",
",",
"width",
")",
"]",
"if",
"description",
"!=",
"''",
":",
"result",
"+=",
"[",
"''",
",",
"''",
"]",
"words",
"=",
"description",
".",
"split",
"(",
")",
"lines",
"=",
"[",
"]",
"line",
"=",
"[",
"]",
"last",
"=",
"0",
"for",
"word",
"in",
"words",
":",
"if",
"len",
"(",
"word",
")",
"+",
"last",
"<",
"width",
"-",
"10",
":",
"line",
".",
"append",
"(",
"word",
")",
"last",
"+=",
"len",
"(",
"word",
")",
"+",
"1",
"else",
":",
"lines",
".",
"append",
"(",
"line",
")",
"line",
"=",
"[",
"word",
"]",
"last",
"=",
"len",
"(",
"word",
")",
"+",
"1",
"lines",
".",
"append",
"(",
"line",
")",
"for",
"line",
"in",
"lines",
":",
"result",
"+=",
"[",
"str",
".",
"center",
"(",
"' '",
".",
"join",
"(",
"line",
")",
",",
"width",
")",
"]",
"if",
"tunings",
"!=",
"[",
"]",
":",
"result",
"+=",
"[",
"''",
",",
"''",
",",
"str",
".",
"center",
"(",
"'Instruments'",
",",
"width",
")",
"]",
"for",
"(",
"i",
",",
"tuning",
")",
"in",
"enumerate",
"(",
"tunings",
")",
":",
"result",
"+=",
"[",
"''",
",",
"str",
".",
"center",
"(",
"'%d. %s'",
"%",
"(",
"i",
"+",
"1",
",",
"tuning",
".",
"instrument",
")",
",",
"width",
")",
",",
"str",
".",
"center",
"(",
"tuning",
".",
"description",
",",
"width",
")",
"]",
"result",
"+=",
"[",
"''",
",",
"''",
"]",
"return",
"result"
] | Create a nice header in the form of a list of strings using the
information that has been filled in.
All arguments except 'width' and 'tunings' should be strings. 'width'
should be an integer and 'tunings' a list of tunings representing the
instruments. | [
"Create",
"a",
"nice",
"header",
"in",
"the",
"form",
"of",
"a",
"list",
"of",
"strings",
"using",
"the",
"information",
"that",
"has",
"been",
"filled",
"in",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L44-L88 |
3,460 | bspaans/python-mingus | mingus/extra/tablature.py | from_Note | def from_Note(note, width=80, tuning=None):
"""Return a string made out of ASCII tablature representing a Note object
or note string.
Throw a RangeError if a suitable fret can't be found.
'tuning' should be a StringTuning object or None for the default tuning.
To force a certain fingering you can use a 'string' and 'fret' attribute
on the Note. If the fingering is valid, it will get used instead of the
default one.
"""
if tuning is None:
tuning = default_tuning
result = begin_track(tuning)
min = 1000
(s, f) = (-1, -1)
# Do an attribute check
if hasattr(note, 'string') and hasattr(note, 'fret'):
n = tuning.get_Note(note.string, note.fret)
if n is not None and int(n) == int(note):
(s, f) = (note.string, note.fret)
min = 0
if min == 1000:
for (string, fret) in enumerate(tuning.find_frets(note)):
if fret is not None:
if fret < min:
min = fret
(s, f) = (string, fret)
l = len(result[0])
w = max(4, (width - l) - 1)
# Build ASCII
if min != 1000:
fret = str(f)
for i in range(len(result)):
d = len(fret)
if i != s:
result[i] += '-' * w + '|'
else:
d = w - len(fret)
result[i] += '-' * (d / 2) + fret
d = (w - d / 2) - len(fret)
result[i] += '-' * d + '|'
else:
raise RangeError("No fret found that could play note '%s'. "
"Note out of range." % note)
result.reverse()
return os.linesep.join(result) | python | def from_Note(note, width=80, tuning=None):
"""Return a string made out of ASCII tablature representing a Note object
or note string.
Throw a RangeError if a suitable fret can't be found.
'tuning' should be a StringTuning object or None for the default tuning.
To force a certain fingering you can use a 'string' and 'fret' attribute
on the Note. If the fingering is valid, it will get used instead of the
default one.
"""
if tuning is None:
tuning = default_tuning
result = begin_track(tuning)
min = 1000
(s, f) = (-1, -1)
# Do an attribute check
if hasattr(note, 'string') and hasattr(note, 'fret'):
n = tuning.get_Note(note.string, note.fret)
if n is not None and int(n) == int(note):
(s, f) = (note.string, note.fret)
min = 0
if min == 1000:
for (string, fret) in enumerate(tuning.find_frets(note)):
if fret is not None:
if fret < min:
min = fret
(s, f) = (string, fret)
l = len(result[0])
w = max(4, (width - l) - 1)
# Build ASCII
if min != 1000:
fret = str(f)
for i in range(len(result)):
d = len(fret)
if i != s:
result[i] += '-' * w + '|'
else:
d = w - len(fret)
result[i] += '-' * (d / 2) + fret
d = (w - d / 2) - len(fret)
result[i] += '-' * d + '|'
else:
raise RangeError("No fret found that could play note '%s'. "
"Note out of range." % note)
result.reverse()
return os.linesep.join(result) | [
"def",
"from_Note",
"(",
"note",
",",
"width",
"=",
"80",
",",
"tuning",
"=",
"None",
")",
":",
"if",
"tuning",
"is",
"None",
":",
"tuning",
"=",
"default_tuning",
"result",
"=",
"begin_track",
"(",
"tuning",
")",
"min",
"=",
"1000",
"(",
"s",
",",
"f",
")",
"=",
"(",
"-",
"1",
",",
"-",
"1",
")",
"# Do an attribute check",
"if",
"hasattr",
"(",
"note",
",",
"'string'",
")",
"and",
"hasattr",
"(",
"note",
",",
"'fret'",
")",
":",
"n",
"=",
"tuning",
".",
"get_Note",
"(",
"note",
".",
"string",
",",
"note",
".",
"fret",
")",
"if",
"n",
"is",
"not",
"None",
"and",
"int",
"(",
"n",
")",
"==",
"int",
"(",
"note",
")",
":",
"(",
"s",
",",
"f",
")",
"=",
"(",
"note",
".",
"string",
",",
"note",
".",
"fret",
")",
"min",
"=",
"0",
"if",
"min",
"==",
"1000",
":",
"for",
"(",
"string",
",",
"fret",
")",
"in",
"enumerate",
"(",
"tuning",
".",
"find_frets",
"(",
"note",
")",
")",
":",
"if",
"fret",
"is",
"not",
"None",
":",
"if",
"fret",
"<",
"min",
":",
"min",
"=",
"fret",
"(",
"s",
",",
"f",
")",
"=",
"(",
"string",
",",
"fret",
")",
"l",
"=",
"len",
"(",
"result",
"[",
"0",
"]",
")",
"w",
"=",
"max",
"(",
"4",
",",
"(",
"width",
"-",
"l",
")",
"-",
"1",
")",
"# Build ASCII",
"if",
"min",
"!=",
"1000",
":",
"fret",
"=",
"str",
"(",
"f",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"result",
")",
")",
":",
"d",
"=",
"len",
"(",
"fret",
")",
"if",
"i",
"!=",
"s",
":",
"result",
"[",
"i",
"]",
"+=",
"'-'",
"*",
"w",
"+",
"'|'",
"else",
":",
"d",
"=",
"w",
"-",
"len",
"(",
"fret",
")",
"result",
"[",
"i",
"]",
"+=",
"'-'",
"*",
"(",
"d",
"/",
"2",
")",
"+",
"fret",
"d",
"=",
"(",
"w",
"-",
"d",
"/",
"2",
")",
"-",
"len",
"(",
"fret",
")",
"result",
"[",
"i",
"]",
"+=",
"'-'",
"*",
"d",
"+",
"'|'",
"else",
":",
"raise",
"RangeError",
"(",
"\"No fret found that could play note '%s'. \"",
"\"Note out of range.\"",
"%",
"note",
")",
"result",
".",
"reverse",
"(",
")",
"return",
"os",
".",
"linesep",
".",
"join",
"(",
"result",
")"
] | Return a string made out of ASCII tablature representing a Note object
or note string.
Throw a RangeError if a suitable fret can't be found.
'tuning' should be a StringTuning object or None for the default tuning.
To force a certain fingering you can use a 'string' and 'fret' attribute
on the Note. If the fingering is valid, it will get used instead of the
default one. | [
"Return",
"a",
"string",
"made",
"out",
"of",
"ASCII",
"tablature",
"representing",
"a",
"Note",
"object",
"or",
"note",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L90-L140 |
3,461 | bspaans/python-mingus | mingus/extra/tablature.py | from_Track | def from_Track(track, maxwidth=80, tuning=None):
"""Convert a mingus.containers.Track object to an ASCII tablature string.
'tuning' should be set to a StringTuning object or to None to use the
Track's tuning (or alternatively the default if the Track hasn't got its
own tuning).
'string' and 'fret' attributes on Notes are taken into account.
"""
result = []
width = _get_width(maxwidth)
if not tuning:
tuning = track.get_tuning()
lastlen = 0
for bar in track:
r = from_Bar(bar, width, tuning, collapse=False)
barstart = r[1].find('||') + 2
if (len(r[0]) + lastlen) - barstart < maxwidth and result != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
result[-i] += item[barstart:]
else:
result += ['', ''] + r
lastlen = len(result[-1])
return os.linesep.join(result) | python | def from_Track(track, maxwidth=80, tuning=None):
"""Convert a mingus.containers.Track object to an ASCII tablature string.
'tuning' should be set to a StringTuning object or to None to use the
Track's tuning (or alternatively the default if the Track hasn't got its
own tuning).
'string' and 'fret' attributes on Notes are taken into account.
"""
result = []
width = _get_width(maxwidth)
if not tuning:
tuning = track.get_tuning()
lastlen = 0
for bar in track:
r = from_Bar(bar, width, tuning, collapse=False)
barstart = r[1].find('||') + 2
if (len(r[0]) + lastlen) - barstart < maxwidth and result != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
result[-i] += item[barstart:]
else:
result += ['', ''] + r
lastlen = len(result[-1])
return os.linesep.join(result) | [
"def",
"from_Track",
"(",
"track",
",",
"maxwidth",
"=",
"80",
",",
"tuning",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"width",
"=",
"_get_width",
"(",
"maxwidth",
")",
"if",
"not",
"tuning",
":",
"tuning",
"=",
"track",
".",
"get_tuning",
"(",
")",
"lastlen",
"=",
"0",
"for",
"bar",
"in",
"track",
":",
"r",
"=",
"from_Bar",
"(",
"bar",
",",
"width",
",",
"tuning",
",",
"collapse",
"=",
"False",
")",
"barstart",
"=",
"r",
"[",
"1",
"]",
".",
"find",
"(",
"'||'",
")",
"+",
"2",
"if",
"(",
"len",
"(",
"r",
"[",
"0",
"]",
")",
"+",
"lastlen",
")",
"-",
"barstart",
"<",
"maxwidth",
"and",
"result",
"!=",
"[",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"r",
")",
"+",
"1",
")",
":",
"item",
"=",
"r",
"[",
"len",
"(",
"r",
")",
"-",
"i",
"]",
"result",
"[",
"-",
"i",
"]",
"+=",
"item",
"[",
"barstart",
":",
"]",
"else",
":",
"result",
"+=",
"[",
"''",
",",
"''",
"]",
"+",
"r",
"lastlen",
"=",
"len",
"(",
"result",
"[",
"-",
"1",
"]",
")",
"return",
"os",
".",
"linesep",
".",
"join",
"(",
"result",
")"
] | Convert a mingus.containers.Track object to an ASCII tablature string.
'tuning' should be set to a StringTuning object or to None to use the
Track's tuning (or alternatively the default if the Track hasn't got its
own tuning).
'string' and 'fret' attributes on Notes are taken into account. | [
"Convert",
"a",
"mingus",
".",
"containers",
".",
"Track",
"object",
"to",
"an",
"ASCII",
"tablature",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L302-L326 |
3,462 | bspaans/python-mingus | mingus/extra/tablature.py | from_Composition | def from_Composition(composition, width=80):
"""Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute.
"""
# Collect tunings
instr_tunings = []
for track in composition:
tun = track.get_tuning()
if tun:
instr_tunings.append(tun)
else:
instr_tunings.append(default_tuning)
result = add_headers(
width,
composition.title,
composition.subtitle,
composition.author,
composition.email,
composition.description,
instr_tunings,
)
# Some variables
w = _get_width(width)
barindex = 0
bars = width / w
lastlen = 0
maxlen = max([len(x) for x in composition.tracks])
while barindex < maxlen:
notfirst = False
for tracks in composition:
tuning = tracks.get_tuning()
ascii = []
for x in xrange(bars):
if barindex + x < len(tracks):
bar = tracks[barindex + x]
r = from_Bar(bar, w, tuning, collapse=False)
barstart = r[1].find('||') + 2
# Add extra '||' to quarter note marks to connect tracks.
if notfirst:
r[0] = (r[0])[:barstart - 2] + '||' + (r[0])[barstart:]
# Add bar to ascii
if ascii != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
ascii[-i] += item[barstart:]
else:
ascii += r
# Add extra '||' to connect tracks
if notfirst and ascii != []:
pad = ascii[-1].find('||')
result += [' ' * pad + '||', ' ' * pad + '||']
else:
notfirst = True
# Finally, add ascii to result
result += ascii
result += ['', '', '']
barindex += bars
return os.linesep.join(result) | python | def from_Composition(composition, width=80):
"""Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute.
"""
# Collect tunings
instr_tunings = []
for track in composition:
tun = track.get_tuning()
if tun:
instr_tunings.append(tun)
else:
instr_tunings.append(default_tuning)
result = add_headers(
width,
composition.title,
composition.subtitle,
composition.author,
composition.email,
composition.description,
instr_tunings,
)
# Some variables
w = _get_width(width)
barindex = 0
bars = width / w
lastlen = 0
maxlen = max([len(x) for x in composition.tracks])
while barindex < maxlen:
notfirst = False
for tracks in composition:
tuning = tracks.get_tuning()
ascii = []
for x in xrange(bars):
if barindex + x < len(tracks):
bar = tracks[barindex + x]
r = from_Bar(bar, w, tuning, collapse=False)
barstart = r[1].find('||') + 2
# Add extra '||' to quarter note marks to connect tracks.
if notfirst:
r[0] = (r[0])[:barstart - 2] + '||' + (r[0])[barstart:]
# Add bar to ascii
if ascii != []:
for i in range(1, len(r) + 1):
item = r[len(r) - i]
ascii[-i] += item[barstart:]
else:
ascii += r
# Add extra '||' to connect tracks
if notfirst and ascii != []:
pad = ascii[-1].find('||')
result += [' ' * pad + '||', ' ' * pad + '||']
else:
notfirst = True
# Finally, add ascii to result
result += ascii
result += ['', '', '']
barindex += bars
return os.linesep.join(result) | [
"def",
"from_Composition",
"(",
"composition",
",",
"width",
"=",
"80",
")",
":",
"# Collect tunings",
"instr_tunings",
"=",
"[",
"]",
"for",
"track",
"in",
"composition",
":",
"tun",
"=",
"track",
".",
"get_tuning",
"(",
")",
"if",
"tun",
":",
"instr_tunings",
".",
"append",
"(",
"tun",
")",
"else",
":",
"instr_tunings",
".",
"append",
"(",
"default_tuning",
")",
"result",
"=",
"add_headers",
"(",
"width",
",",
"composition",
".",
"title",
",",
"composition",
".",
"subtitle",
",",
"composition",
".",
"author",
",",
"composition",
".",
"email",
",",
"composition",
".",
"description",
",",
"instr_tunings",
",",
")",
"# Some variables",
"w",
"=",
"_get_width",
"(",
"width",
")",
"barindex",
"=",
"0",
"bars",
"=",
"width",
"/",
"w",
"lastlen",
"=",
"0",
"maxlen",
"=",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"composition",
".",
"tracks",
"]",
")",
"while",
"barindex",
"<",
"maxlen",
":",
"notfirst",
"=",
"False",
"for",
"tracks",
"in",
"composition",
":",
"tuning",
"=",
"tracks",
".",
"get_tuning",
"(",
")",
"ascii",
"=",
"[",
"]",
"for",
"x",
"in",
"xrange",
"(",
"bars",
")",
":",
"if",
"barindex",
"+",
"x",
"<",
"len",
"(",
"tracks",
")",
":",
"bar",
"=",
"tracks",
"[",
"barindex",
"+",
"x",
"]",
"r",
"=",
"from_Bar",
"(",
"bar",
",",
"w",
",",
"tuning",
",",
"collapse",
"=",
"False",
")",
"barstart",
"=",
"r",
"[",
"1",
"]",
".",
"find",
"(",
"'||'",
")",
"+",
"2",
"# Add extra '||' to quarter note marks to connect tracks.",
"if",
"notfirst",
":",
"r",
"[",
"0",
"]",
"=",
"(",
"r",
"[",
"0",
"]",
")",
"[",
":",
"barstart",
"-",
"2",
"]",
"+",
"'||'",
"+",
"(",
"r",
"[",
"0",
"]",
")",
"[",
"barstart",
":",
"]",
"# Add bar to ascii",
"if",
"ascii",
"!=",
"[",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"r",
")",
"+",
"1",
")",
":",
"item",
"=",
"r",
"[",
"len",
"(",
"r",
")",
"-",
"i",
"]",
"ascii",
"[",
"-",
"i",
"]",
"+=",
"item",
"[",
"barstart",
":",
"]",
"else",
":",
"ascii",
"+=",
"r",
"# Add extra '||' to connect tracks",
"if",
"notfirst",
"and",
"ascii",
"!=",
"[",
"]",
":",
"pad",
"=",
"ascii",
"[",
"-",
"1",
"]",
".",
"find",
"(",
"'||'",
")",
"result",
"+=",
"[",
"' '",
"*",
"pad",
"+",
"'||'",
",",
"' '",
"*",
"pad",
"+",
"'||'",
"]",
"else",
":",
"notfirst",
"=",
"True",
"# Finally, add ascii to result",
"result",
"+=",
"ascii",
"result",
"+=",
"[",
"''",
",",
"''",
",",
"''",
"]",
"barindex",
"+=",
"bars",
"return",
"os",
".",
"linesep",
".",
"join",
"(",
"result",
")"
] | Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
attribute. | [
"Convert",
"a",
"mingus",
".",
"containers",
".",
"Composition",
"to",
"an",
"ASCII",
"tablature",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L328-L397 |
3,463 | bspaans/python-mingus | mingus/extra/tablature.py | from_Suite | def from_Suite(suite, maxwidth=80):
"""Convert a mingus.containers.Suite to an ASCII tablature string, complete
with headers.
This function makes use of the Suite's title, subtitle, author, email
and description attributes.
"""
subtitle = str(len(suite.compositions)) + ' Compositions' if suite.subtitle\
== '' else suite.subtitle
result = os.linesep.join(add_headers(
maxwidth,
suite.title,
subtitle,
suite.author,
suite.email,
suite.description,
))
hr = maxwidth * '='
n = os.linesep
result = n + hr + n + result + n + hr + n + n
for comp in suite:
c = from_Composition(comp, maxwidth)
result += c + n + hr + n + n
return result | python | def from_Suite(suite, maxwidth=80):
"""Convert a mingus.containers.Suite to an ASCII tablature string, complete
with headers.
This function makes use of the Suite's title, subtitle, author, email
and description attributes.
"""
subtitle = str(len(suite.compositions)) + ' Compositions' if suite.subtitle\
== '' else suite.subtitle
result = os.linesep.join(add_headers(
maxwidth,
suite.title,
subtitle,
suite.author,
suite.email,
suite.description,
))
hr = maxwidth * '='
n = os.linesep
result = n + hr + n + result + n + hr + n + n
for comp in suite:
c = from_Composition(comp, maxwidth)
result += c + n + hr + n + n
return result | [
"def",
"from_Suite",
"(",
"suite",
",",
"maxwidth",
"=",
"80",
")",
":",
"subtitle",
"=",
"str",
"(",
"len",
"(",
"suite",
".",
"compositions",
")",
")",
"+",
"' Compositions'",
"if",
"suite",
".",
"subtitle",
"==",
"''",
"else",
"suite",
".",
"subtitle",
"result",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"add_headers",
"(",
"maxwidth",
",",
"suite",
".",
"title",
",",
"subtitle",
",",
"suite",
".",
"author",
",",
"suite",
".",
"email",
",",
"suite",
".",
"description",
",",
")",
")",
"hr",
"=",
"maxwidth",
"*",
"'='",
"n",
"=",
"os",
".",
"linesep",
"result",
"=",
"n",
"+",
"hr",
"+",
"n",
"+",
"result",
"+",
"n",
"+",
"hr",
"+",
"n",
"+",
"n",
"for",
"comp",
"in",
"suite",
":",
"c",
"=",
"from_Composition",
"(",
"comp",
",",
"maxwidth",
")",
"result",
"+=",
"c",
"+",
"n",
"+",
"hr",
"+",
"n",
"+",
"n",
"return",
"result"
] | Convert a mingus.containers.Suite to an ASCII tablature string, complete
with headers.
This function makes use of the Suite's title, subtitle, author, email
and description attributes. | [
"Convert",
"a",
"mingus",
".",
"containers",
".",
"Suite",
"to",
"an",
"ASCII",
"tablature",
"string",
"complete",
"with",
"headers",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L399-L422 |
3,464 | bspaans/python-mingus | mingus/extra/tablature.py | _get_qsize | def _get_qsize(tuning, width):
"""Return a reasonable quarter note size for 'tuning' and 'width'."""
names = [x.to_shorthand() for x in tuning.tuning]
basesize = len(max(names)) + 3
barsize = ((width - basesize) - 2) - 1
# x * 4 + 0.5x - barsize = 0 4.5x = barsize x = barsize / 4.5
return max(0, int(barsize / 4.5)) | python | def _get_qsize(tuning, width):
"""Return a reasonable quarter note size for 'tuning' and 'width'."""
names = [x.to_shorthand() for x in tuning.tuning]
basesize = len(max(names)) + 3
barsize = ((width - basesize) - 2) - 1
# x * 4 + 0.5x - barsize = 0 4.5x = barsize x = barsize / 4.5
return max(0, int(barsize / 4.5)) | [
"def",
"_get_qsize",
"(",
"tuning",
",",
"width",
")",
":",
"names",
"=",
"[",
"x",
".",
"to_shorthand",
"(",
")",
"for",
"x",
"in",
"tuning",
".",
"tuning",
"]",
"basesize",
"=",
"len",
"(",
"max",
"(",
"names",
")",
")",
"+",
"3",
"barsize",
"=",
"(",
"(",
"width",
"-",
"basesize",
")",
"-",
"2",
")",
"-",
"1",
"# x * 4 + 0.5x - barsize = 0 4.5x = barsize x = barsize / 4.5",
"return",
"max",
"(",
"0",
",",
"int",
"(",
"barsize",
"/",
"4.5",
")",
")"
] | Return a reasonable quarter note size for 'tuning' and 'width'. | [
"Return",
"a",
"reasonable",
"quarter",
"note",
"size",
"for",
"tuning",
"and",
"width",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L424-L431 |
3,465 | bspaans/python-mingus | mingus/extra/tablature.py | _get_width | def _get_width(maxwidth):
"""Return the width of a single bar, when width of the page is given."""
width = maxwidth / 3
if maxwidth <= 60:
width = maxwidth
elif 60 < maxwidth <= 120:
width = maxwidth / 2
return width | python | def _get_width(maxwidth):
"""Return the width of a single bar, when width of the page is given."""
width = maxwidth / 3
if maxwidth <= 60:
width = maxwidth
elif 60 < maxwidth <= 120:
width = maxwidth / 2
return width | [
"def",
"_get_width",
"(",
"maxwidth",
")",
":",
"width",
"=",
"maxwidth",
"/",
"3",
"if",
"maxwidth",
"<=",
"60",
":",
"width",
"=",
"maxwidth",
"elif",
"60",
"<",
"maxwidth",
"<=",
"120",
":",
"width",
"=",
"maxwidth",
"/",
"2",
"return",
"width"
] | Return the width of a single bar, when width of the page is given. | [
"Return",
"the",
"width",
"of",
"a",
"single",
"bar",
"when",
"width",
"of",
"the",
"page",
"is",
"given",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L433-L440 |
3,466 | bspaans/python-mingus | mingus/core/chords.py | triad | def triad(note, key):
"""Return the triad on note in key as a list.
Examples:
>>> triad('E', 'C')
['E', 'G', 'B']
>>> triad('E', 'B')
['E', 'G#', 'B']
"""
return [note, intervals.third(note, key), intervals.fifth(note, key)] | python | def triad(note, key):
"""Return the triad on note in key as a list.
Examples:
>>> triad('E', 'C')
['E', 'G', 'B']
>>> triad('E', 'B')
['E', 'G#', 'B']
"""
return [note, intervals.third(note, key), intervals.fifth(note, key)] | [
"def",
"triad",
"(",
"note",
",",
"key",
")",
":",
"return",
"[",
"note",
",",
"intervals",
".",
"third",
"(",
"note",
",",
"key",
")",
",",
"intervals",
".",
"fifth",
"(",
"note",
",",
"key",
")",
"]"
] | Return the triad on note in key as a list.
Examples:
>>> triad('E', 'C')
['E', 'G', 'B']
>>> triad('E', 'B')
['E', 'G#', 'B'] | [
"Return",
"the",
"triad",
"on",
"note",
"in",
"key",
"as",
"a",
"list",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L165-L174 |
3,467 | bspaans/python-mingus | mingus/core/chords.py | triads | def triads(key):
"""Return all the triads in key.
Implemented using a cache.
"""
if _triads_cache.has_key(key):
return _triads_cache[key]
res = map(lambda x: triad(x, key), keys.get_notes(key))
_triads_cache[key] = res
return res | python | def triads(key):
"""Return all the triads in key.
Implemented using a cache.
"""
if _triads_cache.has_key(key):
return _triads_cache[key]
res = map(lambda x: triad(x, key), keys.get_notes(key))
_triads_cache[key] = res
return res | [
"def",
"triads",
"(",
"key",
")",
":",
"if",
"_triads_cache",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"_triads_cache",
"[",
"key",
"]",
"res",
"=",
"map",
"(",
"lambda",
"x",
":",
"triad",
"(",
"x",
",",
"key",
")",
",",
"keys",
".",
"get_notes",
"(",
"key",
")",
")",
"_triads_cache",
"[",
"key",
"]",
"=",
"res",
"return",
"res"
] | Return all the triads in key.
Implemented using a cache. | [
"Return",
"all",
"the",
"triads",
"in",
"key",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L176-L185 |
3,468 | bspaans/python-mingus | mingus/core/chords.py | augmented_triad | def augmented_triad(note):
"""Build an augmented triad on note.
Example:
>>> augmented_triad('C')
['C', 'E', 'G#']
"""
return [note, intervals.major_third(note),
notes.augment(intervals.major_fifth(note))] | python | def augmented_triad(note):
"""Build an augmented triad on note.
Example:
>>> augmented_triad('C')
['C', 'E', 'G#']
"""
return [note, intervals.major_third(note),
notes.augment(intervals.major_fifth(note))] | [
"def",
"augmented_triad",
"(",
"note",
")",
":",
"return",
"[",
"note",
",",
"intervals",
".",
"major_third",
"(",
"note",
")",
",",
"notes",
".",
"augment",
"(",
"intervals",
".",
"major_fifth",
"(",
"note",
")",
")",
"]"
] | Build an augmented triad on note.
Example:
>>> augmented_triad('C')
['C', 'E', 'G#'] | [
"Build",
"an",
"augmented",
"triad",
"on",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L214-L222 |
3,469 | bspaans/python-mingus | mingus/core/chords.py | seventh | def seventh(note, key):
"""Return the seventh chord on note in key.
Example:
>>> seventh('C', 'C')
['C', 'E', 'G', 'B']
"""
return triad(note, key) + [intervals.seventh(note, key)] | python | def seventh(note, key):
"""Return the seventh chord on note in key.
Example:
>>> seventh('C', 'C')
['C', 'E', 'G', 'B']
"""
return triad(note, key) + [intervals.seventh(note, key)] | [
"def",
"seventh",
"(",
"note",
",",
"key",
")",
":",
"return",
"triad",
"(",
"note",
",",
"key",
")",
"+",
"[",
"intervals",
".",
"seventh",
"(",
"note",
",",
"key",
")",
"]"
] | Return the seventh chord on note in key.
Example:
>>> seventh('C', 'C')
['C', 'E', 'G', 'B'] | [
"Return",
"the",
"seventh",
"chord",
"on",
"note",
"in",
"key",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L224-L231 |
3,470 | bspaans/python-mingus | mingus/core/chords.py | sevenths | def sevenths(key):
"""Return all the sevenths chords in key in a list."""
if _sevenths_cache.has_key(key):
return _sevenths_cache[key]
res = map(lambda x: seventh(x, key), keys.get_notes(key))
_sevenths_cache[key] = res
return res | python | def sevenths(key):
"""Return all the sevenths chords in key in a list."""
if _sevenths_cache.has_key(key):
return _sevenths_cache[key]
res = map(lambda x: seventh(x, key), keys.get_notes(key))
_sevenths_cache[key] = res
return res | [
"def",
"sevenths",
"(",
"key",
")",
":",
"if",
"_sevenths_cache",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"_sevenths_cache",
"[",
"key",
"]",
"res",
"=",
"map",
"(",
"lambda",
"x",
":",
"seventh",
"(",
"x",
",",
"key",
")",
",",
"keys",
".",
"get_notes",
"(",
"key",
")",
")",
"_sevenths_cache",
"[",
"key",
"]",
"=",
"res",
"return",
"res"
] | Return all the sevenths chords in key in a list. | [
"Return",
"all",
"the",
"sevenths",
"chords",
"in",
"key",
"in",
"a",
"list",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L233-L239 |
3,471 | bspaans/python-mingus | mingus/core/chords.py | dominant_flat_ninth | def dominant_flat_ninth(note):
"""Build a dominant flat ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'Db']
"""
res = dominant_ninth(note)
res[4] = intervals.minor_second(note)
return res | python | def dominant_flat_ninth(note):
"""Build a dominant flat ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'Db']
"""
res = dominant_ninth(note)
res[4] = intervals.minor_second(note)
return res | [
"def",
"dominant_flat_ninth",
"(",
"note",
")",
":",
"res",
"=",
"dominant_ninth",
"(",
"note",
")",
"res",
"[",
"4",
"]",
"=",
"intervals",
".",
"minor_second",
"(",
"note",
")",
"return",
"res"
] | Build a dominant flat ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'Db'] | [
"Build",
"a",
"dominant",
"flat",
"ninth",
"chord",
"on",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L368-L377 |
3,472 | bspaans/python-mingus | mingus/core/chords.py | dominant_sharp_ninth | def dominant_sharp_ninth(note):
"""Build a dominant sharp ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'D#']
"""
res = dominant_ninth(note)
res[4] = notes.augment(intervals.major_second(note))
return res | python | def dominant_sharp_ninth(note):
"""Build a dominant sharp ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'D#']
"""
res = dominant_ninth(note)
res[4] = notes.augment(intervals.major_second(note))
return res | [
"def",
"dominant_sharp_ninth",
"(",
"note",
")",
":",
"res",
"=",
"dominant_ninth",
"(",
"note",
")",
"res",
"[",
"4",
"]",
"=",
"notes",
".",
"augment",
"(",
"intervals",
".",
"major_second",
"(",
"note",
")",
")",
"return",
"res"
] | Build a dominant sharp ninth chord on note.
Example:
>>> dominant_ninth('C')
['C', 'E', 'G', 'Bb', 'D#'] | [
"Build",
"a",
"dominant",
"sharp",
"ninth",
"chord",
"on",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L379-L388 |
3,473 | bspaans/python-mingus | mingus/core/chords.py | eleventh | def eleventh(note):
"""Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F']
"""
return [note, intervals.perfect_fifth(note), intervals.minor_seventh(note),
intervals.perfect_fourth(note)] | python | def eleventh(note):
"""Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F']
"""
return [note, intervals.perfect_fifth(note), intervals.minor_seventh(note),
intervals.perfect_fourth(note)] | [
"def",
"eleventh",
"(",
"note",
")",
":",
"return",
"[",
"note",
",",
"intervals",
".",
"perfect_fifth",
"(",
"note",
")",
",",
"intervals",
".",
"minor_seventh",
"(",
"note",
")",
",",
"intervals",
".",
"perfect_fourth",
"(",
"note",
")",
"]"
] | Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F'] | [
"Build",
"an",
"eleventh",
"chord",
"on",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L390-L398 |
3,474 | bspaans/python-mingus | mingus/core/chords.py | dominant_flat_five | def dominant_flat_five(note):
"""Build a dominant flat five chord on note.
Example:
>>> dominant_flat_five('C')
['C', 'E', 'Gb', 'Bb']
"""
res = dominant_seventh(note)
res[2] = notes.diminish(res[2])
return res | python | def dominant_flat_five(note):
"""Build a dominant flat five chord on note.
Example:
>>> dominant_flat_five('C')
['C', 'E', 'Gb', 'Bb']
"""
res = dominant_seventh(note)
res[2] = notes.diminish(res[2])
return res | [
"def",
"dominant_flat_five",
"(",
"note",
")",
":",
"res",
"=",
"dominant_seventh",
"(",
"note",
")",
"res",
"[",
"2",
"]",
"=",
"notes",
".",
"diminish",
"(",
"res",
"[",
"2",
"]",
")",
"return",
"res"
] | Build a dominant flat five chord on note.
Example:
>>> dominant_flat_five('C')
['C', 'E', 'Gb', 'Bb'] | [
"Build",
"a",
"dominant",
"flat",
"five",
"chord",
"on",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L494-L503 |
3,475 | bspaans/python-mingus | mingus/core/chords.py | from_shorthand | def from_shorthand(shorthand_string, slash=None):
"""Take a chord written in shorthand and return the notes in the chord.
The function can recognize triads, sevenths, sixths, ninths, elevenths,
thirteenths, slashed chords and a number of altered chords.
The second argument should not be given and is only used for a recursive
call when a slashed chord or polychord is found.
See http://tinyurl.com/3hn6v8u for a nice overview of chord patterns.
Examples:
>>> from_shorthand('Amin')
['A', 'C', 'E']
>>> from_shorthand('Am/M7')
['A', 'C', 'E', 'G#']
>>> from_shorthand('A')
['A', 'C#', 'E']
>>> from_shorthand('A/G')
['G', 'A', 'C#', 'E']
>>> from_shorthand('Dm|G')
['G', 'B', 'D', 'F', 'A']
Recognised abbreviations: the letters "m" and "M" in the following
abbreviations can always be substituted by respectively "min", "mi" or
"-" and "maj" or "ma".
Example:
>>> from_shorthand('Amin7') == from_shorthand('Am7')
True
Triads: 'm', 'M' or '', 'dim'
Sevenths: 'm7', 'M7', '7', 'm7b5', 'dim7', 'm/M7' or 'mM7'
Augmented chords: 'aug' or '+', '7#5' or 'M7+5', 'M7+', 'm7+', '7+'
Suspended chords: 'sus4', 'sus2', 'sus47' or '7sus4', 'sus', '11',
'sus4b9' or 'susb9'
Sixths: '6', 'm6', 'M6', '6/7' or '67', '6/9' or '69'
Ninths: '9' or 'add9', 'M9', 'm9', '7b9', '7#9'
Elevenths: '11' or 'add11', '7#11', 'm11'
Thirteenths: '13' or 'add13', 'M13', 'm13'
Altered chords: '7b5', '7b9', '7#9', '67' or '6/7'
Special: '5', 'NC', 'hendrix'
"""
# warning reduce??
if type(shorthand_string) == list:
res = []
for x in shorthand_string:
res.append(from_shorthand(x))
return res
if shorthand_string in ['NC', 'N.C.']:
return []
# Shrink shorthand_string to a format recognised by chord_shorthand
shorthand_string = shorthand_string.replace('min', 'm')
shorthand_string = shorthand_string.replace('mi', 'm')
shorthand_string = shorthand_string.replace('-', 'm')
shorthand_string = shorthand_string.replace('maj', 'M')
shorthand_string = shorthand_string.replace('ma', 'M')
# Get the note name
if not notes.is_valid_note(shorthand_string[0]):
raise NoteFormatError, "Unrecognised note '%s' in chord '%s'"\
% (shorthand_string[0], shorthand_string)
name = shorthand_string[0]
# Look for accidentals
for n in shorthand_string[1:]:
if n == '#':
name += n
elif n == 'b':
name += n
else:
break
# Look for slashes and polychords '|'
slash_index = -1
s = 0
rest_of_string = shorthand_string[len(name):]
for n in rest_of_string:
if n == '/':
slash_index = s
elif n == '|':
# Generate polychord
return from_shorthand(shorthand_string[:len(name) + s],
from_shorthand(shorthand_string[len(name) + s + 1:]))
s += 1
# Generate slash chord
if slash_index != -1 and rest_of_string not in ['m/M7', '6/9', '6/7']:
res = shorthand_string[:len(name) + slash_index]
return from_shorthand(shorthand_string[:len(name) + slash_index],
shorthand_string[len(name) + slash_index + 1:])
shorthand_start = len(name)
short_chord = shorthand_string[shorthand_start:]
if chord_shorthand.has_key(short_chord):
res = chord_shorthand[short_chord](name)
if slash != None:
# Add slashed chords
if type(slash) == str:
if notes.is_valid_note(slash):
res = [slash] + res
else:
raise NoteFormatError, \
"Unrecognised note '%s' in slash chord'%s'" % (slash,
slash + shorthand_string)
elif type(slash) == list:
# Add polychords
r = slash
for n in res:
if n != r[-1]:
r.append(n)
return r
return res
else:
raise FormatError, 'Unknown shorthand: %s' % shorthand_string | python | def from_shorthand(shorthand_string, slash=None):
"""Take a chord written in shorthand and return the notes in the chord.
The function can recognize triads, sevenths, sixths, ninths, elevenths,
thirteenths, slashed chords and a number of altered chords.
The second argument should not be given and is only used for a recursive
call when a slashed chord or polychord is found.
See http://tinyurl.com/3hn6v8u for a nice overview of chord patterns.
Examples:
>>> from_shorthand('Amin')
['A', 'C', 'E']
>>> from_shorthand('Am/M7')
['A', 'C', 'E', 'G#']
>>> from_shorthand('A')
['A', 'C#', 'E']
>>> from_shorthand('A/G')
['G', 'A', 'C#', 'E']
>>> from_shorthand('Dm|G')
['G', 'B', 'D', 'F', 'A']
Recognised abbreviations: the letters "m" and "M" in the following
abbreviations can always be substituted by respectively "min", "mi" or
"-" and "maj" or "ma".
Example:
>>> from_shorthand('Amin7') == from_shorthand('Am7')
True
Triads: 'm', 'M' or '', 'dim'
Sevenths: 'm7', 'M7', '7', 'm7b5', 'dim7', 'm/M7' or 'mM7'
Augmented chords: 'aug' or '+', '7#5' or 'M7+5', 'M7+', 'm7+', '7+'
Suspended chords: 'sus4', 'sus2', 'sus47' or '7sus4', 'sus', '11',
'sus4b9' or 'susb9'
Sixths: '6', 'm6', 'M6', '6/7' or '67', '6/9' or '69'
Ninths: '9' or 'add9', 'M9', 'm9', '7b9', '7#9'
Elevenths: '11' or 'add11', '7#11', 'm11'
Thirteenths: '13' or 'add13', 'M13', 'm13'
Altered chords: '7b5', '7b9', '7#9', '67' or '6/7'
Special: '5', 'NC', 'hendrix'
"""
# warning reduce??
if type(shorthand_string) == list:
res = []
for x in shorthand_string:
res.append(from_shorthand(x))
return res
if shorthand_string in ['NC', 'N.C.']:
return []
# Shrink shorthand_string to a format recognised by chord_shorthand
shorthand_string = shorthand_string.replace('min', 'm')
shorthand_string = shorthand_string.replace('mi', 'm')
shorthand_string = shorthand_string.replace('-', 'm')
shorthand_string = shorthand_string.replace('maj', 'M')
shorthand_string = shorthand_string.replace('ma', 'M')
# Get the note name
if not notes.is_valid_note(shorthand_string[0]):
raise NoteFormatError, "Unrecognised note '%s' in chord '%s'"\
% (shorthand_string[0], shorthand_string)
name = shorthand_string[0]
# Look for accidentals
for n in shorthand_string[1:]:
if n == '#':
name += n
elif n == 'b':
name += n
else:
break
# Look for slashes and polychords '|'
slash_index = -1
s = 0
rest_of_string = shorthand_string[len(name):]
for n in rest_of_string:
if n == '/':
slash_index = s
elif n == '|':
# Generate polychord
return from_shorthand(shorthand_string[:len(name) + s],
from_shorthand(shorthand_string[len(name) + s + 1:]))
s += 1
# Generate slash chord
if slash_index != -1 and rest_of_string not in ['m/M7', '6/9', '6/7']:
res = shorthand_string[:len(name) + slash_index]
return from_shorthand(shorthand_string[:len(name) + slash_index],
shorthand_string[len(name) + slash_index + 1:])
shorthand_start = len(name)
short_chord = shorthand_string[shorthand_start:]
if chord_shorthand.has_key(short_chord):
res = chord_shorthand[short_chord](name)
if slash != None:
# Add slashed chords
if type(slash) == str:
if notes.is_valid_note(slash):
res = [slash] + res
else:
raise NoteFormatError, \
"Unrecognised note '%s' in slash chord'%s'" % (slash,
slash + shorthand_string)
elif type(slash) == list:
# Add polychords
r = slash
for n in res:
if n != r[-1]:
r.append(n)
return r
return res
else:
raise FormatError, 'Unknown shorthand: %s' % shorthand_string | [
"def",
"from_shorthand",
"(",
"shorthand_string",
",",
"slash",
"=",
"None",
")",
":",
"# warning reduce??",
"if",
"type",
"(",
"shorthand_string",
")",
"==",
"list",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"shorthand_string",
":",
"res",
".",
"append",
"(",
"from_shorthand",
"(",
"x",
")",
")",
"return",
"res",
"if",
"shorthand_string",
"in",
"[",
"'NC'",
",",
"'N.C.'",
"]",
":",
"return",
"[",
"]",
"# Shrink shorthand_string to a format recognised by chord_shorthand",
"shorthand_string",
"=",
"shorthand_string",
".",
"replace",
"(",
"'min'",
",",
"'m'",
")",
"shorthand_string",
"=",
"shorthand_string",
".",
"replace",
"(",
"'mi'",
",",
"'m'",
")",
"shorthand_string",
"=",
"shorthand_string",
".",
"replace",
"(",
"'-'",
",",
"'m'",
")",
"shorthand_string",
"=",
"shorthand_string",
".",
"replace",
"(",
"'maj'",
",",
"'M'",
")",
"shorthand_string",
"=",
"shorthand_string",
".",
"replace",
"(",
"'ma'",
",",
"'M'",
")",
"# Get the note name",
"if",
"not",
"notes",
".",
"is_valid_note",
"(",
"shorthand_string",
"[",
"0",
"]",
")",
":",
"raise",
"NoteFormatError",
",",
"\"Unrecognised note '%s' in chord '%s'\"",
"%",
"(",
"shorthand_string",
"[",
"0",
"]",
",",
"shorthand_string",
")",
"name",
"=",
"shorthand_string",
"[",
"0",
"]",
"# Look for accidentals",
"for",
"n",
"in",
"shorthand_string",
"[",
"1",
":",
"]",
":",
"if",
"n",
"==",
"'#'",
":",
"name",
"+=",
"n",
"elif",
"n",
"==",
"'b'",
":",
"name",
"+=",
"n",
"else",
":",
"break",
"# Look for slashes and polychords '|'",
"slash_index",
"=",
"-",
"1",
"s",
"=",
"0",
"rest_of_string",
"=",
"shorthand_string",
"[",
"len",
"(",
"name",
")",
":",
"]",
"for",
"n",
"in",
"rest_of_string",
":",
"if",
"n",
"==",
"'/'",
":",
"slash_index",
"=",
"s",
"elif",
"n",
"==",
"'|'",
":",
"# Generate polychord",
"return",
"from_shorthand",
"(",
"shorthand_string",
"[",
":",
"len",
"(",
"name",
")",
"+",
"s",
"]",
",",
"from_shorthand",
"(",
"shorthand_string",
"[",
"len",
"(",
"name",
")",
"+",
"s",
"+",
"1",
":",
"]",
")",
")",
"s",
"+=",
"1",
"# Generate slash chord",
"if",
"slash_index",
"!=",
"-",
"1",
"and",
"rest_of_string",
"not",
"in",
"[",
"'m/M7'",
",",
"'6/9'",
",",
"'6/7'",
"]",
":",
"res",
"=",
"shorthand_string",
"[",
":",
"len",
"(",
"name",
")",
"+",
"slash_index",
"]",
"return",
"from_shorthand",
"(",
"shorthand_string",
"[",
":",
"len",
"(",
"name",
")",
"+",
"slash_index",
"]",
",",
"shorthand_string",
"[",
"len",
"(",
"name",
")",
"+",
"slash_index",
"+",
"1",
":",
"]",
")",
"shorthand_start",
"=",
"len",
"(",
"name",
")",
"short_chord",
"=",
"shorthand_string",
"[",
"shorthand_start",
":",
"]",
"if",
"chord_shorthand",
".",
"has_key",
"(",
"short_chord",
")",
":",
"res",
"=",
"chord_shorthand",
"[",
"short_chord",
"]",
"(",
"name",
")",
"if",
"slash",
"!=",
"None",
":",
"# Add slashed chords",
"if",
"type",
"(",
"slash",
")",
"==",
"str",
":",
"if",
"notes",
".",
"is_valid_note",
"(",
"slash",
")",
":",
"res",
"=",
"[",
"slash",
"]",
"+",
"res",
"else",
":",
"raise",
"NoteFormatError",
",",
"\"Unrecognised note '%s' in slash chord'%s'\"",
"%",
"(",
"slash",
",",
"slash",
"+",
"shorthand_string",
")",
"elif",
"type",
"(",
"slash",
")",
"==",
"list",
":",
"# Add polychords",
"r",
"=",
"slash",
"for",
"n",
"in",
"res",
":",
"if",
"n",
"!=",
"r",
"[",
"-",
"1",
"]",
":",
"r",
".",
"append",
"(",
"n",
")",
"return",
"r",
"return",
"res",
"else",
":",
"raise",
"FormatError",
",",
"'Unknown shorthand: %s'",
"%",
"shorthand_string"
] | Take a chord written in shorthand and return the notes in the chord.
The function can recognize triads, sevenths, sixths, ninths, elevenths,
thirteenths, slashed chords and a number of altered chords.
The second argument should not be given and is only used for a recursive
call when a slashed chord or polychord is found.
See http://tinyurl.com/3hn6v8u for a nice overview of chord patterns.
Examples:
>>> from_shorthand('Amin')
['A', 'C', 'E']
>>> from_shorthand('Am/M7')
['A', 'C', 'E', 'G#']
>>> from_shorthand('A')
['A', 'C#', 'E']
>>> from_shorthand('A/G')
['G', 'A', 'C#', 'E']
>>> from_shorthand('Dm|G')
['G', 'B', 'D', 'F', 'A']
Recognised abbreviations: the letters "m" and "M" in the following
abbreviations can always be substituted by respectively "min", "mi" or
"-" and "maj" or "ma".
Example:
>>> from_shorthand('Amin7') == from_shorthand('Am7')
True
Triads: 'm', 'M' or '', 'dim'
Sevenths: 'm7', 'M7', '7', 'm7b5', 'dim7', 'm/M7' or 'mM7'
Augmented chords: 'aug' or '+', '7#5' or 'M7+5', 'M7+', 'm7+', '7+'
Suspended chords: 'sus4', 'sus2', 'sus47' or '7sus4', 'sus', '11',
'sus4b9' or 'susb9'
Sixths: '6', 'm6', 'M6', '6/7' or '67', '6/9' or '69'
Ninths: '9' or 'add9', 'M9', 'm9', '7b9', '7#9'
Elevenths: '11' or 'add11', '7#11', 'm11'
Thirteenths: '13' or 'add13', 'M13', 'm13'
Altered chords: '7b5', '7b9', '7#9', '67' or '6/7'
Special: '5', 'NC', 'hendrix' | [
"Take",
"a",
"chord",
"written",
"in",
"shorthand",
"and",
"return",
"the",
"notes",
"in",
"the",
"chord",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L699-L823 |
3,476 | bspaans/python-mingus | mingus/core/chords.py | determine | def determine(chord, shorthand=False, no_inversions=False, no_polychords=False):
"""Name a chord.
This function can determine almost every chord, from a simple triad to a
fourteen note polychord."""
if chord == []:
return []
elif len(chord) == 1:
return chord
elif len(chord) == 2:
return [intervals.determine(chord[0], chord[1])]
elif len(chord) == 3:
return determine_triad(chord, shorthand, no_inversions, no_polychords)
elif len(chord) == 4:
return determine_seventh(chord, shorthand, no_inversions, no_polychords)
elif len(chord) == 5:
return determine_extended_chord5(chord, shorthand, no_inversions,
no_polychords)
elif len(chord) == 6:
return determine_extended_chord6(chord, shorthand, no_inversions,
no_polychords)
elif len(chord) == 7:
return determine_extended_chord7(chord, shorthand, no_inversions,
no_polychords)
else:
return determine_polychords(chord, shorthand) | python | def determine(chord, shorthand=False, no_inversions=False, no_polychords=False):
"""Name a chord.
This function can determine almost every chord, from a simple triad to a
fourteen note polychord."""
if chord == []:
return []
elif len(chord) == 1:
return chord
elif len(chord) == 2:
return [intervals.determine(chord[0], chord[1])]
elif len(chord) == 3:
return determine_triad(chord, shorthand, no_inversions, no_polychords)
elif len(chord) == 4:
return determine_seventh(chord, shorthand, no_inversions, no_polychords)
elif len(chord) == 5:
return determine_extended_chord5(chord, shorthand, no_inversions,
no_polychords)
elif len(chord) == 6:
return determine_extended_chord6(chord, shorthand, no_inversions,
no_polychords)
elif len(chord) == 7:
return determine_extended_chord7(chord, shorthand, no_inversions,
no_polychords)
else:
return determine_polychords(chord, shorthand) | [
"def",
"determine",
"(",
"chord",
",",
"shorthand",
"=",
"False",
",",
"no_inversions",
"=",
"False",
",",
"no_polychords",
"=",
"False",
")",
":",
"if",
"chord",
"==",
"[",
"]",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"chord",
")",
"==",
"1",
":",
"return",
"chord",
"elif",
"len",
"(",
"chord",
")",
"==",
"2",
":",
"return",
"[",
"intervals",
".",
"determine",
"(",
"chord",
"[",
"0",
"]",
",",
"chord",
"[",
"1",
"]",
")",
"]",
"elif",
"len",
"(",
"chord",
")",
"==",
"3",
":",
"return",
"determine_triad",
"(",
"chord",
",",
"shorthand",
",",
"no_inversions",
",",
"no_polychords",
")",
"elif",
"len",
"(",
"chord",
")",
"==",
"4",
":",
"return",
"determine_seventh",
"(",
"chord",
",",
"shorthand",
",",
"no_inversions",
",",
"no_polychords",
")",
"elif",
"len",
"(",
"chord",
")",
"==",
"5",
":",
"return",
"determine_extended_chord5",
"(",
"chord",
",",
"shorthand",
",",
"no_inversions",
",",
"no_polychords",
")",
"elif",
"len",
"(",
"chord",
")",
"==",
"6",
":",
"return",
"determine_extended_chord6",
"(",
"chord",
",",
"shorthand",
",",
"no_inversions",
",",
"no_polychords",
")",
"elif",
"len",
"(",
"chord",
")",
"==",
"7",
":",
"return",
"determine_extended_chord7",
"(",
"chord",
",",
"shorthand",
",",
"no_inversions",
",",
"no_polychords",
")",
"else",
":",
"return",
"determine_polychords",
"(",
"chord",
",",
"shorthand",
")"
] | Name a chord.
This function can determine almost every chord, from a simple triad to a
fourteen note polychord. | [
"Name",
"a",
"chord",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L825-L850 |
3,477 | bspaans/python-mingus | mingus/core/chords.py | determine_triad | def determine_triad(triad, shorthand=False, no_inversions=False,
placeholder=None):
"""Name the triad; return answers in a list.
The third argument should not be given. If shorthand is True the answers
will be in abbreviated form.
This function can determine major, minor, diminished and suspended
triads. Also knows about invertions.
Examples:
>>> determine_triad(['A', 'C', 'E'])
'A minor triad'
>>> determine_triad(['C', 'E', 'A'])
'A minor triad, first inversion'
>>> determine_triad(['A', 'C', 'E'], True)
'Am'
"""
if len(triad) != 3:
# warning: raise exception: not a triad
return False
def inversion_exhauster(triad, shorthand, tries, result):
"""Run tries every inversion and save the result."""
intval1 = intervals.determine(triad[0], triad[1], True)
intval2 = intervals.determine(triad[0], triad[2], True)
def add_result(short):
result.append((short, tries, triad[0]))
intval = intval1 + intval2
if intval == '25':
add_result('sus2')
elif intval == '3b7':
add_result('dom7') # changed from just '7'
elif intval == '3b5':
add_result('7b5') # why not b5?
elif intval == '35':
add_result('M')
elif intval == '3#5':
add_result('aug')
elif intval == '36':
add_result('M6')
elif intval == '37':
add_result('M7')
elif intval == 'b3b5':
add_result('dim')
elif intval == 'b35':
add_result('m')
elif intval == 'b36':
add_result('m6')
elif intval == 'b3b7':
add_result('m7')
elif intval == 'b37':
add_result('m/M7')
elif intval == '45':
add_result('sus4')
elif intval == '5b7':
add_result('m7')
elif intval == '57':
add_result('M7')
if tries != 3 and not no_inversions:
return inversion_exhauster([triad[-1]] + triad[:-1], shorthand,
tries + 1, result)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]] +
int_desc(r[1]))
return res
return inversion_exhauster(triad, shorthand, 1, []) | python | def determine_triad(triad, shorthand=False, no_inversions=False,
placeholder=None):
"""Name the triad; return answers in a list.
The third argument should not be given. If shorthand is True the answers
will be in abbreviated form.
This function can determine major, minor, diminished and suspended
triads. Also knows about invertions.
Examples:
>>> determine_triad(['A', 'C', 'E'])
'A minor triad'
>>> determine_triad(['C', 'E', 'A'])
'A minor triad, first inversion'
>>> determine_triad(['A', 'C', 'E'], True)
'Am'
"""
if len(triad) != 3:
# warning: raise exception: not a triad
return False
def inversion_exhauster(triad, shorthand, tries, result):
"""Run tries every inversion and save the result."""
intval1 = intervals.determine(triad[0], triad[1], True)
intval2 = intervals.determine(triad[0], triad[2], True)
def add_result(short):
result.append((short, tries, triad[0]))
intval = intval1 + intval2
if intval == '25':
add_result('sus2')
elif intval == '3b7':
add_result('dom7') # changed from just '7'
elif intval == '3b5':
add_result('7b5') # why not b5?
elif intval == '35':
add_result('M')
elif intval == '3#5':
add_result('aug')
elif intval == '36':
add_result('M6')
elif intval == '37':
add_result('M7')
elif intval == 'b3b5':
add_result('dim')
elif intval == 'b35':
add_result('m')
elif intval == 'b36':
add_result('m6')
elif intval == 'b3b7':
add_result('m7')
elif intval == 'b37':
add_result('m/M7')
elif intval == '45':
add_result('sus4')
elif intval == '5b7':
add_result('m7')
elif intval == '57':
add_result('M7')
if tries != 3 and not no_inversions:
return inversion_exhauster([triad[-1]] + triad[:-1], shorthand,
tries + 1, result)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]] +
int_desc(r[1]))
return res
return inversion_exhauster(triad, shorthand, 1, []) | [
"def",
"determine_triad",
"(",
"triad",
",",
"shorthand",
"=",
"False",
",",
"no_inversions",
"=",
"False",
",",
"placeholder",
"=",
"None",
")",
":",
"if",
"len",
"(",
"triad",
")",
"!=",
"3",
":",
"# warning: raise exception: not a triad",
"return",
"False",
"def",
"inversion_exhauster",
"(",
"triad",
",",
"shorthand",
",",
"tries",
",",
"result",
")",
":",
"\"\"\"Run tries every inversion and save the result.\"\"\"",
"intval1",
"=",
"intervals",
".",
"determine",
"(",
"triad",
"[",
"0",
"]",
",",
"triad",
"[",
"1",
"]",
",",
"True",
")",
"intval2",
"=",
"intervals",
".",
"determine",
"(",
"triad",
"[",
"0",
"]",
",",
"triad",
"[",
"2",
"]",
",",
"True",
")",
"def",
"add_result",
"(",
"short",
")",
":",
"result",
".",
"append",
"(",
"(",
"short",
",",
"tries",
",",
"triad",
"[",
"0",
"]",
")",
")",
"intval",
"=",
"intval1",
"+",
"intval2",
"if",
"intval",
"==",
"'25'",
":",
"add_result",
"(",
"'sus2'",
")",
"elif",
"intval",
"==",
"'3b7'",
":",
"add_result",
"(",
"'dom7'",
")",
"# changed from just '7'",
"elif",
"intval",
"==",
"'3b5'",
":",
"add_result",
"(",
"'7b5'",
")",
"# why not b5?",
"elif",
"intval",
"==",
"'35'",
":",
"add_result",
"(",
"'M'",
")",
"elif",
"intval",
"==",
"'3#5'",
":",
"add_result",
"(",
"'aug'",
")",
"elif",
"intval",
"==",
"'36'",
":",
"add_result",
"(",
"'M6'",
")",
"elif",
"intval",
"==",
"'37'",
":",
"add_result",
"(",
"'M7'",
")",
"elif",
"intval",
"==",
"'b3b5'",
":",
"add_result",
"(",
"'dim'",
")",
"elif",
"intval",
"==",
"'b35'",
":",
"add_result",
"(",
"'m'",
")",
"elif",
"intval",
"==",
"'b36'",
":",
"add_result",
"(",
"'m6'",
")",
"elif",
"intval",
"==",
"'b3b7'",
":",
"add_result",
"(",
"'m7'",
")",
"elif",
"intval",
"==",
"'b37'",
":",
"add_result",
"(",
"'m/M7'",
")",
"elif",
"intval",
"==",
"'45'",
":",
"add_result",
"(",
"'sus4'",
")",
"elif",
"intval",
"==",
"'5b7'",
":",
"add_result",
"(",
"'m7'",
")",
"elif",
"intval",
"==",
"'57'",
":",
"add_result",
"(",
"'M7'",
")",
"if",
"tries",
"!=",
"3",
"and",
"not",
"no_inversions",
":",
"return",
"inversion_exhauster",
"(",
"[",
"triad",
"[",
"-",
"1",
"]",
"]",
"+",
"triad",
"[",
":",
"-",
"1",
"]",
",",
"shorthand",
",",
"tries",
"+",
"1",
",",
"result",
")",
"else",
":",
"res",
"=",
"[",
"]",
"for",
"r",
"in",
"result",
":",
"if",
"shorthand",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"r",
"[",
"0",
"]",
")",
"else",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"chord_shorthand_meaning",
"[",
"r",
"[",
"0",
"]",
"]",
"+",
"int_desc",
"(",
"r",
"[",
"1",
"]",
")",
")",
"return",
"res",
"return",
"inversion_exhauster",
"(",
"triad",
",",
"shorthand",
",",
"1",
",",
"[",
"]",
")"
] | Name the triad; return answers in a list.
The third argument should not be given. If shorthand is True the answers
will be in abbreviated form.
This function can determine major, minor, diminished and suspended
triads. Also knows about invertions.
Examples:
>>> determine_triad(['A', 'C', 'E'])
'A minor triad'
>>> determine_triad(['C', 'E', 'A'])
'A minor triad, first inversion'
>>> determine_triad(['A', 'C', 'E'], True)
'Am' | [
"Name",
"the",
"triad",
";",
"return",
"answers",
"in",
"a",
"list",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L852-L925 |
3,478 | bspaans/python-mingus | mingus/core/chords.py | determine_seventh | def determine_seventh(seventh, shorthand=False, no_inversion=False,
no_polychords=False):
"""Determine the type of seventh chord; return the results in a list,
ordered on inversions.
This function expects seventh to be a list of 4 notes.
If shorthand is set to True, results will be returned in chord shorthand
('Cmin7', etc.); inversions will be dropped in that case.
Example:
>>> determine_seventh(['C', 'E', 'G', 'B'])
['C major seventh']
"""
if len(seventh) != 4:
# warning raise exception: seventh chord is not a seventh chord
return False
def inversion_exhauster(seventh, shorthand, tries, result, polychords):
"""Determine sevenths recursive functions."""
# Check whether the first three notes of seventh are part of some triad.
triads = determine_triad(seventh[:3], True, True)
# Get the interval between the first and last note
intval3 = intervals.determine(seventh[0], seventh[3])
def add_result(short, poly=False):
"""Helper function."""
result.append((short, tries, seventh[0], poly))
# Recognizing polychords
if tries == 1 and not no_polychords:
polychords = polychords + determine_polychords(seventh, shorthand)
# Recognizing sevenths
for triad in triads:
# Basic triads
triad = triad[len(seventh[0]):]
if triad == 'm':
if intval3 == 'minor seventh':
add_result('m7')
elif intval3 == 'major seventh':
add_result('m/M7')
elif intval3 == 'major sixth':
add_result('m6')
elif triad == 'M':
if intval3 == 'major seventh':
add_result('M7')
elif intval3 == 'minor seventh':
add_result('7')
elif intval3 == 'major sixth':
add_result('M6')
elif triad == 'dim':
if intval3 == 'minor seventh':
add_result('m7b5')
elif intval3 == 'diminished seventh':
add_result('dim7')
elif triad == 'aug':
if intval3 == 'minor seventh':
add_result('m7+')
if intval3 == 'major seventh':
add_result('M7+')
elif triad == 'sus4':
if intval3 == 'minor seventh':
add_result('sus47')
elif intval3 == 'minor second':
add_result('sus4b9')
elif triad == 'm7':
# Other
if intval3 == 'perfect fourth':
add_result('11')
elif triad == '7b5':
if intval3 == 'minor seventh':
add_result('7b5')
if tries != 4 and not no_inversion:
return inversion_exhauster([seventh[-1]] + seventh[:-1], shorthand,
tries + 1, result, polychords)
else:
# Return results
res = []
# Reset seventh
seventh = [seventh[3]] + seventh[0:3]
for x in result:
if shorthand:
res.append(x[2] + x[0])
else:
res.append(x[2] + chord_shorthand_meaning[x[0]]
+ int_desc(x[1]))
return res + polychords
return inversion_exhauster(seventh, shorthand, 1, [], []) | python | def determine_seventh(seventh, shorthand=False, no_inversion=False,
no_polychords=False):
"""Determine the type of seventh chord; return the results in a list,
ordered on inversions.
This function expects seventh to be a list of 4 notes.
If shorthand is set to True, results will be returned in chord shorthand
('Cmin7', etc.); inversions will be dropped in that case.
Example:
>>> determine_seventh(['C', 'E', 'G', 'B'])
['C major seventh']
"""
if len(seventh) != 4:
# warning raise exception: seventh chord is not a seventh chord
return False
def inversion_exhauster(seventh, shorthand, tries, result, polychords):
"""Determine sevenths recursive functions."""
# Check whether the first three notes of seventh are part of some triad.
triads = determine_triad(seventh[:3], True, True)
# Get the interval between the first and last note
intval3 = intervals.determine(seventh[0], seventh[3])
def add_result(short, poly=False):
"""Helper function."""
result.append((short, tries, seventh[0], poly))
# Recognizing polychords
if tries == 1 and not no_polychords:
polychords = polychords + determine_polychords(seventh, shorthand)
# Recognizing sevenths
for triad in triads:
# Basic triads
triad = triad[len(seventh[0]):]
if triad == 'm':
if intval3 == 'minor seventh':
add_result('m7')
elif intval3 == 'major seventh':
add_result('m/M7')
elif intval3 == 'major sixth':
add_result('m6')
elif triad == 'M':
if intval3 == 'major seventh':
add_result('M7')
elif intval3 == 'minor seventh':
add_result('7')
elif intval3 == 'major sixth':
add_result('M6')
elif triad == 'dim':
if intval3 == 'minor seventh':
add_result('m7b5')
elif intval3 == 'diminished seventh':
add_result('dim7')
elif triad == 'aug':
if intval3 == 'minor seventh':
add_result('m7+')
if intval3 == 'major seventh':
add_result('M7+')
elif triad == 'sus4':
if intval3 == 'minor seventh':
add_result('sus47')
elif intval3 == 'minor second':
add_result('sus4b9')
elif triad == 'm7':
# Other
if intval3 == 'perfect fourth':
add_result('11')
elif triad == '7b5':
if intval3 == 'minor seventh':
add_result('7b5')
if tries != 4 and not no_inversion:
return inversion_exhauster([seventh[-1]] + seventh[:-1], shorthand,
tries + 1, result, polychords)
else:
# Return results
res = []
# Reset seventh
seventh = [seventh[3]] + seventh[0:3]
for x in result:
if shorthand:
res.append(x[2] + x[0])
else:
res.append(x[2] + chord_shorthand_meaning[x[0]]
+ int_desc(x[1]))
return res + polychords
return inversion_exhauster(seventh, shorthand, 1, [], []) | [
"def",
"determine_seventh",
"(",
"seventh",
",",
"shorthand",
"=",
"False",
",",
"no_inversion",
"=",
"False",
",",
"no_polychords",
"=",
"False",
")",
":",
"if",
"len",
"(",
"seventh",
")",
"!=",
"4",
":",
"# warning raise exception: seventh chord is not a seventh chord",
"return",
"False",
"def",
"inversion_exhauster",
"(",
"seventh",
",",
"shorthand",
",",
"tries",
",",
"result",
",",
"polychords",
")",
":",
"\"\"\"Determine sevenths recursive functions.\"\"\"",
"# Check whether the first three notes of seventh are part of some triad.",
"triads",
"=",
"determine_triad",
"(",
"seventh",
"[",
":",
"3",
"]",
",",
"True",
",",
"True",
")",
"# Get the interval between the first and last note",
"intval3",
"=",
"intervals",
".",
"determine",
"(",
"seventh",
"[",
"0",
"]",
",",
"seventh",
"[",
"3",
"]",
")",
"def",
"add_result",
"(",
"short",
",",
"poly",
"=",
"False",
")",
":",
"\"\"\"Helper function.\"\"\"",
"result",
".",
"append",
"(",
"(",
"short",
",",
"tries",
",",
"seventh",
"[",
"0",
"]",
",",
"poly",
")",
")",
"# Recognizing polychords",
"if",
"tries",
"==",
"1",
"and",
"not",
"no_polychords",
":",
"polychords",
"=",
"polychords",
"+",
"determine_polychords",
"(",
"seventh",
",",
"shorthand",
")",
"# Recognizing sevenths",
"for",
"triad",
"in",
"triads",
":",
"# Basic triads",
"triad",
"=",
"triad",
"[",
"len",
"(",
"seventh",
"[",
"0",
"]",
")",
":",
"]",
"if",
"triad",
"==",
"'m'",
":",
"if",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'m7'",
")",
"elif",
"intval3",
"==",
"'major seventh'",
":",
"add_result",
"(",
"'m/M7'",
")",
"elif",
"intval3",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'m6'",
")",
"elif",
"triad",
"==",
"'M'",
":",
"if",
"intval3",
"==",
"'major seventh'",
":",
"add_result",
"(",
"'M7'",
")",
"elif",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'7'",
")",
"elif",
"intval3",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'M6'",
")",
"elif",
"triad",
"==",
"'dim'",
":",
"if",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'m7b5'",
")",
"elif",
"intval3",
"==",
"'diminished seventh'",
":",
"add_result",
"(",
"'dim7'",
")",
"elif",
"triad",
"==",
"'aug'",
":",
"if",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'m7+'",
")",
"if",
"intval3",
"==",
"'major seventh'",
":",
"add_result",
"(",
"'M7+'",
")",
"elif",
"triad",
"==",
"'sus4'",
":",
"if",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'sus47'",
")",
"elif",
"intval3",
"==",
"'minor second'",
":",
"add_result",
"(",
"'sus4b9'",
")",
"elif",
"triad",
"==",
"'m7'",
":",
"# Other",
"if",
"intval3",
"==",
"'perfect fourth'",
":",
"add_result",
"(",
"'11'",
")",
"elif",
"triad",
"==",
"'7b5'",
":",
"if",
"intval3",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'7b5'",
")",
"if",
"tries",
"!=",
"4",
"and",
"not",
"no_inversion",
":",
"return",
"inversion_exhauster",
"(",
"[",
"seventh",
"[",
"-",
"1",
"]",
"]",
"+",
"seventh",
"[",
":",
"-",
"1",
"]",
",",
"shorthand",
",",
"tries",
"+",
"1",
",",
"result",
",",
"polychords",
")",
"else",
":",
"# Return results",
"res",
"=",
"[",
"]",
"# Reset seventh",
"seventh",
"=",
"[",
"seventh",
"[",
"3",
"]",
"]",
"+",
"seventh",
"[",
"0",
":",
"3",
"]",
"for",
"x",
"in",
"result",
":",
"if",
"shorthand",
":",
"res",
".",
"append",
"(",
"x",
"[",
"2",
"]",
"+",
"x",
"[",
"0",
"]",
")",
"else",
":",
"res",
".",
"append",
"(",
"x",
"[",
"2",
"]",
"+",
"chord_shorthand_meaning",
"[",
"x",
"[",
"0",
"]",
"]",
"+",
"int_desc",
"(",
"x",
"[",
"1",
"]",
")",
")",
"return",
"res",
"+",
"polychords",
"return",
"inversion_exhauster",
"(",
"seventh",
",",
"shorthand",
",",
"1",
",",
"[",
"]",
",",
"[",
"]",
")"
] | Determine the type of seventh chord; return the results in a list,
ordered on inversions.
This function expects seventh to be a list of 4 notes.
If shorthand is set to True, results will be returned in chord shorthand
('Cmin7', etc.); inversions will be dropped in that case.
Example:
>>> determine_seventh(['C', 'E', 'G', 'B'])
['C major seventh'] | [
"Determine",
"the",
"type",
"of",
"seventh",
"chord",
";",
"return",
"the",
"results",
"in",
"a",
"list",
"ordered",
"on",
"inversions",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L927-L1019 |
3,479 | bspaans/python-mingus | mingus/core/chords.py | determine_extended_chord5 | def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an extended chord."""
if len(chord) != 5:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(chord, shorthand, tries, result, polychords):
"""Recursive helper function."""
def add_result(short):
result.append((short, tries, chord[0]))
triads = determine_triad(chord[:3], True, True)
sevenths = determine_seventh(chord[:4], True, True, True)
# Determine polychords
if tries == 1 and not no_polychords:
polychords += determine_polychords(chord, shorthand)
intval4 = intervals.determine(chord[0], chord[4])
for seventh in sevenths:
seventh = seventh[len(chord[0]):]
if seventh == 'M7':
if intval4 == 'major second':
add_result('M9')
elif seventh == 'm7':
if intval4 == 'major second':
add_result('m9')
elif intval4 == 'perfect fourth':
add_result('m11')
elif seventh == '7':
if intval4 == 'major second':
add_result('9')
elif intval4 == 'minor second':
add_result('7b9')
elif intval4 == 'augmented second':
add_result('7#9')
elif intval4 == 'minor third':
add_result('7b12')
elif intval4 == 'augmented fourth':
add_result('7#11')
elif intval4 == 'major sixth':
add_result('13')
elif seventh == 'M6':
if intval4 == 'major second':
add_result('6/9')
elif intval4 == 'minor seventh':
add_result('6/7')
if tries != 5 and not no_inversions:
return inversion_exhauster([chord[-1]] + chord[:-1], shorthand,
tries + 1, result, polychords)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]]
+ int_desc(r[1]))
return res + polychords
return inversion_exhauster(chord, shorthand, 1, [], []) | python | def determine_extended_chord5(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an extended chord."""
if len(chord) != 5:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(chord, shorthand, tries, result, polychords):
"""Recursive helper function."""
def add_result(short):
result.append((short, tries, chord[0]))
triads = determine_triad(chord[:3], True, True)
sevenths = determine_seventh(chord[:4], True, True, True)
# Determine polychords
if tries == 1 and not no_polychords:
polychords += determine_polychords(chord, shorthand)
intval4 = intervals.determine(chord[0], chord[4])
for seventh in sevenths:
seventh = seventh[len(chord[0]):]
if seventh == 'M7':
if intval4 == 'major second':
add_result('M9')
elif seventh == 'm7':
if intval4 == 'major second':
add_result('m9')
elif intval4 == 'perfect fourth':
add_result('m11')
elif seventh == '7':
if intval4 == 'major second':
add_result('9')
elif intval4 == 'minor second':
add_result('7b9')
elif intval4 == 'augmented second':
add_result('7#9')
elif intval4 == 'minor third':
add_result('7b12')
elif intval4 == 'augmented fourth':
add_result('7#11')
elif intval4 == 'major sixth':
add_result('13')
elif seventh == 'M6':
if intval4 == 'major second':
add_result('6/9')
elif intval4 == 'minor seventh':
add_result('6/7')
if tries != 5 and not no_inversions:
return inversion_exhauster([chord[-1]] + chord[:-1], shorthand,
tries + 1, result, polychords)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]]
+ int_desc(r[1]))
return res + polychords
return inversion_exhauster(chord, shorthand, 1, [], []) | [
"def",
"determine_extended_chord5",
"(",
"chord",
",",
"shorthand",
"=",
"False",
",",
"no_inversions",
"=",
"False",
",",
"no_polychords",
"=",
"False",
")",
":",
"if",
"len",
"(",
"chord",
")",
"!=",
"5",
":",
"# warning raise exeption: not an extended chord",
"return",
"False",
"def",
"inversion_exhauster",
"(",
"chord",
",",
"shorthand",
",",
"tries",
",",
"result",
",",
"polychords",
")",
":",
"\"\"\"Recursive helper function.\"\"\"",
"def",
"add_result",
"(",
"short",
")",
":",
"result",
".",
"append",
"(",
"(",
"short",
",",
"tries",
",",
"chord",
"[",
"0",
"]",
")",
")",
"triads",
"=",
"determine_triad",
"(",
"chord",
"[",
":",
"3",
"]",
",",
"True",
",",
"True",
")",
"sevenths",
"=",
"determine_seventh",
"(",
"chord",
"[",
":",
"4",
"]",
",",
"True",
",",
"True",
",",
"True",
")",
"# Determine polychords",
"if",
"tries",
"==",
"1",
"and",
"not",
"no_polychords",
":",
"polychords",
"+=",
"determine_polychords",
"(",
"chord",
",",
"shorthand",
")",
"intval4",
"=",
"intervals",
".",
"determine",
"(",
"chord",
"[",
"0",
"]",
",",
"chord",
"[",
"4",
"]",
")",
"for",
"seventh",
"in",
"sevenths",
":",
"seventh",
"=",
"seventh",
"[",
"len",
"(",
"chord",
"[",
"0",
"]",
")",
":",
"]",
"if",
"seventh",
"==",
"'M7'",
":",
"if",
"intval4",
"==",
"'major second'",
":",
"add_result",
"(",
"'M9'",
")",
"elif",
"seventh",
"==",
"'m7'",
":",
"if",
"intval4",
"==",
"'major second'",
":",
"add_result",
"(",
"'m9'",
")",
"elif",
"intval4",
"==",
"'perfect fourth'",
":",
"add_result",
"(",
"'m11'",
")",
"elif",
"seventh",
"==",
"'7'",
":",
"if",
"intval4",
"==",
"'major second'",
":",
"add_result",
"(",
"'9'",
")",
"elif",
"intval4",
"==",
"'minor second'",
":",
"add_result",
"(",
"'7b9'",
")",
"elif",
"intval4",
"==",
"'augmented second'",
":",
"add_result",
"(",
"'7#9'",
")",
"elif",
"intval4",
"==",
"'minor third'",
":",
"add_result",
"(",
"'7b12'",
")",
"elif",
"intval4",
"==",
"'augmented fourth'",
":",
"add_result",
"(",
"'7#11'",
")",
"elif",
"intval4",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'13'",
")",
"elif",
"seventh",
"==",
"'M6'",
":",
"if",
"intval4",
"==",
"'major second'",
":",
"add_result",
"(",
"'6/9'",
")",
"elif",
"intval4",
"==",
"'minor seventh'",
":",
"add_result",
"(",
"'6/7'",
")",
"if",
"tries",
"!=",
"5",
"and",
"not",
"no_inversions",
":",
"return",
"inversion_exhauster",
"(",
"[",
"chord",
"[",
"-",
"1",
"]",
"]",
"+",
"chord",
"[",
":",
"-",
"1",
"]",
",",
"shorthand",
",",
"tries",
"+",
"1",
",",
"result",
",",
"polychords",
")",
"else",
":",
"res",
"=",
"[",
"]",
"for",
"r",
"in",
"result",
":",
"if",
"shorthand",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"r",
"[",
"0",
"]",
")",
"else",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"chord_shorthand_meaning",
"[",
"r",
"[",
"0",
"]",
"]",
"+",
"int_desc",
"(",
"r",
"[",
"1",
"]",
")",
")",
"return",
"res",
"+",
"polychords",
"return",
"inversion_exhauster",
"(",
"chord",
",",
"shorthand",
",",
"1",
",",
"[",
"]",
",",
"[",
"]",
")"
] | Determine the names of an extended chord. | [
"Determine",
"the",
"names",
"of",
"an",
"extended",
"chord",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L1021-L1082 |
3,480 | bspaans/python-mingus | mingus/core/chords.py | determine_extended_chord6 | def determine_extended_chord6(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an 6 note chord."""
if len(chord) != 6:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(
chord,
shorthand,
tries,
result,
polychords,
):
"""Recursive helper function"""
# Determine polychords
if tries == 1 and not no_polychords:
polychords += determine_polychords(chord, shorthand)
def add_result(short):
result.append((short, tries, chord[0]))
ch = determine_extended_chord5(chord[:5], True, True, True)
intval5 = intervals.determine(chord[0], chord[5])
for c in ch:
c = c[len(chord[0]):]
if c == '9':
if intval5 == 'perfect fourth':
add_result('11')
elif intval5 == 'augmented fourth':
add_result('7#11')
elif intval5 == 'major sixth':
add_result('13')
elif c == 'm9':
if intval5 == 'perfect fourth':
add_result('m11')
elif intval5 == 'major sixth':
add_result('m13')
elif c == 'M9':
if intval5 == 'perfect fourth':
add_result('M11')
elif intval5 == 'major sixth':
add_result('M13')
if tries != 6 and not no_inversions:
return inversion_exhauster([chord[-1]] + chord[:-1], shorthand,
tries + 1, result, polychords)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]] +
int_desc(r[1]))
return res + polychords
return inversion_exhauster(chord, shorthand, 1, [], []) | python | def determine_extended_chord6(chord, shorthand=False, no_inversions=False,
no_polychords=False):
"""Determine the names of an 6 note chord."""
if len(chord) != 6:
# warning raise exeption: not an extended chord
return False
def inversion_exhauster(
chord,
shorthand,
tries,
result,
polychords,
):
"""Recursive helper function"""
# Determine polychords
if tries == 1 and not no_polychords:
polychords += determine_polychords(chord, shorthand)
def add_result(short):
result.append((short, tries, chord[0]))
ch = determine_extended_chord5(chord[:5], True, True, True)
intval5 = intervals.determine(chord[0], chord[5])
for c in ch:
c = c[len(chord[0]):]
if c == '9':
if intval5 == 'perfect fourth':
add_result('11')
elif intval5 == 'augmented fourth':
add_result('7#11')
elif intval5 == 'major sixth':
add_result('13')
elif c == 'm9':
if intval5 == 'perfect fourth':
add_result('m11')
elif intval5 == 'major sixth':
add_result('m13')
elif c == 'M9':
if intval5 == 'perfect fourth':
add_result('M11')
elif intval5 == 'major sixth':
add_result('M13')
if tries != 6 and not no_inversions:
return inversion_exhauster([chord[-1]] + chord[:-1], shorthand,
tries + 1, result, polychords)
else:
res = []
for r in result:
if shorthand:
res.append(r[2] + r[0])
else:
res.append(r[2] + chord_shorthand_meaning[r[0]] +
int_desc(r[1]))
return res + polychords
return inversion_exhauster(chord, shorthand, 1, [], []) | [
"def",
"determine_extended_chord6",
"(",
"chord",
",",
"shorthand",
"=",
"False",
",",
"no_inversions",
"=",
"False",
",",
"no_polychords",
"=",
"False",
")",
":",
"if",
"len",
"(",
"chord",
")",
"!=",
"6",
":",
"# warning raise exeption: not an extended chord",
"return",
"False",
"def",
"inversion_exhauster",
"(",
"chord",
",",
"shorthand",
",",
"tries",
",",
"result",
",",
"polychords",
",",
")",
":",
"\"\"\"Recursive helper function\"\"\"",
"# Determine polychords",
"if",
"tries",
"==",
"1",
"and",
"not",
"no_polychords",
":",
"polychords",
"+=",
"determine_polychords",
"(",
"chord",
",",
"shorthand",
")",
"def",
"add_result",
"(",
"short",
")",
":",
"result",
".",
"append",
"(",
"(",
"short",
",",
"tries",
",",
"chord",
"[",
"0",
"]",
")",
")",
"ch",
"=",
"determine_extended_chord5",
"(",
"chord",
"[",
":",
"5",
"]",
",",
"True",
",",
"True",
",",
"True",
")",
"intval5",
"=",
"intervals",
".",
"determine",
"(",
"chord",
"[",
"0",
"]",
",",
"chord",
"[",
"5",
"]",
")",
"for",
"c",
"in",
"ch",
":",
"c",
"=",
"c",
"[",
"len",
"(",
"chord",
"[",
"0",
"]",
")",
":",
"]",
"if",
"c",
"==",
"'9'",
":",
"if",
"intval5",
"==",
"'perfect fourth'",
":",
"add_result",
"(",
"'11'",
")",
"elif",
"intval5",
"==",
"'augmented fourth'",
":",
"add_result",
"(",
"'7#11'",
")",
"elif",
"intval5",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'13'",
")",
"elif",
"c",
"==",
"'m9'",
":",
"if",
"intval5",
"==",
"'perfect fourth'",
":",
"add_result",
"(",
"'m11'",
")",
"elif",
"intval5",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'m13'",
")",
"elif",
"c",
"==",
"'M9'",
":",
"if",
"intval5",
"==",
"'perfect fourth'",
":",
"add_result",
"(",
"'M11'",
")",
"elif",
"intval5",
"==",
"'major sixth'",
":",
"add_result",
"(",
"'M13'",
")",
"if",
"tries",
"!=",
"6",
"and",
"not",
"no_inversions",
":",
"return",
"inversion_exhauster",
"(",
"[",
"chord",
"[",
"-",
"1",
"]",
"]",
"+",
"chord",
"[",
":",
"-",
"1",
"]",
",",
"shorthand",
",",
"tries",
"+",
"1",
",",
"result",
",",
"polychords",
")",
"else",
":",
"res",
"=",
"[",
"]",
"for",
"r",
"in",
"result",
":",
"if",
"shorthand",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"r",
"[",
"0",
"]",
")",
"else",
":",
"res",
".",
"append",
"(",
"r",
"[",
"2",
"]",
"+",
"chord_shorthand_meaning",
"[",
"r",
"[",
"0",
"]",
"]",
"+",
"int_desc",
"(",
"r",
"[",
"1",
"]",
")",
")",
"return",
"res",
"+",
"polychords",
"return",
"inversion_exhauster",
"(",
"chord",
",",
"shorthand",
",",
"1",
",",
"[",
"]",
",",
"[",
"]",
")"
] | Determine the names of an 6 note chord. | [
"Determine",
"the",
"names",
"of",
"an",
"6",
"note",
"chord",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L1084-L1140 |
3,481 | bspaans/python-mingus | mingus/core/chords.py | determine_polychords | def determine_polychords(chord, shorthand=False):
"""Determine the polychords in chord.
This function can handle anything from polychords based on two triads to
6 note extended chords.
"""
polychords = []
function_list = [determine_triad, determine_seventh,
determine_extended_chord5, determine_extended_chord6,
determine_extended_chord7]
# Range tracking.
if len(chord) <= 3:
return []
elif len(chord) > 14:
return []
elif len(chord) - 3 <= 5:
function_nr = range(0, len(chord) - 3)
else:
function_nr = range(0, 5)
for f in function_nr:
for f2 in function_nr:
# The clever part: Try the function_list[f] on the len(chord) - (3 +
# f) last notes of the chord. Then try the function_list[f2] on the
# f2 + 3 first notes of the chord. Thus, trying all possible
# combinations.
for chord1 in function_list[f](chord[len(chord) - (3 + f):], True,
True, True):
for chord2 in function_list[f2](chord[:f2 + 3], True, True,
True):
polychords.append('%s|%s' % (chord1, chord2))
if shorthand:
for p in polychords:
p = p + ' polychord'
return polychords | python | def determine_polychords(chord, shorthand=False):
"""Determine the polychords in chord.
This function can handle anything from polychords based on two triads to
6 note extended chords.
"""
polychords = []
function_list = [determine_triad, determine_seventh,
determine_extended_chord5, determine_extended_chord6,
determine_extended_chord7]
# Range tracking.
if len(chord) <= 3:
return []
elif len(chord) > 14:
return []
elif len(chord) - 3 <= 5:
function_nr = range(0, len(chord) - 3)
else:
function_nr = range(0, 5)
for f in function_nr:
for f2 in function_nr:
# The clever part: Try the function_list[f] on the len(chord) - (3 +
# f) last notes of the chord. Then try the function_list[f2] on the
# f2 + 3 first notes of the chord. Thus, trying all possible
# combinations.
for chord1 in function_list[f](chord[len(chord) - (3 + f):], True,
True, True):
for chord2 in function_list[f2](chord[:f2 + 3], True, True,
True):
polychords.append('%s|%s' % (chord1, chord2))
if shorthand:
for p in polychords:
p = p + ' polychord'
return polychords | [
"def",
"determine_polychords",
"(",
"chord",
",",
"shorthand",
"=",
"False",
")",
":",
"polychords",
"=",
"[",
"]",
"function_list",
"=",
"[",
"determine_triad",
",",
"determine_seventh",
",",
"determine_extended_chord5",
",",
"determine_extended_chord6",
",",
"determine_extended_chord7",
"]",
"# Range tracking.",
"if",
"len",
"(",
"chord",
")",
"<=",
"3",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"chord",
")",
">",
"14",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"chord",
")",
"-",
"3",
"<=",
"5",
":",
"function_nr",
"=",
"range",
"(",
"0",
",",
"len",
"(",
"chord",
")",
"-",
"3",
")",
"else",
":",
"function_nr",
"=",
"range",
"(",
"0",
",",
"5",
")",
"for",
"f",
"in",
"function_nr",
":",
"for",
"f2",
"in",
"function_nr",
":",
"# The clever part: Try the function_list[f] on the len(chord) - (3 +",
"# f) last notes of the chord. Then try the function_list[f2] on the",
"# f2 + 3 first notes of the chord. Thus, trying all possible",
"# combinations.",
"for",
"chord1",
"in",
"function_list",
"[",
"f",
"]",
"(",
"chord",
"[",
"len",
"(",
"chord",
")",
"-",
"(",
"3",
"+",
"f",
")",
":",
"]",
",",
"True",
",",
"True",
",",
"True",
")",
":",
"for",
"chord2",
"in",
"function_list",
"[",
"f2",
"]",
"(",
"chord",
"[",
":",
"f2",
"+",
"3",
"]",
",",
"True",
",",
"True",
",",
"True",
")",
":",
"polychords",
".",
"append",
"(",
"'%s|%s'",
"%",
"(",
"chord1",
",",
"chord2",
")",
")",
"if",
"shorthand",
":",
"for",
"p",
"in",
"polychords",
":",
"p",
"=",
"p",
"+",
"' polychord'",
"return",
"polychords"
] | Determine the polychords in chord.
This function can handle anything from polychords based on two triads to
6 note extended chords. | [
"Determine",
"the",
"polychords",
"in",
"chord",
".",
"This",
"function",
"can",
"handle",
"anything",
"from",
"polychords",
"based",
"on",
"two",
"triads",
"to",
"6",
"note",
"extended",
"chords",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L1197-L1231 |
3,482 | bspaans/python-mingus | mingus/extra/lilypond.py | from_Note | def from_Note(note, process_octaves=True, standalone=True):
"""Get a Note object and return the LilyPond equivalent in a string.
If process_octaves is set to False, all data regarding octaves will be
ignored. If standalone is True, the result can be used by functions
like to_png and will produce a valid output. The argument is mostly here
to let from_NoteContainer make use of this function.
"""
# Throw exception
if not hasattr(note, 'name'):
return False
# Lower the case of the name
result = note.name[0].lower()
# Convert #'s and b's to 'is' and 'es' suffixes
for accidental in note.name[1:]:
if accidental == '#':
result += 'is'
elif accidental == 'b':
result += 'es'
# Place ' and , for octaves
if process_octaves:
oct = note.octave
if oct >= 4:
while oct > 3:
result += "'"
oct -= 1
elif oct < 3:
while oct < 3:
result += ','
oct += 1
if standalone:
return '{ %s }' % result
else:
return result | python | def from_Note(note, process_octaves=True, standalone=True):
"""Get a Note object and return the LilyPond equivalent in a string.
If process_octaves is set to False, all data regarding octaves will be
ignored. If standalone is True, the result can be used by functions
like to_png and will produce a valid output. The argument is mostly here
to let from_NoteContainer make use of this function.
"""
# Throw exception
if not hasattr(note, 'name'):
return False
# Lower the case of the name
result = note.name[0].lower()
# Convert #'s and b's to 'is' and 'es' suffixes
for accidental in note.name[1:]:
if accidental == '#':
result += 'is'
elif accidental == 'b':
result += 'es'
# Place ' and , for octaves
if process_octaves:
oct = note.octave
if oct >= 4:
while oct > 3:
result += "'"
oct -= 1
elif oct < 3:
while oct < 3:
result += ','
oct += 1
if standalone:
return '{ %s }' % result
else:
return result | [
"def",
"from_Note",
"(",
"note",
",",
"process_octaves",
"=",
"True",
",",
"standalone",
"=",
"True",
")",
":",
"# Throw exception",
"if",
"not",
"hasattr",
"(",
"note",
",",
"'name'",
")",
":",
"return",
"False",
"# Lower the case of the name",
"result",
"=",
"note",
".",
"name",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"# Convert #'s and b's to 'is' and 'es' suffixes",
"for",
"accidental",
"in",
"note",
".",
"name",
"[",
"1",
":",
"]",
":",
"if",
"accidental",
"==",
"'#'",
":",
"result",
"+=",
"'is'",
"elif",
"accidental",
"==",
"'b'",
":",
"result",
"+=",
"'es'",
"# Place ' and , for octaves",
"if",
"process_octaves",
":",
"oct",
"=",
"note",
".",
"octave",
"if",
"oct",
">=",
"4",
":",
"while",
"oct",
">",
"3",
":",
"result",
"+=",
"\"'\"",
"oct",
"-=",
"1",
"elif",
"oct",
"<",
"3",
":",
"while",
"oct",
"<",
"3",
":",
"result",
"+=",
"','",
"oct",
"+=",
"1",
"if",
"standalone",
":",
"return",
"'{ %s }'",
"%",
"result",
"else",
":",
"return",
"result"
] | Get a Note object and return the LilyPond equivalent in a string.
If process_octaves is set to False, all data regarding octaves will be
ignored. If standalone is True, the result can be used by functions
like to_png and will produce a valid output. The argument is mostly here
to let from_NoteContainer make use of this function. | [
"Get",
"a",
"Note",
"object",
"and",
"return",
"the",
"LilyPond",
"equivalent",
"in",
"a",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L34-L70 |
3,483 | bspaans/python-mingus | mingus/extra/lilypond.py | from_NoteContainer | def from_NoteContainer(nc, duration=None, standalone=True):
"""Get a NoteContainer object and return the LilyPond equivalent in a
string.
The second argument determining the duration of the NoteContainer is
optional. When the standalone argument is True the result of this
function can be used directly by functions like to_png. It is mostly
here to be used by from_Bar.
"""
# Throw exception
if nc is not None and not hasattr(nc, 'notes'):
return False
# Return rests for None or empty lists
if nc is None or len(nc.notes) == 0:
result = 'r'
elif len(nc.notes) == 1:
# Return a single note if the list contains only one note
result = from_Note(nc.notes[0], standalone=False)
else:
# Return the notes grouped in '<' and '>'
result = '<'
for notes in nc.notes:
result += from_Note(notes, standalone=False) + ' '
result = result[:-1] + '>'
# Add the duration
if duration != None:
parsed_value = value.determine(duration)
# Special case: check for longa and breve in the duration (issue #37)
dur = parsed_value[0]
if dur == value.longa:
result += '\\longa'
elif dur == value.breve:
result += '\\breve'
else:
result += str(int(parsed_value[0]))
for i in range(parsed_value[1]):
result += '.'
if not standalone:
return result
else:
return '{ %s }' % result | python | def from_NoteContainer(nc, duration=None, standalone=True):
"""Get a NoteContainer object and return the LilyPond equivalent in a
string.
The second argument determining the duration of the NoteContainer is
optional. When the standalone argument is True the result of this
function can be used directly by functions like to_png. It is mostly
here to be used by from_Bar.
"""
# Throw exception
if nc is not None and not hasattr(nc, 'notes'):
return False
# Return rests for None or empty lists
if nc is None or len(nc.notes) == 0:
result = 'r'
elif len(nc.notes) == 1:
# Return a single note if the list contains only one note
result = from_Note(nc.notes[0], standalone=False)
else:
# Return the notes grouped in '<' and '>'
result = '<'
for notes in nc.notes:
result += from_Note(notes, standalone=False) + ' '
result = result[:-1] + '>'
# Add the duration
if duration != None:
parsed_value = value.determine(duration)
# Special case: check for longa and breve in the duration (issue #37)
dur = parsed_value[0]
if dur == value.longa:
result += '\\longa'
elif dur == value.breve:
result += '\\breve'
else:
result += str(int(parsed_value[0]))
for i in range(parsed_value[1]):
result += '.'
if not standalone:
return result
else:
return '{ %s }' % result | [
"def",
"from_NoteContainer",
"(",
"nc",
",",
"duration",
"=",
"None",
",",
"standalone",
"=",
"True",
")",
":",
"# Throw exception",
"if",
"nc",
"is",
"not",
"None",
"and",
"not",
"hasattr",
"(",
"nc",
",",
"'notes'",
")",
":",
"return",
"False",
"# Return rests for None or empty lists",
"if",
"nc",
"is",
"None",
"or",
"len",
"(",
"nc",
".",
"notes",
")",
"==",
"0",
":",
"result",
"=",
"'r'",
"elif",
"len",
"(",
"nc",
".",
"notes",
")",
"==",
"1",
":",
"# Return a single note if the list contains only one note",
"result",
"=",
"from_Note",
"(",
"nc",
".",
"notes",
"[",
"0",
"]",
",",
"standalone",
"=",
"False",
")",
"else",
":",
"# Return the notes grouped in '<' and '>'",
"result",
"=",
"'<'",
"for",
"notes",
"in",
"nc",
".",
"notes",
":",
"result",
"+=",
"from_Note",
"(",
"notes",
",",
"standalone",
"=",
"False",
")",
"+",
"' '",
"result",
"=",
"result",
"[",
":",
"-",
"1",
"]",
"+",
"'>'",
"# Add the duration",
"if",
"duration",
"!=",
"None",
":",
"parsed_value",
"=",
"value",
".",
"determine",
"(",
"duration",
")",
"# Special case: check for longa and breve in the duration (issue #37)",
"dur",
"=",
"parsed_value",
"[",
"0",
"]",
"if",
"dur",
"==",
"value",
".",
"longa",
":",
"result",
"+=",
"'\\\\longa'",
"elif",
"dur",
"==",
"value",
".",
"breve",
":",
"result",
"+=",
"'\\\\breve'",
"else",
":",
"result",
"+=",
"str",
"(",
"int",
"(",
"parsed_value",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"parsed_value",
"[",
"1",
"]",
")",
":",
"result",
"+=",
"'.'",
"if",
"not",
"standalone",
":",
"return",
"result",
"else",
":",
"return",
"'{ %s }'",
"%",
"result"
] | Get a NoteContainer object and return the LilyPond equivalent in a
string.
The second argument determining the duration of the NoteContainer is
optional. When the standalone argument is True the result of this
function can be used directly by functions like to_png. It is mostly
here to be used by from_Bar. | [
"Get",
"a",
"NoteContainer",
"object",
"and",
"return",
"the",
"LilyPond",
"equivalent",
"in",
"a",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L72-L116 |
3,484 | bspaans/python-mingus | mingus/extra/lilypond.py | from_Bar | def from_Bar(bar, showkey=True, showtime=True):
"""Get a Bar object and return the LilyPond equivalent in a string.
The showkey and showtime parameters can be set to determine whether the
key and the time should be shown.
"""
# Throw exception
if not hasattr(bar, 'bar'):
return False
# Process the key
if showkey:
key_note = Note(bar.key.key[0].upper() + bar.key.key[1:])
key = '\\key %s \\%s ' % (from_Note(key_note, False, standalone=False), bar.key.mode)
result = key
else:
result = ''
# Handle the NoteContainers
latest_ratio = (1, 1)
ratio_has_changed = False
for bar_entry in bar.bar:
parsed_value = value.determine(bar_entry[1])
ratio = parsed_value[2:]
if ratio == latest_ratio:
result += from_NoteContainer(bar_entry[2], bar_entry[1],
standalone=False) + ' '
else:
if ratio_has_changed:
result += '}'
result += '\\times %d/%d {' % (ratio[1], ratio[0])
result += from_NoteContainer(bar_entry[2], bar_entry[1],
standalone=False) + ' '
latest_ratio = ratio
ratio_has_changed = True
if ratio_has_changed:
result += '}'
# Process the time
if showtime:
return '{ \\time %d/%d %s}' % (bar.meter[0], bar.meter[1], result)
else:
return '{ %s}' % result | python | def from_Bar(bar, showkey=True, showtime=True):
"""Get a Bar object and return the LilyPond equivalent in a string.
The showkey and showtime parameters can be set to determine whether the
key and the time should be shown.
"""
# Throw exception
if not hasattr(bar, 'bar'):
return False
# Process the key
if showkey:
key_note = Note(bar.key.key[0].upper() + bar.key.key[1:])
key = '\\key %s \\%s ' % (from_Note(key_note, False, standalone=False), bar.key.mode)
result = key
else:
result = ''
# Handle the NoteContainers
latest_ratio = (1, 1)
ratio_has_changed = False
for bar_entry in bar.bar:
parsed_value = value.determine(bar_entry[1])
ratio = parsed_value[2:]
if ratio == latest_ratio:
result += from_NoteContainer(bar_entry[2], bar_entry[1],
standalone=False) + ' '
else:
if ratio_has_changed:
result += '}'
result += '\\times %d/%d {' % (ratio[1], ratio[0])
result += from_NoteContainer(bar_entry[2], bar_entry[1],
standalone=False) + ' '
latest_ratio = ratio
ratio_has_changed = True
if ratio_has_changed:
result += '}'
# Process the time
if showtime:
return '{ \\time %d/%d %s}' % (bar.meter[0], bar.meter[1], result)
else:
return '{ %s}' % result | [
"def",
"from_Bar",
"(",
"bar",
",",
"showkey",
"=",
"True",
",",
"showtime",
"=",
"True",
")",
":",
"# Throw exception",
"if",
"not",
"hasattr",
"(",
"bar",
",",
"'bar'",
")",
":",
"return",
"False",
"# Process the key",
"if",
"showkey",
":",
"key_note",
"=",
"Note",
"(",
"bar",
".",
"key",
".",
"key",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"bar",
".",
"key",
".",
"key",
"[",
"1",
":",
"]",
")",
"key",
"=",
"'\\\\key %s \\\\%s '",
"%",
"(",
"from_Note",
"(",
"key_note",
",",
"False",
",",
"standalone",
"=",
"False",
")",
",",
"bar",
".",
"key",
".",
"mode",
")",
"result",
"=",
"key",
"else",
":",
"result",
"=",
"''",
"# Handle the NoteContainers",
"latest_ratio",
"=",
"(",
"1",
",",
"1",
")",
"ratio_has_changed",
"=",
"False",
"for",
"bar_entry",
"in",
"bar",
".",
"bar",
":",
"parsed_value",
"=",
"value",
".",
"determine",
"(",
"bar_entry",
"[",
"1",
"]",
")",
"ratio",
"=",
"parsed_value",
"[",
"2",
":",
"]",
"if",
"ratio",
"==",
"latest_ratio",
":",
"result",
"+=",
"from_NoteContainer",
"(",
"bar_entry",
"[",
"2",
"]",
",",
"bar_entry",
"[",
"1",
"]",
",",
"standalone",
"=",
"False",
")",
"+",
"' '",
"else",
":",
"if",
"ratio_has_changed",
":",
"result",
"+=",
"'}'",
"result",
"+=",
"'\\\\times %d/%d {'",
"%",
"(",
"ratio",
"[",
"1",
"]",
",",
"ratio",
"[",
"0",
"]",
")",
"result",
"+=",
"from_NoteContainer",
"(",
"bar_entry",
"[",
"2",
"]",
",",
"bar_entry",
"[",
"1",
"]",
",",
"standalone",
"=",
"False",
")",
"+",
"' '",
"latest_ratio",
"=",
"ratio",
"ratio_has_changed",
"=",
"True",
"if",
"ratio_has_changed",
":",
"result",
"+=",
"'}'",
"# Process the time",
"if",
"showtime",
":",
"return",
"'{ \\\\time %d/%d %s}'",
"%",
"(",
"bar",
".",
"meter",
"[",
"0",
"]",
",",
"bar",
".",
"meter",
"[",
"1",
"]",
",",
"result",
")",
"else",
":",
"return",
"'{ %s}'",
"%",
"result"
] | Get a Bar object and return the LilyPond equivalent in a string.
The showkey and showtime parameters can be set to determine whether the
key and the time should be shown. | [
"Get",
"a",
"Bar",
"object",
"and",
"return",
"the",
"LilyPond",
"equivalent",
"in",
"a",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L118-L160 |
3,485 | bspaans/python-mingus | mingus/extra/lilypond.py | from_Track | def from_Track(track):
"""Process a Track object and return the LilyPond equivalent in a string."""
# Throw exception
if not hasattr(track, 'bars'):
return False
lastkey = Key('C')
lasttime = (4, 4)
# Handle the Bars:
result = ''
for bar in track.bars:
if lastkey != bar.key:
showkey = True
else:
showkey = False
if lasttime != bar.meter:
showtime = True
else:
showtime = False
result += from_Bar(bar, showkey, showtime) + ' '
lastkey = bar.key
lasttime = bar.meter
return '{ %s}' % result | python | def from_Track(track):
"""Process a Track object and return the LilyPond equivalent in a string."""
# Throw exception
if not hasattr(track, 'bars'):
return False
lastkey = Key('C')
lasttime = (4, 4)
# Handle the Bars:
result = ''
for bar in track.bars:
if lastkey != bar.key:
showkey = True
else:
showkey = False
if lasttime != bar.meter:
showtime = True
else:
showtime = False
result += from_Bar(bar, showkey, showtime) + ' '
lastkey = bar.key
lasttime = bar.meter
return '{ %s}' % result | [
"def",
"from_Track",
"(",
"track",
")",
":",
"# Throw exception",
"if",
"not",
"hasattr",
"(",
"track",
",",
"'bars'",
")",
":",
"return",
"False",
"lastkey",
"=",
"Key",
"(",
"'C'",
")",
"lasttime",
"=",
"(",
"4",
",",
"4",
")",
"# Handle the Bars:",
"result",
"=",
"''",
"for",
"bar",
"in",
"track",
".",
"bars",
":",
"if",
"lastkey",
"!=",
"bar",
".",
"key",
":",
"showkey",
"=",
"True",
"else",
":",
"showkey",
"=",
"False",
"if",
"lasttime",
"!=",
"bar",
".",
"meter",
":",
"showtime",
"=",
"True",
"else",
":",
"showtime",
"=",
"False",
"result",
"+=",
"from_Bar",
"(",
"bar",
",",
"showkey",
",",
"showtime",
")",
"+",
"' '",
"lastkey",
"=",
"bar",
".",
"key",
"lasttime",
"=",
"bar",
".",
"meter",
"return",
"'{ %s}'",
"%",
"result"
] | Process a Track object and return the LilyPond equivalent in a string. | [
"Process",
"a",
"Track",
"object",
"and",
"return",
"the",
"LilyPond",
"equivalent",
"in",
"a",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L162-L184 |
3,486 | bspaans/python-mingus | mingus/extra/lilypond.py | from_Composition | def from_Composition(composition):
"""Return the LilyPond equivalent of a Composition in a string."""
# warning Throw exception
if not hasattr(composition, 'tracks'):
return False
result = '\\header { title = "%s" composer = "%s" opus = "%s" } '\
% (composition.title, composition.author, composition.subtitle)
for track in composition.tracks:
result += from_Track(track) + ' '
return result[:-1] | python | def from_Composition(composition):
"""Return the LilyPond equivalent of a Composition in a string."""
# warning Throw exception
if not hasattr(composition, 'tracks'):
return False
result = '\\header { title = "%s" composer = "%s" opus = "%s" } '\
% (composition.title, composition.author, composition.subtitle)
for track in composition.tracks:
result += from_Track(track) + ' '
return result[:-1] | [
"def",
"from_Composition",
"(",
"composition",
")",
":",
"# warning Throw exception",
"if",
"not",
"hasattr",
"(",
"composition",
",",
"'tracks'",
")",
":",
"return",
"False",
"result",
"=",
"'\\\\header { title = \"%s\" composer = \"%s\" opus = \"%s\" } '",
"%",
"(",
"composition",
".",
"title",
",",
"composition",
".",
"author",
",",
"composition",
".",
"subtitle",
")",
"for",
"track",
"in",
"composition",
".",
"tracks",
":",
"result",
"+=",
"from_Track",
"(",
"track",
")",
"+",
"' '",
"return",
"result",
"[",
":",
"-",
"1",
"]"
] | Return the LilyPond equivalent of a Composition in a string. | [
"Return",
"the",
"LilyPond",
"equivalent",
"of",
"a",
"Composition",
"in",
"a",
"string",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L186-L195 |
3,487 | bspaans/python-mingus | mingus/extra/lilypond.py | save_string_and_execute_LilyPond | def save_string_and_execute_LilyPond(ly_string, filename, command):
"""A helper function for to_png and to_pdf. Should not be used directly."""
ly_string = '\\version "2.10.33"\n' + ly_string
if filename[-4:] in ['.pdf', '.png']:
filename = filename[:-4]
try:
f = open(filename + '.ly', 'w')
f.write(ly_string)
f.close()
except:
return False
command = 'lilypond %s -o "%s" "%s.ly"' % (command, filename, filename)
print 'Executing: %s' % command
p = subprocess.Popen(command, shell=True).wait()
os.remove(filename + '.ly')
return True | python | def save_string_and_execute_LilyPond(ly_string, filename, command):
"""A helper function for to_png and to_pdf. Should not be used directly."""
ly_string = '\\version "2.10.33"\n' + ly_string
if filename[-4:] in ['.pdf', '.png']:
filename = filename[:-4]
try:
f = open(filename + '.ly', 'w')
f.write(ly_string)
f.close()
except:
return False
command = 'lilypond %s -o "%s" "%s.ly"' % (command, filename, filename)
print 'Executing: %s' % command
p = subprocess.Popen(command, shell=True).wait()
os.remove(filename + '.ly')
return True | [
"def",
"save_string_and_execute_LilyPond",
"(",
"ly_string",
",",
"filename",
",",
"command",
")",
":",
"ly_string",
"=",
"'\\\\version \"2.10.33\"\\n'",
"+",
"ly_string",
"if",
"filename",
"[",
"-",
"4",
":",
"]",
"in",
"[",
"'.pdf'",
",",
"'.png'",
"]",
":",
"filename",
"=",
"filename",
"[",
":",
"-",
"4",
"]",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
"+",
"'.ly'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"ly_string",
")",
"f",
".",
"close",
"(",
")",
"except",
":",
"return",
"False",
"command",
"=",
"'lilypond %s -o \"%s\" \"%s.ly\"'",
"%",
"(",
"command",
",",
"filename",
",",
"filename",
")",
"print",
"'Executing: %s'",
"%",
"command",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
")",
".",
"wait",
"(",
")",
"os",
".",
"remove",
"(",
"filename",
"+",
"'.ly'",
")",
"return",
"True"
] | A helper function for to_png and to_pdf. Should not be used directly. | [
"A",
"helper",
"function",
"for",
"to_png",
"and",
"to_pdf",
".",
"Should",
"not",
"be",
"used",
"directly",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L214-L229 |
3,488 | bspaans/python-mingus | mingus/core/value.py | determine | def determine(value):
"""Analyse the value and return a tuple containing the parts it's made of.
The tuple respectively consists of the base note value, the number of
dots, and the ratio (see tuplet).
Examples:
>>> determine(8)
(8, 0, 1, 1)
>>> determine(12)
(8, 0, 3, 2)
>>> determine(14)
(8, 0, 7, 4)
This function recognizes all the base values, triplets, quintuplets,
septuplets and up to four dots. The values are matched on range.
"""
i = -2
for v in base_values:
if value == v:
return (value, 0, 1, 1)
if value < v:
break
i += 1
scaled = float(value) / 2 ** i
if scaled >= 0.9375: # base value
return (base_values[i], 0, 1, 1)
elif scaled >= 0.8125:
# septuplet: scaled = 0.875
return (base_values[i + 1], 0, 7, 4)
elif scaled >= 17 / 24.0:
# triplet: scaled = 0.75
return (base_values[i + 1], 0, 3, 2)
elif scaled >= 31 / 48.0:
# dotted note (one dot): scaled = 2/3.0
return (v, 1, 1, 1)
elif scaled >= 67 / 112.0:
# quintuplet: scaled = 0.625
return (base_values[i + 1], 0, 5, 4)
d = 3
for x in range(2, 5):
d += 2 ** x
if scaled == 2.0 ** x / d:
return (v, x, 1, 1)
return (base_values[i + 1], 0, 1, 1) | python | def determine(value):
"""Analyse the value and return a tuple containing the parts it's made of.
The tuple respectively consists of the base note value, the number of
dots, and the ratio (see tuplet).
Examples:
>>> determine(8)
(8, 0, 1, 1)
>>> determine(12)
(8, 0, 3, 2)
>>> determine(14)
(8, 0, 7, 4)
This function recognizes all the base values, triplets, quintuplets,
septuplets and up to four dots. The values are matched on range.
"""
i = -2
for v in base_values:
if value == v:
return (value, 0, 1, 1)
if value < v:
break
i += 1
scaled = float(value) / 2 ** i
if scaled >= 0.9375: # base value
return (base_values[i], 0, 1, 1)
elif scaled >= 0.8125:
# septuplet: scaled = 0.875
return (base_values[i + 1], 0, 7, 4)
elif scaled >= 17 / 24.0:
# triplet: scaled = 0.75
return (base_values[i + 1], 0, 3, 2)
elif scaled >= 31 / 48.0:
# dotted note (one dot): scaled = 2/3.0
return (v, 1, 1, 1)
elif scaled >= 67 / 112.0:
# quintuplet: scaled = 0.625
return (base_values[i + 1], 0, 5, 4)
d = 3
for x in range(2, 5):
d += 2 ** x
if scaled == 2.0 ** x / d:
return (v, x, 1, 1)
return (base_values[i + 1], 0, 1, 1) | [
"def",
"determine",
"(",
"value",
")",
":",
"i",
"=",
"-",
"2",
"for",
"v",
"in",
"base_values",
":",
"if",
"value",
"==",
"v",
":",
"return",
"(",
"value",
",",
"0",
",",
"1",
",",
"1",
")",
"if",
"value",
"<",
"v",
":",
"break",
"i",
"+=",
"1",
"scaled",
"=",
"float",
"(",
"value",
")",
"/",
"2",
"**",
"i",
"if",
"scaled",
">=",
"0.9375",
":",
"# base value",
"return",
"(",
"base_values",
"[",
"i",
"]",
",",
"0",
",",
"1",
",",
"1",
")",
"elif",
"scaled",
">=",
"0.8125",
":",
"# septuplet: scaled = 0.875",
"return",
"(",
"base_values",
"[",
"i",
"+",
"1",
"]",
",",
"0",
",",
"7",
",",
"4",
")",
"elif",
"scaled",
">=",
"17",
"/",
"24.0",
":",
"# triplet: scaled = 0.75",
"return",
"(",
"base_values",
"[",
"i",
"+",
"1",
"]",
",",
"0",
",",
"3",
",",
"2",
")",
"elif",
"scaled",
">=",
"31",
"/",
"48.0",
":",
"# dotted note (one dot): scaled = 2/3.0",
"return",
"(",
"v",
",",
"1",
",",
"1",
",",
"1",
")",
"elif",
"scaled",
">=",
"67",
"/",
"112.0",
":",
"# quintuplet: scaled = 0.625",
"return",
"(",
"base_values",
"[",
"i",
"+",
"1",
"]",
",",
"0",
",",
"5",
",",
"4",
")",
"d",
"=",
"3",
"for",
"x",
"in",
"range",
"(",
"2",
",",
"5",
")",
":",
"d",
"+=",
"2",
"**",
"x",
"if",
"scaled",
"==",
"2.0",
"**",
"x",
"/",
"d",
":",
"return",
"(",
"v",
",",
"x",
",",
"1",
",",
"1",
")",
"return",
"(",
"base_values",
"[",
"i",
"+",
"1",
"]",
",",
"0",
",",
"1",
",",
"1",
")"
] | Analyse the value and return a tuple containing the parts it's made of.
The tuple respectively consists of the base note value, the number of
dots, and the ratio (see tuplet).
Examples:
>>> determine(8)
(8, 0, 1, 1)
>>> determine(12)
(8, 0, 3, 2)
>>> determine(14)
(8, 0, 7, 4)
This function recognizes all the base values, triplets, quintuplets,
septuplets and up to four dots. The values are matched on range. | [
"Analyse",
"the",
"value",
"and",
"return",
"a",
"tuple",
"containing",
"the",
"parts",
"it",
"s",
"made",
"of",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/value.py#L230-L274 |
3,489 | bspaans/python-mingus | mingus/midi/fluidsynth.py | init | def init(sf2, driver=None, file=None):
"""Initialize the audio.
Return True on success, False on failure.
This function needs to be called before you can have any audio.
The sf2 argument should be the location of a valid soundfont file.
The optional driver argument can be any of 'alsa', 'oss', 'jack',
'portaudio', 'sndmgr', 'coreaudio' or 'Direct Sound'.
If the file argument is not None, then instead of loading the driver, a
new wave file will be initialized to store the audio data.
"""
global midi, initialized
if not initialized:
if file is not None:
midi.start_recording(file)
else:
midi.start_audio_output(driver)
if not midi.load_sound_font(sf2):
return False
midi.fs.program_reset()
initialized = True
return True | python | def init(sf2, driver=None, file=None):
"""Initialize the audio.
Return True on success, False on failure.
This function needs to be called before you can have any audio.
The sf2 argument should be the location of a valid soundfont file.
The optional driver argument can be any of 'alsa', 'oss', 'jack',
'portaudio', 'sndmgr', 'coreaudio' or 'Direct Sound'.
If the file argument is not None, then instead of loading the driver, a
new wave file will be initialized to store the audio data.
"""
global midi, initialized
if not initialized:
if file is not None:
midi.start_recording(file)
else:
midi.start_audio_output(driver)
if not midi.load_sound_font(sf2):
return False
midi.fs.program_reset()
initialized = True
return True | [
"def",
"init",
"(",
"sf2",
",",
"driver",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"global",
"midi",
",",
"initialized",
"if",
"not",
"initialized",
":",
"if",
"file",
"is",
"not",
"None",
":",
"midi",
".",
"start_recording",
"(",
"file",
")",
"else",
":",
"midi",
".",
"start_audio_output",
"(",
"driver",
")",
"if",
"not",
"midi",
".",
"load_sound_font",
"(",
"sf2",
")",
":",
"return",
"False",
"midi",
".",
"fs",
".",
"program_reset",
"(",
")",
"initialized",
"=",
"True",
"return",
"True"
] | Initialize the audio.
Return True on success, False on failure.
This function needs to be called before you can have any audio.
The sf2 argument should be the location of a valid soundfont file.
The optional driver argument can be any of 'alsa', 'oss', 'jack',
'portaudio', 'sndmgr', 'coreaudio' or 'Direct Sound'.
If the file argument is not None, then instead of loading the driver, a
new wave file will be initialized to store the audio data. | [
"Initialize",
"the",
"audio",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/fluidsynth.py#L105-L130 |
3,490 | bspaans/python-mingus | mingus/midi/fluidsynth.py | FluidSynthSequencer.start_recording | def start_recording(self, file='mingus_dump.wav'):
"""Initialize a new wave file for recording."""
w = wave.open(file, 'wb')
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(44100)
self.wav = w | python | def start_recording(self, file='mingus_dump.wav'):
"""Initialize a new wave file for recording."""
w = wave.open(file, 'wb')
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(44100)
self.wav = w | [
"def",
"start_recording",
"(",
"self",
",",
"file",
"=",
"'mingus_dump.wav'",
")",
":",
"w",
"=",
"wave",
".",
"open",
"(",
"file",
",",
"'wb'",
")",
"w",
".",
"setnchannels",
"(",
"2",
")",
"w",
".",
"setsampwidth",
"(",
"2",
")",
"w",
".",
"setframerate",
"(",
"44100",
")",
"self",
".",
"wav",
"=",
"w"
] | Initialize a new wave file for recording. | [
"Initialize",
"a",
"new",
"wave",
"file",
"for",
"recording",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/fluidsynth.py#L61-L67 |
3,491 | bspaans/python-mingus | mingus/midi/fluidsynth.py | FluidSynthSequencer.load_sound_font | def load_sound_font(self, sf2):
"""Load a sound font.
Return True on success, False on failure.
This function should be called before your audio can be played,
since the instruments are kept in the sf2 file.
"""
self.sfid = self.fs.sfload(sf2)
return not self.sfid == -1 | python | def load_sound_font(self, sf2):
"""Load a sound font.
Return True on success, False on failure.
This function should be called before your audio can be played,
since the instruments are kept in the sf2 file.
"""
self.sfid = self.fs.sfload(sf2)
return not self.sfid == -1 | [
"def",
"load_sound_font",
"(",
"self",
",",
"sf2",
")",
":",
"self",
".",
"sfid",
"=",
"self",
".",
"fs",
".",
"sfload",
"(",
"sf2",
")",
"return",
"not",
"self",
".",
"sfid",
"==",
"-",
"1"
] | Load a sound font.
Return True on success, False on failure.
This function should be called before your audio can be played,
since the instruments are kept in the sf2 file. | [
"Load",
"a",
"sound",
"font",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/fluidsynth.py#L69-L78 |
3,492 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.create | def create(self, group_type, config_file, group_name=None,
region=None, profile_name=None):
"""
Create a Greengrass group in the given region.
:param group_type: the type of group to create. Must match a `key` in
the `group_types` dict
:param config_file: config file of the group to create
:param group_name: the name of the group. If no name is given, then
group_type will be used.
:param region: the region in which to create the new group.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
logging.info("[begin] create command using group_types:{0}".format(
self.group_types))
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is False:
raise ValueError(
"Config file already tracking previously created group"
)
if group_type not in self.group_types.keys():
raise ValueError("Can only create {0} groups.".format(
self.group_types)
)
if region is None:
region = self._region
# create an instance of the requested group type that uses the given
# config file and region
gt = self.group_types[group_type](config=config, region=region)
# get and store the account's IoT endpoint for future use
ep = _get_iot_session(region=region).describe_endpoint()
misc = config['misc']
misc['iot_endpoint'] = ep['endpointAddress']
config['misc'] = misc
# Create a Group
logging.info("[begin] Creating a Greengrass Group")
if group_name is None:
group_name = group_type
gg_client = _get_gg_session(region=region, profile_name=profile_name)
group_info = gg_client.create_group(Name="{0}".format(group_name))
config['group'] = {"id": group_info['Id']}
# setup the policies and roles
gt.create_and_attach_thing_policy()
gt.create_and_attach_iam_role()
cl_arn = self._create_core_definition(
gg_client=gg_client, group_type=gt,
config=config, group_name=group_name
)
dl_arn = self._create_device_definition(
gg_client=gg_client, group_type=gt,
config=config, group_name=group_name
)
lv_arn = self._create_function_definition(
gg_client=gg_client, group_type=gt,
config=config
)
log_arn = self._create_logger_definition(
gg_client=gg_client, group_type=gt,
config=config
)
sub_arn = self._create_subscription_definition(
gg_client=gg_client, group_type=gt,
config=config
)
logging.info(
'Group details, core_def:{0} device_def:{1} func_def:{2} '
'logger_def:{3} subs_def:{4}'.format(
cl_arn, dl_arn, lv_arn, log_arn, sub_arn)
)
# Add all the constituent parts to the Greengrass Group
group_args = {'GroupId': group_info['Id']}
if cl_arn:
group_args['CoreDefinitionVersionArn'] = cl_arn
if dl_arn:
group_args['DeviceDefinitionVersionArn'] = dl_arn
if lv_arn:
group_args['FunctionDefinitionVersionArn'] = lv_arn
if log_arn:
group_args['LoggerDefinitionVersionArn'] = log_arn
if sub_arn:
group_args['SubscriptionDefinitionVersionArn'] = sub_arn
grp = gg_client.create_group_version(
**group_args
)
# store info about the provisioned artifacts into the local config file
config['group'] = {
"id": group_info['Id'],
"version_arn": grp['Arn'],
"version": grp['Version'],
"name": group_name
}
logging.info(
"[end] Created Greengrass Group {0}".format(group_info['Id'])) | python | def create(self, group_type, config_file, group_name=None,
region=None, profile_name=None):
"""
Create a Greengrass group in the given region.
:param group_type: the type of group to create. Must match a `key` in
the `group_types` dict
:param config_file: config file of the group to create
:param group_name: the name of the group. If no name is given, then
group_type will be used.
:param region: the region in which to create the new group.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
logging.info("[begin] create command using group_types:{0}".format(
self.group_types))
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is False:
raise ValueError(
"Config file already tracking previously created group"
)
if group_type not in self.group_types.keys():
raise ValueError("Can only create {0} groups.".format(
self.group_types)
)
if region is None:
region = self._region
# create an instance of the requested group type that uses the given
# config file and region
gt = self.group_types[group_type](config=config, region=region)
# get and store the account's IoT endpoint for future use
ep = _get_iot_session(region=region).describe_endpoint()
misc = config['misc']
misc['iot_endpoint'] = ep['endpointAddress']
config['misc'] = misc
# Create a Group
logging.info("[begin] Creating a Greengrass Group")
if group_name is None:
group_name = group_type
gg_client = _get_gg_session(region=region, profile_name=profile_name)
group_info = gg_client.create_group(Name="{0}".format(group_name))
config['group'] = {"id": group_info['Id']}
# setup the policies and roles
gt.create_and_attach_thing_policy()
gt.create_and_attach_iam_role()
cl_arn = self._create_core_definition(
gg_client=gg_client, group_type=gt,
config=config, group_name=group_name
)
dl_arn = self._create_device_definition(
gg_client=gg_client, group_type=gt,
config=config, group_name=group_name
)
lv_arn = self._create_function_definition(
gg_client=gg_client, group_type=gt,
config=config
)
log_arn = self._create_logger_definition(
gg_client=gg_client, group_type=gt,
config=config
)
sub_arn = self._create_subscription_definition(
gg_client=gg_client, group_type=gt,
config=config
)
logging.info(
'Group details, core_def:{0} device_def:{1} func_def:{2} '
'logger_def:{3} subs_def:{4}'.format(
cl_arn, dl_arn, lv_arn, log_arn, sub_arn)
)
# Add all the constituent parts to the Greengrass Group
group_args = {'GroupId': group_info['Id']}
if cl_arn:
group_args['CoreDefinitionVersionArn'] = cl_arn
if dl_arn:
group_args['DeviceDefinitionVersionArn'] = dl_arn
if lv_arn:
group_args['FunctionDefinitionVersionArn'] = lv_arn
if log_arn:
group_args['LoggerDefinitionVersionArn'] = log_arn
if sub_arn:
group_args['SubscriptionDefinitionVersionArn'] = sub_arn
grp = gg_client.create_group_version(
**group_args
)
# store info about the provisioned artifacts into the local config file
config['group'] = {
"id": group_info['Id'],
"version_arn": grp['Arn'],
"version": grp['Version'],
"name": group_name
}
logging.info(
"[end] Created Greengrass Group {0}".format(group_info['Id'])) | [
"def",
"create",
"(",
"self",
",",
"group_type",
",",
"config_file",
",",
"group_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"[begin] create command using group_types:{0}\"",
".",
"format",
"(",
"self",
".",
"group_types",
")",
")",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"Config file already tracking previously created group\"",
")",
"if",
"group_type",
"not",
"in",
"self",
".",
"group_types",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only create {0} groups.\"",
".",
"format",
"(",
"self",
".",
"group_types",
")",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"# create an instance of the requested group type that uses the given",
"# config file and region",
"gt",
"=",
"self",
".",
"group_types",
"[",
"group_type",
"]",
"(",
"config",
"=",
"config",
",",
"region",
"=",
"region",
")",
"# get and store the account's IoT endpoint for future use",
"ep",
"=",
"_get_iot_session",
"(",
"region",
"=",
"region",
")",
".",
"describe_endpoint",
"(",
")",
"misc",
"=",
"config",
"[",
"'misc'",
"]",
"misc",
"[",
"'iot_endpoint'",
"]",
"=",
"ep",
"[",
"'endpointAddress'",
"]",
"config",
"[",
"'misc'",
"]",
"=",
"misc",
"# Create a Group",
"logging",
".",
"info",
"(",
"\"[begin] Creating a Greengrass Group\"",
")",
"if",
"group_name",
"is",
"None",
":",
"group_name",
"=",
"group_type",
"gg_client",
"=",
"_get_gg_session",
"(",
"region",
"=",
"region",
",",
"profile_name",
"=",
"profile_name",
")",
"group_info",
"=",
"gg_client",
".",
"create_group",
"(",
"Name",
"=",
"\"{0}\"",
".",
"format",
"(",
"group_name",
")",
")",
"config",
"[",
"'group'",
"]",
"=",
"{",
"\"id\"",
":",
"group_info",
"[",
"'Id'",
"]",
"}",
"# setup the policies and roles",
"gt",
".",
"create_and_attach_thing_policy",
"(",
")",
"gt",
".",
"create_and_attach_iam_role",
"(",
")",
"cl_arn",
"=",
"self",
".",
"_create_core_definition",
"(",
"gg_client",
"=",
"gg_client",
",",
"group_type",
"=",
"gt",
",",
"config",
"=",
"config",
",",
"group_name",
"=",
"group_name",
")",
"dl_arn",
"=",
"self",
".",
"_create_device_definition",
"(",
"gg_client",
"=",
"gg_client",
",",
"group_type",
"=",
"gt",
",",
"config",
"=",
"config",
",",
"group_name",
"=",
"group_name",
")",
"lv_arn",
"=",
"self",
".",
"_create_function_definition",
"(",
"gg_client",
"=",
"gg_client",
",",
"group_type",
"=",
"gt",
",",
"config",
"=",
"config",
")",
"log_arn",
"=",
"self",
".",
"_create_logger_definition",
"(",
"gg_client",
"=",
"gg_client",
",",
"group_type",
"=",
"gt",
",",
"config",
"=",
"config",
")",
"sub_arn",
"=",
"self",
".",
"_create_subscription_definition",
"(",
"gg_client",
"=",
"gg_client",
",",
"group_type",
"=",
"gt",
",",
"config",
"=",
"config",
")",
"logging",
".",
"info",
"(",
"'Group details, core_def:{0} device_def:{1} func_def:{2} '",
"'logger_def:{3} subs_def:{4}'",
".",
"format",
"(",
"cl_arn",
",",
"dl_arn",
",",
"lv_arn",
",",
"log_arn",
",",
"sub_arn",
")",
")",
"# Add all the constituent parts to the Greengrass Group",
"group_args",
"=",
"{",
"'GroupId'",
":",
"group_info",
"[",
"'Id'",
"]",
"}",
"if",
"cl_arn",
":",
"group_args",
"[",
"'CoreDefinitionVersionArn'",
"]",
"=",
"cl_arn",
"if",
"dl_arn",
":",
"group_args",
"[",
"'DeviceDefinitionVersionArn'",
"]",
"=",
"dl_arn",
"if",
"lv_arn",
":",
"group_args",
"[",
"'FunctionDefinitionVersionArn'",
"]",
"=",
"lv_arn",
"if",
"log_arn",
":",
"group_args",
"[",
"'LoggerDefinitionVersionArn'",
"]",
"=",
"log_arn",
"if",
"sub_arn",
":",
"group_args",
"[",
"'SubscriptionDefinitionVersionArn'",
"]",
"=",
"sub_arn",
"grp",
"=",
"gg_client",
".",
"create_group_version",
"(",
"*",
"*",
"group_args",
")",
"# store info about the provisioned artifacts into the local config file",
"config",
"[",
"'group'",
"]",
"=",
"{",
"\"id\"",
":",
"group_info",
"[",
"'Id'",
"]",
",",
"\"version_arn\"",
":",
"grp",
"[",
"'Arn'",
"]",
",",
"\"version\"",
":",
"grp",
"[",
"'Version'",
"]",
",",
"\"name\"",
":",
"group_name",
"}",
"logging",
".",
"info",
"(",
"\"[end] Created Greengrass Group {0}\"",
".",
"format",
"(",
"group_info",
"[",
"'Id'",
"]",
")",
")"
] | Create a Greengrass group in the given region.
:param group_type: the type of group to create. Must match a `key` in
the `group_types` dict
:param config_file: config file of the group to create
:param group_name: the name of the group. If no name is given, then
group_type will be used.
:param region: the region in which to create the new group.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None] | [
"Create",
"a",
"Greengrass",
"group",
"in",
"the",
"given",
"region",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L73-L180 |
3,493 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands._create_subscription_definition | def _create_subscription_definition(gg_client, group_type, config):
"""
Configure routing subscriptions for a Greengrass group.
group_type: either default or an overridden group type
config: GroupConfigFile object used for routing subscriptions
"""
logging.info('[begin] Configuring routing subscriptions')
sub_info = gg_client.create_subscription_definition(
Name="{0}_routing".format(group_type.type_name)
)
logging.info('Created subscription definition: {0}'.format(sub_info))
subs = group_type.get_subscription_definition(config=config)
if subs is None:
logging.warning(
"[end] No SubscriptionDefinition exists in GroupType:{0}".format(
group_type.type_name)
)
return
subv = gg_client.create_subscription_definition_version(
SubscriptionDefinitionId=sub_info['Id'],
Subscriptions=subs
)
sub_arn = subv['Arn']
config['subscription_def'] = {
"id": sub_info['Id'],
"version_arn": sub_arn
}
logging.info('[end] Configured routing subscriptions')
return sub_arn | python | def _create_subscription_definition(gg_client, group_type, config):
"""
Configure routing subscriptions for a Greengrass group.
group_type: either default or an overridden group type
config: GroupConfigFile object used for routing subscriptions
"""
logging.info('[begin] Configuring routing subscriptions')
sub_info = gg_client.create_subscription_definition(
Name="{0}_routing".format(group_type.type_name)
)
logging.info('Created subscription definition: {0}'.format(sub_info))
subs = group_type.get_subscription_definition(config=config)
if subs is None:
logging.warning(
"[end] No SubscriptionDefinition exists in GroupType:{0}".format(
group_type.type_name)
)
return
subv = gg_client.create_subscription_definition_version(
SubscriptionDefinitionId=sub_info['Id'],
Subscriptions=subs
)
sub_arn = subv['Arn']
config['subscription_def'] = {
"id": sub_info['Id'],
"version_arn": sub_arn
}
logging.info('[end] Configured routing subscriptions')
return sub_arn | [
"def",
"_create_subscription_definition",
"(",
"gg_client",
",",
"group_type",
",",
"config",
")",
":",
"logging",
".",
"info",
"(",
"'[begin] Configuring routing subscriptions'",
")",
"sub_info",
"=",
"gg_client",
".",
"create_subscription_definition",
"(",
"Name",
"=",
"\"{0}_routing\"",
".",
"format",
"(",
"group_type",
".",
"type_name",
")",
")",
"logging",
".",
"info",
"(",
"'Created subscription definition: {0}'",
".",
"format",
"(",
"sub_info",
")",
")",
"subs",
"=",
"group_type",
".",
"get_subscription_definition",
"(",
"config",
"=",
"config",
")",
"if",
"subs",
"is",
"None",
":",
"logging",
".",
"warning",
"(",
"\"[end] No SubscriptionDefinition exists in GroupType:{0}\"",
".",
"format",
"(",
"group_type",
".",
"type_name",
")",
")",
"return",
"subv",
"=",
"gg_client",
".",
"create_subscription_definition_version",
"(",
"SubscriptionDefinitionId",
"=",
"sub_info",
"[",
"'Id'",
"]",
",",
"Subscriptions",
"=",
"subs",
")",
"sub_arn",
"=",
"subv",
"[",
"'Arn'",
"]",
"config",
"[",
"'subscription_def'",
"]",
"=",
"{",
"\"id\"",
":",
"sub_info",
"[",
"'Id'",
"]",
",",
"\"version_arn\"",
":",
"sub_arn",
"}",
"logging",
".",
"info",
"(",
"'[end] Configured routing subscriptions'",
")",
"return",
"sub_arn"
] | Configure routing subscriptions for a Greengrass group.
group_type: either default or an overridden group type
config: GroupConfigFile object used for routing subscriptions | [
"Configure",
"routing",
"subscriptions",
"for",
"a",
"Greengrass",
"group",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L321-L352 |
3,494 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.clean_core | def clean_core(self, config_file, region=None, profile_name=None):
"""
Clean all Core related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the core to clean
:param region: the region in which the core should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
:return:
"""
config = GroupConfigFile(config_file=config_file)
if region is None:
region = self._region
# delete the Core's Certificate
core_cert_id = config['core']['cert_id']
core_cert_arn = config['core']['cert_arn']
core_thing_name = config['core']['thing_name']
policy_name = config['misc']['policy_name']
logging.info('Deleting core_thing_name:{0}'.format(core_thing_name))
GroupCommands._delete_thing(
cert_arn=core_cert_arn, cert_id=core_cert_id,
thing_name=core_thing_name, region=region,
policy_name=policy_name, profile_name=profile_name
)
config.make_core_fresh() | python | def clean_core(self, config_file, region=None, profile_name=None):
"""
Clean all Core related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the core to clean
:param region: the region in which the core should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
:return:
"""
config = GroupConfigFile(config_file=config_file)
if region is None:
region = self._region
# delete the Core's Certificate
core_cert_id = config['core']['cert_id']
core_cert_arn = config['core']['cert_arn']
core_thing_name = config['core']['thing_name']
policy_name = config['misc']['policy_name']
logging.info('Deleting core_thing_name:{0}'.format(core_thing_name))
GroupCommands._delete_thing(
cert_arn=core_cert_arn, cert_id=core_cert_id,
thing_name=core_thing_name, region=region,
policy_name=policy_name, profile_name=profile_name
)
config.make_core_fresh() | [
"def",
"clean_core",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"# delete the Core's Certificate",
"core_cert_id",
"=",
"config",
"[",
"'core'",
"]",
"[",
"'cert_id'",
"]",
"core_cert_arn",
"=",
"config",
"[",
"'core'",
"]",
"[",
"'cert_arn'",
"]",
"core_thing_name",
"=",
"config",
"[",
"'core'",
"]",
"[",
"'thing_name'",
"]",
"policy_name",
"=",
"config",
"[",
"'misc'",
"]",
"[",
"'policy_name'",
"]",
"logging",
".",
"info",
"(",
"'Deleting core_thing_name:{0}'",
".",
"format",
"(",
"core_thing_name",
")",
")",
"GroupCommands",
".",
"_delete_thing",
"(",
"cert_arn",
"=",
"core_cert_arn",
",",
"cert_id",
"=",
"core_cert_id",
",",
"thing_name",
"=",
"core_thing_name",
",",
"region",
"=",
"region",
",",
"policy_name",
"=",
"policy_name",
",",
"profile_name",
"=",
"profile_name",
")",
"config",
".",
"make_core_fresh",
"(",
")"
] | Clean all Core related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the core to clean
:param region: the region in which the core should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
:return: | [
"Clean",
"all",
"Core",
"related",
"provisioned",
"artifacts",
"from",
"both",
"the",
"local",
"file",
"and",
"the",
"AWS",
"Greengrass",
"service",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L490-L518 |
3,495 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.clean_devices | def clean_devices(self, config_file, region=None, profile_name=None):
"""
Clean all device related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the devices to clean
:param region: the region in which the devices should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if region is None:
region = self._region
devices = config['devices']
if 'device_thing_name' in devices:
logging.info('Configured devices already clean')
return
policy_name = config['misc']['policy_name']
for device in devices:
cert_arn = devices[device]['cert_arn']
cert_id = devices[device]['cert_id']
thing_name = device
logging.info('Deleting device_thing_name:{0}'.format(thing_name))
GroupCommands._delete_thing(
cert_arn, cert_id, thing_name, region, policy_name, profile_name
)
config.make_devices_fresh() | python | def clean_devices(self, config_file, region=None, profile_name=None):
"""
Clean all device related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the devices to clean
:param region: the region in which the devices should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if region is None:
region = self._region
devices = config['devices']
if 'device_thing_name' in devices:
logging.info('Configured devices already clean')
return
policy_name = config['misc']['policy_name']
for device in devices:
cert_arn = devices[device]['cert_arn']
cert_id = devices[device]['cert_id']
thing_name = device
logging.info('Deleting device_thing_name:{0}'.format(thing_name))
GroupCommands._delete_thing(
cert_arn, cert_id, thing_name, region, policy_name, profile_name
)
config.make_devices_fresh() | [
"def",
"clean_devices",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"devices",
"=",
"config",
"[",
"'devices'",
"]",
"if",
"'device_thing_name'",
"in",
"devices",
":",
"logging",
".",
"info",
"(",
"'Configured devices already clean'",
")",
"return",
"policy_name",
"=",
"config",
"[",
"'misc'",
"]",
"[",
"'policy_name'",
"]",
"for",
"device",
"in",
"devices",
":",
"cert_arn",
"=",
"devices",
"[",
"device",
"]",
"[",
"'cert_arn'",
"]",
"cert_id",
"=",
"devices",
"[",
"device",
"]",
"[",
"'cert_id'",
"]",
"thing_name",
"=",
"device",
"logging",
".",
"info",
"(",
"'Deleting device_thing_name:{0}'",
".",
"format",
"(",
"thing_name",
")",
")",
"GroupCommands",
".",
"_delete_thing",
"(",
"cert_arn",
",",
"cert_id",
",",
"thing_name",
",",
"region",
",",
"policy_name",
",",
"profile_name",
")",
"config",
".",
"make_devices_fresh",
"(",
")"
] | Clean all device related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the devices to clean
:param region: the region in which the devices should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None] | [
"Clean",
"all",
"device",
"related",
"provisioned",
"artifacts",
"from",
"both",
"the",
"local",
"file",
"and",
"the",
"AWS",
"Greengrass",
"service",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L520-L549 |
3,496 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.clean_file | def clean_file(config_file):
"""
Clean all provisioned artifacts from the local config file.
:param config_file: config file of the group to clean
"""
logging.info('[begin] Cleaning config file')
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is True:
raise ValueError("Config is already clean.")
config.make_fresh()
logging.info('[end] Cleaned config file:{0}'.format(config_file)) | python | def clean_file(config_file):
"""
Clean all provisioned artifacts from the local config file.
:param config_file: config file of the group to clean
"""
logging.info('[begin] Cleaning config file')
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is True:
raise ValueError("Config is already clean.")
config.make_fresh()
logging.info('[end] Cleaned config file:{0}'.format(config_file)) | [
"def",
"clean_file",
"(",
"config_file",
")",
":",
"logging",
".",
"info",
"(",
"'[begin] Cleaning config file'",
")",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
"is",
"True",
":",
"raise",
"ValueError",
"(",
"\"Config is already clean.\"",
")",
"config",
".",
"make_fresh",
"(",
")",
"logging",
".",
"info",
"(",
"'[end] Cleaned config file:{0}'",
".",
"format",
"(",
"config_file",
")",
")"
] | Clean all provisioned artifacts from the local config file.
:param config_file: config file of the group to clean | [
"Clean",
"all",
"provisioned",
"artifacts",
"from",
"the",
"local",
"config",
"file",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L552-L564 |
3,497 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.clean_all | def clean_all(self, config_file, region=None, profile_name=None):
"""
Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
logging.info('[begin] Cleaning all provisioned artifacts')
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is True:
raise ValueError("Config is already clean.")
if region is None:
region = self._region
self._delete_group(
config_file, region=region, profile_name=profile_name)
self.clean_core(config_file, region=region)
self.clean_devices(config_file, region=region)
self.clean_file(config_file)
logging.info('[end] Cleaned all provisioned artifacts') | python | def clean_all(self, config_file, region=None, profile_name=None):
"""
Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
logging.info('[begin] Cleaning all provisioned artifacts')
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is True:
raise ValueError("Config is already clean.")
if region is None:
region = self._region
self._delete_group(
config_file, region=region, profile_name=profile_name)
self.clean_core(config_file, region=region)
self.clean_devices(config_file, region=region)
self.clean_file(config_file)
logging.info('[end] Cleaned all provisioned artifacts') | [
"def",
"clean_all",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"'[begin] Cleaning all provisioned artifacts'",
")",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
"is",
"True",
":",
"raise",
"ValueError",
"(",
"\"Config is already clean.\"",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"self",
".",
"_delete_group",
"(",
"config_file",
",",
"region",
"=",
"region",
",",
"profile_name",
"=",
"profile_name",
")",
"self",
".",
"clean_core",
"(",
"config_file",
",",
"region",
"=",
"region",
")",
"self",
".",
"clean_devices",
"(",
"config_file",
",",
"region",
"=",
"region",
")",
"self",
".",
"clean_file",
"(",
"config_file",
")",
"logging",
".",
"info",
"(",
"'[end] Cleaned all provisioned artifacts'",
")"
] | Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cleaned.
[default: us-west-2]
:param profile_name: the name of the `awscli` profile to use.
[default: None] | [
"Clean",
"all",
"provisioned",
"artifacts",
"from",
"both",
"the",
"local",
"file",
"and",
"the",
"AWS",
"Greengrass",
"service",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L566-L591 |
3,498 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.deploy | def deploy(self, config_file, region=None, profile_name=None):
"""
Deploy the configuration and Lambda functions of a Greengrass group to
the Greengrass core contained in the group.
:param config_file: config file of the group to deploy
:param region: the region from which to deploy the group.
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if config.is_fresh():
raise ValueError("Config not yet tracking a group. Cannot deploy.")
if region is None:
region = self._region
gg_client = _get_gg_session(region=region, profile_name=profile_name)
dep_req = gg_client.create_deployment(
GroupId=config['group']['id'],
GroupVersionId=config['group']['version'],
DeploymentType="NewDeployment"
)
print("Group deploy requested for deployment_id:{0}".format(
dep_req['DeploymentId'],
)) | python | def deploy(self, config_file, region=None, profile_name=None):
"""
Deploy the configuration and Lambda functions of a Greengrass group to
the Greengrass core contained in the group.
:param config_file: config file of the group to deploy
:param region: the region from which to deploy the group.
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if config.is_fresh():
raise ValueError("Config not yet tracking a group. Cannot deploy.")
if region is None:
region = self._region
gg_client = _get_gg_session(region=region, profile_name=profile_name)
dep_req = gg_client.create_deployment(
GroupId=config['group']['id'],
GroupVersionId=config['group']['version'],
DeploymentType="NewDeployment"
)
print("Group deploy requested for deployment_id:{0}".format(
dep_req['DeploymentId'],
)) | [
"def",
"deploy",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Config not yet tracking a group. Cannot deploy.\"",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"gg_client",
"=",
"_get_gg_session",
"(",
"region",
"=",
"region",
",",
"profile_name",
"=",
"profile_name",
")",
"dep_req",
"=",
"gg_client",
".",
"create_deployment",
"(",
"GroupId",
"=",
"config",
"[",
"'group'",
"]",
"[",
"'id'",
"]",
",",
"GroupVersionId",
"=",
"config",
"[",
"'group'",
"]",
"[",
"'version'",
"]",
",",
"DeploymentType",
"=",
"\"NewDeployment\"",
")",
"print",
"(",
"\"Group deploy requested for deployment_id:{0}\"",
".",
"format",
"(",
"dep_req",
"[",
"'DeploymentId'",
"]",
",",
")",
")"
] | Deploy the configuration and Lambda functions of a Greengrass group to
the Greengrass core contained in the group.
:param config_file: config file of the group to deploy
:param region: the region from which to deploy the group.
:param profile_name: the name of the `awscli` profile to use.
[default: None] | [
"Deploy",
"the",
"configuration",
"and",
"Lambda",
"functions",
"of",
"a",
"Greengrass",
"group",
"to",
"the",
"Greengrass",
"core",
"contained",
"in",
"the",
"group",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L593-L619 |
3,499 | awslabs/aws-greengrass-group-setup | gg_group_setup/cmd.py | GroupCommands.create_core | def create_core(self, thing_name, config_file, region=None,
cert_dir=None, account_id=None,
policy_name='ggc-default-policy', profile_name=None):
"""
Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the certificate directory, then records
the created information in the local config file for inclusion in the
Greengrass Group as a Greengrass Core.
:param thing_name: the name of the thing to create and use as a
Greengrass Core
:param config_file: config file used to track the Greengrass Core in the
group
:param region: the region in which to create the new core.
[default: us-west-2]
:param cert_dir: the directory in which to store the thing's keys and
certs. If `None` then use the current directory.
:param account_id: the account_id in which to create the new core.
[default: None]
:param policy_name: the name of the policy to associate with the device.
[default: 'ggc-default-policy']
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is False:
raise ValueError(
"Config file already tracking previously created core or group"
)
if region is None:
region = self._region
if account_id is None:
account_id = self._account_id
keys_cert, thing = self.create_thing(thing_name, region, cert_dir)
cert_arn = keys_cert['certificateArn']
config['core'] = {
'thing_arn': thing['thingArn'],
'cert_arn': cert_arn,
'cert_id': keys_cert['certificateId'],
'thing_name': thing_name
}
logging.debug("create_core cfg:{0}".format(config))
logging.info("Thing:'{0}' associated with cert:'{1}'".format(
thing_name, cert_arn))
core_policy = self.get_core_policy(
core_name=thing_name, account_id=account_id, region=region)
iot_client = _get_iot_session(region=region, profile_name=profile_name)
self._create_attach_thing_policy(
cert_arn, core_policy,
iot_client=iot_client, policy_name=policy_name
)
misc = config['misc']
misc['policy_name'] = policy_name
config['misc'] = misc | python | def create_core(self, thing_name, config_file, region=None,
cert_dir=None, account_id=None,
policy_name='ggc-default-policy', profile_name=None):
"""
Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the certificate directory, then records
the created information in the local config file for inclusion in the
Greengrass Group as a Greengrass Core.
:param thing_name: the name of the thing to create and use as a
Greengrass Core
:param config_file: config file used to track the Greengrass Core in the
group
:param region: the region in which to create the new core.
[default: us-west-2]
:param cert_dir: the directory in which to store the thing's keys and
certs. If `None` then use the current directory.
:param account_id: the account_id in which to create the new core.
[default: None]
:param policy_name: the name of the policy to associate with the device.
[default: 'ggc-default-policy']
:param profile_name: the name of the `awscli` profile to use.
[default: None]
"""
config = GroupConfigFile(config_file=config_file)
if config.is_fresh() is False:
raise ValueError(
"Config file already tracking previously created core or group"
)
if region is None:
region = self._region
if account_id is None:
account_id = self._account_id
keys_cert, thing = self.create_thing(thing_name, region, cert_dir)
cert_arn = keys_cert['certificateArn']
config['core'] = {
'thing_arn': thing['thingArn'],
'cert_arn': cert_arn,
'cert_id': keys_cert['certificateId'],
'thing_name': thing_name
}
logging.debug("create_core cfg:{0}".format(config))
logging.info("Thing:'{0}' associated with cert:'{1}'".format(
thing_name, cert_arn))
core_policy = self.get_core_policy(
core_name=thing_name, account_id=account_id, region=region)
iot_client = _get_iot_session(region=region, profile_name=profile_name)
self._create_attach_thing_policy(
cert_arn, core_policy,
iot_client=iot_client, policy_name=policy_name
)
misc = config['misc']
misc['policy_name'] = policy_name
config['misc'] = misc | [
"def",
"create_core",
"(",
"self",
",",
"thing_name",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"cert_dir",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"policy_name",
"=",
"'ggc-default-policy'",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"Config file already tracking previously created core or group\"",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"if",
"account_id",
"is",
"None",
":",
"account_id",
"=",
"self",
".",
"_account_id",
"keys_cert",
",",
"thing",
"=",
"self",
".",
"create_thing",
"(",
"thing_name",
",",
"region",
",",
"cert_dir",
")",
"cert_arn",
"=",
"keys_cert",
"[",
"'certificateArn'",
"]",
"config",
"[",
"'core'",
"]",
"=",
"{",
"'thing_arn'",
":",
"thing",
"[",
"'thingArn'",
"]",
",",
"'cert_arn'",
":",
"cert_arn",
",",
"'cert_id'",
":",
"keys_cert",
"[",
"'certificateId'",
"]",
",",
"'thing_name'",
":",
"thing_name",
"}",
"logging",
".",
"debug",
"(",
"\"create_core cfg:{0}\"",
".",
"format",
"(",
"config",
")",
")",
"logging",
".",
"info",
"(",
"\"Thing:'{0}' associated with cert:'{1}'\"",
".",
"format",
"(",
"thing_name",
",",
"cert_arn",
")",
")",
"core_policy",
"=",
"self",
".",
"get_core_policy",
"(",
"core_name",
"=",
"thing_name",
",",
"account_id",
"=",
"account_id",
",",
"region",
"=",
"region",
")",
"iot_client",
"=",
"_get_iot_session",
"(",
"region",
"=",
"region",
",",
"profile_name",
"=",
"profile_name",
")",
"self",
".",
"_create_attach_thing_policy",
"(",
"cert_arn",
",",
"core_policy",
",",
"iot_client",
"=",
"iot_client",
",",
"policy_name",
"=",
"policy_name",
")",
"misc",
"=",
"config",
"[",
"'misc'",
"]",
"misc",
"[",
"'policy_name'",
"]",
"=",
"policy_name",
"config",
"[",
"'misc'",
"]",
"=",
"misc"
] | Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the certificate directory, then records
the created information in the local config file for inclusion in the
Greengrass Group as a Greengrass Core.
:param thing_name: the name of the thing to create and use as a
Greengrass Core
:param config_file: config file used to track the Greengrass Core in the
group
:param region: the region in which to create the new core.
[default: us-west-2]
:param cert_dir: the directory in which to store the thing's keys and
certs. If `None` then use the current directory.
:param account_id: the account_id in which to create the new core.
[default: None]
:param policy_name: the name of the policy to associate with the device.
[default: 'ggc-default-policy']
:param profile_name: the name of the `awscli` profile to use.
[default: None] | [
"Using",
"the",
"thing_name",
"value",
"creates",
"a",
"Thing",
"in",
"AWS",
"IoT",
"attaches",
"and",
"downloads",
"new",
"keys",
"&",
"certs",
"to",
"the",
"certificate",
"directory",
"then",
"records",
"the",
"created",
"information",
"in",
"the",
"local",
"config",
"file",
"for",
"inclusion",
"in",
"the",
"Greengrass",
"Group",
"as",
"a",
"Greengrass",
"Core",
"."
] | 06189ceccb794fedf80e0e7649938c18792e16c9 | https://github.com/awslabs/aws-greengrass-group-setup/blob/06189ceccb794fedf80e0e7649938c18792e16c9/gg_group_setup/cmd.py#L679-L733 |
Subsets and Splits