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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_midi_event
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read event type " "and channel data from file.") # Get the nibbles event_type = (ec & 0xf0) >> 4 channel = ec & 0x0f # I don't know what these events are supposed to do, but I keep finding # them. The parser ignores them. if event_type < 8: raise FormatError('Unknown event type %d. Byte %d.' % (event_type, self.bytes_read)) # Meta events can have strings of variable length if event_type == 0x0f: try: meta_event = self.bytes_to_int(fp.read(1)) (length, chunk_delta) = self.parse_varbyte_as_int(fp) data = fp.read(length) chunk_size += 1 + chunk_delta + length self.bytes_read += 1 + length except: raise IOError("Couldn't read meta event from file.") return ({'event': event_type, 'meta_event': meta_event, 'data': data}, chunk_size) elif event_type in [12, 13]: # Program change and Channel aftertouch events only have one # parameter try: param1 = fp.read(1) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) return ({'event': event_type, 'channel': channel, 'param1': param1}, chunk_size) else: try: param1 = fp.read(1) param2 = fp.read(1) chunk_size += 2 self.bytes_read += 2 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) param2 = self.bytes_to_int(param2) return ({'event': event_type, 'channel': channel, 'param1': param1, 'param2': param2}, chunk_size)
python
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read event type " "and channel data from file.") # Get the nibbles event_type = (ec & 0xf0) >> 4 channel = ec & 0x0f # I don't know what these events are supposed to do, but I keep finding # them. The parser ignores them. if event_type < 8: raise FormatError('Unknown event type %d. Byte %d.' % (event_type, self.bytes_read)) # Meta events can have strings of variable length if event_type == 0x0f: try: meta_event = self.bytes_to_int(fp.read(1)) (length, chunk_delta) = self.parse_varbyte_as_int(fp) data = fp.read(length) chunk_size += 1 + chunk_delta + length self.bytes_read += 1 + length except: raise IOError("Couldn't read meta event from file.") return ({'event': event_type, 'meta_event': meta_event, 'data': data}, chunk_size) elif event_type in [12, 13]: # Program change and Channel aftertouch events only have one # parameter try: param1 = fp.read(1) chunk_size += 1 self.bytes_read += 1 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) return ({'event': event_type, 'channel': channel, 'param1': param1}, chunk_size) else: try: param1 = fp.read(1) param2 = fp.read(1) chunk_size += 2 self.bytes_read += 2 except: raise IOError("Couldn't read MIDI event parameters from file.") param1 = self.bytes_to_int(param1) param2 = self.bytes_to_int(param2) return ({'event': event_type, 'channel': channel, 'param1': param1, 'param2': param2}, chunk_size)
[ "def", "parse_midi_event", "(", "self", ",", "fp", ")", ":", "chunk_size", "=", "0", "try", ":", "ec", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "1", ")", ")", "chunk_size", "+=", "1", "self", ".", "bytes_read", "+=", "1", "except", ":", "raise", "IOError", "(", "\"Couldn't read event type \"", "\"and channel data from file.\"", ")", "# Get the nibbles", "event_type", "=", "(", "ec", "&", "0xf0", ")", ">>", "4", "channel", "=", "ec", "&", "0x0f", "# I don't know what these events are supposed to do, but I keep finding", "# them. The parser ignores them.", "if", "event_type", "<", "8", ":", "raise", "FormatError", "(", "'Unknown event type %d. Byte %d.'", "%", "(", "event_type", ",", "self", ".", "bytes_read", ")", ")", "# Meta events can have strings of variable length", "if", "event_type", "==", "0x0f", ":", "try", ":", "meta_event", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "1", ")", ")", "(", "length", ",", "chunk_delta", ")", "=", "self", ".", "parse_varbyte_as_int", "(", "fp", ")", "data", "=", "fp", ".", "read", "(", "length", ")", "chunk_size", "+=", "1", "+", "chunk_delta", "+", "length", "self", ".", "bytes_read", "+=", "1", "+", "length", "except", ":", "raise", "IOError", "(", "\"Couldn't read meta event from file.\"", ")", "return", "(", "{", "'event'", ":", "event_type", ",", "'meta_event'", ":", "meta_event", ",", "'data'", ":", "data", "}", ",", "chunk_size", ")", "elif", "event_type", "in", "[", "12", ",", "13", "]", ":", "# Program change and Channel aftertouch events only have one", "# parameter", "try", ":", "param1", "=", "fp", ".", "read", "(", "1", ")", "chunk_size", "+=", "1", "self", ".", "bytes_read", "+=", "1", "except", ":", "raise", "IOError", "(", "\"Couldn't read MIDI event parameters from file.\"", ")", "param1", "=", "self", ".", "bytes_to_int", "(", "param1", ")", "return", "(", "{", "'event'", ":", "event_type", ",", "'channel'", ":", "channel", ",", "'param1'", ":", "param1", "}", ",", "chunk_size", ")", "else", ":", "try", ":", "param1", "=", "fp", ".", "read", "(", "1", ")", "param2", "=", "fp", ".", "read", "(", "1", ")", "chunk_size", "+=", "2", "self", ".", "bytes_read", "+=", "2", "except", ":", "raise", "IOError", "(", "\"Couldn't read MIDI event parameters from file.\"", ")", "param1", "=", "self", ".", "bytes_to_int", "(", "param1", ")", "param2", "=", "self", ".", "bytes_to_int", "(", "param2", ")", "return", "(", "{", "'event'", ":", "event_type", ",", "'channel'", ":", "channel", ",", "'param1'", ":", "param1", ",", "'param2'", ":", "param2", "}", ",", "chunk_size", ")" ]
Parse a MIDI event. Return a dictionary and the number of bytes read.
[ "Parse", "a", "MIDI", "event", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L261-L320
train
236,200
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_track_header
def parse_track_header(self, fp): """Return the size of the track chunk.""" # Check the header try: h = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track header from file. Byte %d." % self.bytes_read) if h != 'MTrk': raise HeaderError('Not a valid Track header. Byte %d.' % self.bytes_read) # Parse the size of the header try: chunk_size = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track chunk size from file.") chunk_size = self.bytes_to_int(chunk_size) return chunk_size
python
def parse_track_header(self, fp): """Return the size of the track chunk.""" # Check the header try: h = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track header from file. Byte %d." % self.bytes_read) if h != 'MTrk': raise HeaderError('Not a valid Track header. Byte %d.' % self.bytes_read) # Parse the size of the header try: chunk_size = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track chunk size from file.") chunk_size = self.bytes_to_int(chunk_size) return chunk_size
[ "def", "parse_track_header", "(", "self", ",", "fp", ")", ":", "# Check the header", "try", ":", "h", "=", "fp", ".", "read", "(", "4", ")", "self", ".", "bytes_read", "+=", "4", "except", ":", "raise", "IOError", "(", "\"Couldn't read track header from file. Byte %d.\"", "%", "self", ".", "bytes_read", ")", "if", "h", "!=", "'MTrk'", ":", "raise", "HeaderError", "(", "'Not a valid Track header. Byte %d.'", "%", "self", ".", "bytes_read", ")", "# Parse the size of the header", "try", ":", "chunk_size", "=", "fp", ".", "read", "(", "4", ")", "self", ".", "bytes_read", "+=", "4", "except", ":", "raise", "IOError", "(", "\"Couldn't read track chunk size from file.\"", ")", "chunk_size", "=", "self", ".", "bytes_to_int", "(", "chunk_size", ")", "return", "chunk_size" ]
Return the size of the track chunk.
[ "Return", "the", "size", "of", "the", "track", "chunk", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L322-L342
train
236,201
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_varbyte_as_int
def parse_varbyte_as_int(self, fp, return_bytes_read=True): """Read a variable length byte from the file and return the corresponding integer.""" result = 0 bytes_read = 0 r = 0x80 while r & 0x80: try: r = self.bytes_to_int(fp.read(1)) self.bytes_read += 1 except: raise IOError("Couldn't read variable length byte from file.") if r & 0x80: result = (result << 7) + (r & 0x7F) else: result = (result << 7) + r bytes_read += 1 if not return_bytes_read: return result else: return (result, bytes_read)
python
def parse_varbyte_as_int(self, fp, return_bytes_read=True): """Read a variable length byte from the file and return the corresponding integer.""" result = 0 bytes_read = 0 r = 0x80 while r & 0x80: try: r = self.bytes_to_int(fp.read(1)) self.bytes_read += 1 except: raise IOError("Couldn't read variable length byte from file.") if r & 0x80: result = (result << 7) + (r & 0x7F) else: result = (result << 7) + r bytes_read += 1 if not return_bytes_read: return result else: return (result, bytes_read)
[ "def", "parse_varbyte_as_int", "(", "self", ",", "fp", ",", "return_bytes_read", "=", "True", ")", ":", "result", "=", "0", "bytes_read", "=", "0", "r", "=", "0x80", "while", "r", "&", "0x80", ":", "try", ":", "r", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "1", ")", ")", "self", ".", "bytes_read", "+=", "1", "except", ":", "raise", "IOError", "(", "\"Couldn't read variable length byte from file.\"", ")", "if", "r", "&", "0x80", ":", "result", "=", "(", "result", "<<", "7", ")", "+", "(", "r", "&", "0x7F", ")", "else", ":", "result", "=", "(", "result", "<<", "7", ")", "+", "r", "bytes_read", "+=", "1", "if", "not", "return_bytes_read", ":", "return", "result", "else", ":", "return", "(", "result", ",", "bytes_read", ")" ]
Read a variable length byte from the file and return the corresponding integer.
[ "Read", "a", "variable", "length", "byte", "from", "the", "file", "and", "return", "the", "corresponding", "integer", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L366-L386
train
236,202
bspaans/python-mingus
mingus/containers/note.py
Note.set_note
def set_note(self, name='C', octave=4, dynamics={}): """Set the note to name in octave with dynamics. Return the objects if it succeeded, raise an NoteFormatError otherwise. """ dash_index = name.split('-') if len(dash_index) == 1: if notes.is_valid_note(name): self.name = name self.octave = octave self.dynamics = dynamics return self else: raise NoteFormatError("The string '%s' is not a valid " "representation of a note in mingus" % name) elif len(dash_index) == 2: if notes.is_valid_note(dash_index[0]): self.name = dash_index[0] self.octave = int(dash_index[1]) self.dynamics = dynamics return self else: raise NoteFormatError("The string '%s' is not a valid " "representation of a note in mingus" % name) return False
python
def set_note(self, name='C', octave=4, dynamics={}): """Set the note to name in octave with dynamics. Return the objects if it succeeded, raise an NoteFormatError otherwise. """ dash_index = name.split('-') if len(dash_index) == 1: if notes.is_valid_note(name): self.name = name self.octave = octave self.dynamics = dynamics return self else: raise NoteFormatError("The string '%s' is not a valid " "representation of a note in mingus" % name) elif len(dash_index) == 2: if notes.is_valid_note(dash_index[0]): self.name = dash_index[0] self.octave = int(dash_index[1]) self.dynamics = dynamics return self else: raise NoteFormatError("The string '%s' is not a valid " "representation of a note in mingus" % name) return False
[ "def", "set_note", "(", "self", ",", "name", "=", "'C'", ",", "octave", "=", "4", ",", "dynamics", "=", "{", "}", ")", ":", "dash_index", "=", "name", ".", "split", "(", "'-'", ")", "if", "len", "(", "dash_index", ")", "==", "1", ":", "if", "notes", ".", "is_valid_note", "(", "name", ")", ":", "self", ".", "name", "=", "name", "self", ".", "octave", "=", "octave", "self", ".", "dynamics", "=", "dynamics", "return", "self", "else", ":", "raise", "NoteFormatError", "(", "\"The string '%s' is not a valid \"", "\"representation of a note in mingus\"", "%", "name", ")", "elif", "len", "(", "dash_index", ")", "==", "2", ":", "if", "notes", ".", "is_valid_note", "(", "dash_index", "[", "0", "]", ")", ":", "self", ".", "name", "=", "dash_index", "[", "0", "]", "self", ".", "octave", "=", "int", "(", "dash_index", "[", "1", "]", ")", "self", ".", "dynamics", "=", "dynamics", "return", "self", "else", ":", "raise", "NoteFormatError", "(", "\"The string '%s' is not a valid \"", "\"representation of a note in mingus\"", "%", "name", ")", "return", "False" ]
Set the note to name in octave with dynamics. Return the objects if it succeeded, raise an NoteFormatError otherwise.
[ "Set", "the", "note", "to", "name", "in", "octave", "with", "dynamics", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L70-L95
train
236,203
bspaans/python-mingus
mingus/containers/note.py
Note.change_octave
def change_octave(self, diff): """Change the octave of the note to the current octave + diff.""" self.octave += diff if self.octave < 0: self.octave = 0
python
def change_octave(self, diff): """Change the octave of the note to the current octave + diff.""" self.octave += diff if self.octave < 0: self.octave = 0
[ "def", "change_octave", "(", "self", ",", "diff", ")", ":", "self", ".", "octave", "+=", "diff", "if", "self", ".", "octave", "<", "0", ":", "self", ".", "octave", "=", "0" ]
Change the octave of the note to the current octave + diff.
[ "Change", "the", "octave", "of", "the", "note", "to", "the", "current", "octave", "+", "diff", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L111-L115
train
236,204
bspaans/python-mingus
mingus/containers/note.py
Note.transpose
def transpose(self, interval, up=True): """Transpose the note up or down the interval. Examples: >>> a = Note('A') >>> a.transpose('3') >>> a 'C#-5' >>> a.transpose('3', False) >>> a 'A-4' """ (old, o_octave) = (self.name, self.octave) self.name = intervals.from_shorthand(self.name, interval, up) if up: if self < Note(old, o_octave): self.octave += 1 else: if self > Note(old, o_octave): self.octave -= 1
python
def transpose(self, interval, up=True): """Transpose the note up or down the interval. Examples: >>> a = Note('A') >>> a.transpose('3') >>> a 'C#-5' >>> a.transpose('3', False) >>> a 'A-4' """ (old, o_octave) = (self.name, self.octave) self.name = intervals.from_shorthand(self.name, interval, up) if up: if self < Note(old, o_octave): self.octave += 1 else: if self > Note(old, o_octave): self.octave -= 1
[ "def", "transpose", "(", "self", ",", "interval", ",", "up", "=", "True", ")", ":", "(", "old", ",", "o_octave", ")", "=", "(", "self", ".", "name", ",", "self", ".", "octave", ")", "self", ".", "name", "=", "intervals", ".", "from_shorthand", "(", "self", ".", "name", ",", "interval", ",", "up", ")", "if", "up", ":", "if", "self", "<", "Note", "(", "old", ",", "o_octave", ")", ":", "self", ".", "octave", "+=", "1", "else", ":", "if", "self", ">", "Note", "(", "old", ",", "o_octave", ")", ":", "self", ".", "octave", "-=", "1" ]
Transpose the note up or down the interval. Examples: >>> a = Note('A') >>> a.transpose('3') >>> a 'C#-5' >>> a.transpose('3', False) >>> a 'A-4'
[ "Transpose", "the", "note", "up", "or", "down", "the", "interval", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L129-L148
train
236,205
bspaans/python-mingus
mingus/containers/note.py
Note.from_int
def from_int(self, integer): """Set the Note corresponding to the integer. 0 is a C on octave 0, 12 is a C on octave 1, etc. Example: >>> Note().from_int(12) 'C-1' """ self.name = notes.int_to_note(integer % 12) self.octave = integer // 12 return self
python
def from_int(self, integer): """Set the Note corresponding to the integer. 0 is a C on octave 0, 12 is a C on octave 1, etc. Example: >>> Note().from_int(12) 'C-1' """ self.name = notes.int_to_note(integer % 12) self.octave = integer // 12 return self
[ "def", "from_int", "(", "self", ",", "integer", ")", ":", "self", ".", "name", "=", "notes", ".", "int_to_note", "(", "integer", "%", "12", ")", "self", ".", "octave", "=", "integer", "//", "12", "return", "self" ]
Set the Note corresponding to the integer. 0 is a C on octave 0, 12 is a C on octave 1, etc. Example: >>> Note().from_int(12) 'C-1'
[ "Set", "the", "Note", "corresponding", "to", "the", "integer", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L150-L161
train
236,206
bspaans/python-mingus
mingus/containers/note.py
Note.from_hertz
def from_hertz(self, hertz, standard_pitch=440): """Set the Note name and pitch, calculated from the hertz value. The standard_pitch argument can be used to set the pitch of A-4, from which the rest is calculated. """ value = ((log((float(hertz) * 1024) / standard_pitch, 2) + 1.0 / 24) * 12 + 9) # notes.note_to_int("A") self.name = notes.int_to_note(int(value) % 12) self.octave = int(value / 12) - 6 return self
python
def from_hertz(self, hertz, standard_pitch=440): """Set the Note name and pitch, calculated from the hertz value. The standard_pitch argument can be used to set the pitch of A-4, from which the rest is calculated. """ value = ((log((float(hertz) * 1024) / standard_pitch, 2) + 1.0 / 24) * 12 + 9) # notes.note_to_int("A") self.name = notes.int_to_note(int(value) % 12) self.octave = int(value / 12) - 6 return self
[ "def", "from_hertz", "(", "self", ",", "hertz", ",", "standard_pitch", "=", "440", ")", ":", "value", "=", "(", "(", "log", "(", "(", "float", "(", "hertz", ")", "*", "1024", ")", "/", "standard_pitch", ",", "2", ")", "+", "1.0", "/", "24", ")", "*", "12", "+", "9", ")", "# notes.note_to_int(\"A\")", "self", ".", "name", "=", "notes", ".", "int_to_note", "(", "int", "(", "value", ")", "%", "12", ")", "self", ".", "octave", "=", "int", "(", "value", "/", "12", ")", "-", "6", "return", "self" ]
Set the Note name and pitch, calculated from the hertz value. The standard_pitch argument can be used to set the pitch of A-4, from which the rest is calculated.
[ "Set", "the", "Note", "name", "and", "pitch", "calculated", "from", "the", "hertz", "value", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L184-L194
train
236,207
bspaans/python-mingus
mingus/containers/note.py
Note.to_shorthand
def to_shorthand(self): """Give the traditional Helmhotz pitch notation. Examples: >>> Note('C-4').to_shorthand() "c'" >>> Note('C-3').to_shorthand() 'c' >>> Note('C-2').to_shorthand() 'C' >>> Note('C-1').to_shorthand() 'C,' """ if self.octave < 3: res = self.name else: res = str.lower(self.name) o = self.octave - 3 while o < -1: res += ',' o += 1 while o > 0: res += "'" o -= 1 return res
python
def to_shorthand(self): """Give the traditional Helmhotz pitch notation. Examples: >>> Note('C-4').to_shorthand() "c'" >>> Note('C-3').to_shorthand() 'c' >>> Note('C-2').to_shorthand() 'C' >>> Note('C-1').to_shorthand() 'C,' """ if self.octave < 3: res = self.name else: res = str.lower(self.name) o = self.octave - 3 while o < -1: res += ',' o += 1 while o > 0: res += "'" o -= 1 return res
[ "def", "to_shorthand", "(", "self", ")", ":", "if", "self", ".", "octave", "<", "3", ":", "res", "=", "self", ".", "name", "else", ":", "res", "=", "str", ".", "lower", "(", "self", ".", "name", ")", "o", "=", "self", ".", "octave", "-", "3", "while", "o", "<", "-", "1", ":", "res", "+=", "','", "o", "+=", "1", "while", "o", ">", "0", ":", "res", "+=", "\"'\"", "o", "-=", "1", "return", "res" ]
Give the traditional Helmhotz pitch notation. Examples: >>> Note('C-4').to_shorthand() "c'" >>> Note('C-3').to_shorthand() 'c' >>> Note('C-2').to_shorthand() 'C' >>> Note('C-1').to_shorthand() 'C,'
[ "Give", "the", "traditional", "Helmhotz", "pitch", "notation", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L196-L220
train
236,208
bspaans/python-mingus
mingus/containers/note.py
Note.from_shorthand
def from_shorthand(self, shorthand): """Convert from traditional Helmhotz pitch notation. Examples: >>> Note().from_shorthand("C,,") 'C-0' >>> Note().from_shorthand("C") 'C-2' >>> Note().from_shorthand("c'") 'C-4' """ name = '' octave = 0 for x in shorthand: if x in ['a', 'b', 'c', 'd', 'e', 'f', 'g']: name = str.upper(x) octave = 3 elif x in ['A', 'B', 'C', 'D', 'E', 'F', 'G']: name = x octave = 2 elif x in ['#', 'b']: name += x elif x == ',': octave -= 1 elif x == "'": octave += 1 return self.set_note(name, octave, {})
python
def from_shorthand(self, shorthand): """Convert from traditional Helmhotz pitch notation. Examples: >>> Note().from_shorthand("C,,") 'C-0' >>> Note().from_shorthand("C") 'C-2' >>> Note().from_shorthand("c'") 'C-4' """ name = '' octave = 0 for x in shorthand: if x in ['a', 'b', 'c', 'd', 'e', 'f', 'g']: name = str.upper(x) octave = 3 elif x in ['A', 'B', 'C', 'D', 'E', 'F', 'G']: name = x octave = 2 elif x in ['#', 'b']: name += x elif x == ',': octave -= 1 elif x == "'": octave += 1 return self.set_note(name, octave, {})
[ "def", "from_shorthand", "(", "self", ",", "shorthand", ")", ":", "name", "=", "''", "octave", "=", "0", "for", "x", "in", "shorthand", ":", "if", "x", "in", "[", "'a'", ",", "'b'", ",", "'c'", ",", "'d'", ",", "'e'", ",", "'f'", ",", "'g'", "]", ":", "name", "=", "str", ".", "upper", "(", "x", ")", "octave", "=", "3", "elif", "x", "in", "[", "'A'", ",", "'B'", ",", "'C'", ",", "'D'", ",", "'E'", ",", "'F'", ",", "'G'", "]", ":", "name", "=", "x", "octave", "=", "2", "elif", "x", "in", "[", "'#'", ",", "'b'", "]", ":", "name", "+=", "x", "elif", "x", "==", "','", ":", "octave", "-=", "1", "elif", "x", "==", "\"'\"", ":", "octave", "+=", "1", "return", "self", ".", "set_note", "(", "name", ",", "octave", ",", "{", "}", ")" ]
Convert from traditional Helmhotz pitch notation. Examples: >>> Note().from_shorthand("C,,") 'C-0' >>> Note().from_shorthand("C") 'C-2' >>> Note().from_shorthand("c'") 'C-4'
[ "Convert", "from", "traditional", "Helmhotz", "pitch", "notation", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L222-L248
train
236,209
bspaans/python-mingus
mingus/core/intervals.py
interval
def interval(key, start_note, interval): """Return the note found at the interval starting from start_note in the given key. Raise a KeyError exception if start_note is not a valid note. Example: >>> interval('C', 'D', 1) 'E' """ if not notes.is_valid_note(start_note): raise KeyError("The start note '%s' is not a valid note" % start_note) notes_in_key = keys.get_notes(key) for n in notes_in_key: if n[0] == start_note[0]: index = notes_in_key.index(n) return notes_in_key[(index + interval) % 7]
python
def interval(key, start_note, interval): """Return the note found at the interval starting from start_note in the given key. Raise a KeyError exception if start_note is not a valid note. Example: >>> interval('C', 'D', 1) 'E' """ if not notes.is_valid_note(start_note): raise KeyError("The start note '%s' is not a valid note" % start_note) notes_in_key = keys.get_notes(key) for n in notes_in_key: if n[0] == start_note[0]: index = notes_in_key.index(n) return notes_in_key[(index + interval) % 7]
[ "def", "interval", "(", "key", ",", "start_note", ",", "interval", ")", ":", "if", "not", "notes", ".", "is_valid_note", "(", "start_note", ")", ":", "raise", "KeyError", "(", "\"The start note '%s' is not a valid note\"", "%", "start_note", ")", "notes_in_key", "=", "keys", ".", "get_notes", "(", "key", ")", "for", "n", "in", "notes_in_key", ":", "if", "n", "[", "0", "]", "==", "start_note", "[", "0", "]", ":", "index", "=", "notes_in_key", ".", "index", "(", "n", ")", "return", "notes_in_key", "[", "(", "index", "+", "interval", ")", "%", "7", "]" ]
Return the note found at the interval starting from start_note in the given key. Raise a KeyError exception if start_note is not a valid note. Example: >>> interval('C', 'D', 1) 'E'
[ "Return", "the", "note", "found", "at", "the", "interval", "starting", "from", "start_note", "in", "the", "given", "key", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L37-L53
train
236,210
bspaans/python-mingus
mingus/core/intervals.py
measure
def measure(note1, note2): """Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10 """ res = notes.note_to_int(note2) - notes.note_to_int(note1) if res < 0: return 12 - res * -1 else: return res
python
def measure(note1, note2): """Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10 """ res = notes.note_to_int(note2) - notes.note_to_int(note1) if res < 0: return 12 - res * -1 else: return res
[ "def", "measure", "(", "note1", ",", "note2", ")", ":", "res", "=", "notes", ".", "note_to_int", "(", "note2", ")", "-", "notes", ".", "note_to_int", "(", "note1", ")", "if", "res", "<", "0", ":", "return", "12", "-", "res", "*", "-", "1", "else", ":", "return", "res" ]
Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10
[ "Return", "an", "integer", "in", "the", "range", "of", "0", "-", "11", "determining", "the", "half", "note", "steps", "between", "note1", "and", "note2", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L235-L249
train
236,211
bspaans/python-mingus
mingus/core/intervals.py
augment_or_diminish_until_the_interval_is_right
def augment_or_diminish_until_the_interval_is_right(note1, note2, interval): """A helper function for the minor and major functions. You should probably not use this directly. """ cur = measure(note1, note2) while cur != interval: if cur > interval: note2 = notes.diminish(note2) elif cur < interval: note2 = notes.augment(note2) cur = measure(note1, note2) # We are practically done right now, but we need to be able to create the # minor seventh of Cb and get Bbb instead of B######### as the result val = 0 for token in note2[1:]: if token == '#': val += 1 elif token == 'b': val -= 1 # These are some checks to see if we have generated too much #'s or too much # b's. In these cases we need to convert #'s to b's and vice versa. if val > 6: val = val % 12 val = -12 + val elif val < -6: val = val % -12 val = 12 + val # Rebuild the note result = note2[0] while val > 0: result = notes.augment(result) val -= 1 while val < 0: result = notes.diminish(result) val += 1 return result
python
def augment_or_diminish_until_the_interval_is_right(note1, note2, interval): """A helper function for the minor and major functions. You should probably not use this directly. """ cur = measure(note1, note2) while cur != interval: if cur > interval: note2 = notes.diminish(note2) elif cur < interval: note2 = notes.augment(note2) cur = measure(note1, note2) # We are practically done right now, but we need to be able to create the # minor seventh of Cb and get Bbb instead of B######### as the result val = 0 for token in note2[1:]: if token == '#': val += 1 elif token == 'b': val -= 1 # These are some checks to see if we have generated too much #'s or too much # b's. In these cases we need to convert #'s to b's and vice versa. if val > 6: val = val % 12 val = -12 + val elif val < -6: val = val % -12 val = 12 + val # Rebuild the note result = note2[0] while val > 0: result = notes.augment(result) val -= 1 while val < 0: result = notes.diminish(result) val += 1 return result
[ "def", "augment_or_diminish_until_the_interval_is_right", "(", "note1", ",", "note2", ",", "interval", ")", ":", "cur", "=", "measure", "(", "note1", ",", "note2", ")", "while", "cur", "!=", "interval", ":", "if", "cur", ">", "interval", ":", "note2", "=", "notes", ".", "diminish", "(", "note2", ")", "elif", "cur", "<", "interval", ":", "note2", "=", "notes", ".", "augment", "(", "note2", ")", "cur", "=", "measure", "(", "note1", ",", "note2", ")", "# We are practically done right now, but we need to be able to create the", "# minor seventh of Cb and get Bbb instead of B######### as the result", "val", "=", "0", "for", "token", "in", "note2", "[", "1", ":", "]", ":", "if", "token", "==", "'#'", ":", "val", "+=", "1", "elif", "token", "==", "'b'", ":", "val", "-=", "1", "# These are some checks to see if we have generated too much #'s or too much", "# b's. In these cases we need to convert #'s to b's and vice versa.", "if", "val", ">", "6", ":", "val", "=", "val", "%", "12", "val", "=", "-", "12", "+", "val", "elif", "val", "<", "-", "6", ":", "val", "=", "val", "%", "-", "12", "val", "=", "12", "+", "val", "# Rebuild the note", "result", "=", "note2", "[", "0", "]", "while", "val", ">", "0", ":", "result", "=", "notes", ".", "augment", "(", "result", ")", "val", "-=", "1", "while", "val", "<", "0", ":", "result", "=", "notes", ".", "diminish", "(", "result", ")", "val", "+=", "1", "return", "result" ]
A helper function for the minor and major functions. You should probably not use this directly.
[ "A", "helper", "function", "for", "the", "minor", "and", "major", "functions", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L251-L290
train
236,212
bspaans/python-mingus
mingus/core/intervals.py
invert
def invert(interval): """Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] """ interval.reverse() res = list(interval) interval.reverse() return res
python
def invert(interval): """Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] """ interval.reverse() res = list(interval) interval.reverse() return res
[ "def", "invert", "(", "interval", ")", ":", "interval", ".", "reverse", "(", ")", "res", "=", "list", "(", "interval", ")", "interval", ".", "reverse", "(", ")", "return", "res" ]
Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C']
[ "Invert", "an", "interval", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L292-L302
train
236,213
bspaans/python-mingus
mingus/core/intervals.py
determine
def determine(note1, note2, shorthand=False): """Name the interval between note1 and note2. Examples: >>> determine('C', 'E') 'major third' >>> determine('C', 'Eb') 'minor third' >>> determine('C', 'E#') 'augmented third' >>> determine('C', 'Ebb') 'diminished third' This works for all intervals. Note that there are corner cases for major fifths and fourths: >>> determine('C', 'G') 'perfect fifth' >>> determine('C', 'F') 'perfect fourth' """ # Corner case for unisons ('A' and 'Ab', for instance) if note1[0] == note2[0]: def get_val(note): """Private function: count the value of accidentals.""" r = 0 for x in note[1:]: if x == 'b': r -= 1 elif x == '#': r += 1 return r x = get_val(note1) y = get_val(note2) if x == y: if not shorthand: return 'major unison' return '1' elif x < y: if not shorthand: return 'augmented unison' return '#1' elif x - y == 1: if not shorthand: return 'minor unison' return 'b1' else: if not shorthand: return 'diminished unison' return 'bb1' # Other intervals n1 = notes.fifths.index(note1[0]) n2 = notes.fifths.index(note2[0]) number_of_fifth_steps = n2 - n1 if n2 < n1: number_of_fifth_steps = len(notes.fifths) - n1 + n2 # [name, shorthand_name, half notes for major version of this interval] fifth_steps = [ ['unison', '1', 0], ['fifth', '5', 7], ['second', '2', 2], ['sixth', '6', 9], ['third', '3', 4], ['seventh', '7', 11], ['fourth', '4', 5], ] # Count half steps between note1 and note2 half_notes = measure(note1, note2) # Get the proper list from the number of fifth steps current = fifth_steps[number_of_fifth_steps] # maj = number of major steps for this interval maj = current[2] # if maj is equal to the half steps between note1 and note2 the interval is # major or perfect if maj == half_notes: # Corner cases for perfect fifths and fourths if current[0] == 'fifth': if not shorthand: return 'perfect fifth' elif current[0] == 'fourth': if not shorthand: return 'perfect fourth' if not shorthand: return 'major ' + current[0] return current[1] elif maj + 1 <= half_notes: # if maj + 1 is equal to half_notes, the interval is augmented. if not shorthand: return 'augmented ' + current[0] return '#' * (half_notes - maj) + current[1] elif maj - 1 == half_notes: # etc. if not shorthand: return 'minor ' + current[0] return 'b' + current[1] elif maj - 2 >= half_notes: if not shorthand: return 'diminished ' + current[0] return 'b' * (maj - half_notes) + current[1]
python
def determine(note1, note2, shorthand=False): """Name the interval between note1 and note2. Examples: >>> determine('C', 'E') 'major third' >>> determine('C', 'Eb') 'minor third' >>> determine('C', 'E#') 'augmented third' >>> determine('C', 'Ebb') 'diminished third' This works for all intervals. Note that there are corner cases for major fifths and fourths: >>> determine('C', 'G') 'perfect fifth' >>> determine('C', 'F') 'perfect fourth' """ # Corner case for unisons ('A' and 'Ab', for instance) if note1[0] == note2[0]: def get_val(note): """Private function: count the value of accidentals.""" r = 0 for x in note[1:]: if x == 'b': r -= 1 elif x == '#': r += 1 return r x = get_val(note1) y = get_val(note2) if x == y: if not shorthand: return 'major unison' return '1' elif x < y: if not shorthand: return 'augmented unison' return '#1' elif x - y == 1: if not shorthand: return 'minor unison' return 'b1' else: if not shorthand: return 'diminished unison' return 'bb1' # Other intervals n1 = notes.fifths.index(note1[0]) n2 = notes.fifths.index(note2[0]) number_of_fifth_steps = n2 - n1 if n2 < n1: number_of_fifth_steps = len(notes.fifths) - n1 + n2 # [name, shorthand_name, half notes for major version of this interval] fifth_steps = [ ['unison', '1', 0], ['fifth', '5', 7], ['second', '2', 2], ['sixth', '6', 9], ['third', '3', 4], ['seventh', '7', 11], ['fourth', '4', 5], ] # Count half steps between note1 and note2 half_notes = measure(note1, note2) # Get the proper list from the number of fifth steps current = fifth_steps[number_of_fifth_steps] # maj = number of major steps for this interval maj = current[2] # if maj is equal to the half steps between note1 and note2 the interval is # major or perfect if maj == half_notes: # Corner cases for perfect fifths and fourths if current[0] == 'fifth': if not shorthand: return 'perfect fifth' elif current[0] == 'fourth': if not shorthand: return 'perfect fourth' if not shorthand: return 'major ' + current[0] return current[1] elif maj + 1 <= half_notes: # if maj + 1 is equal to half_notes, the interval is augmented. if not shorthand: return 'augmented ' + current[0] return '#' * (half_notes - maj) + current[1] elif maj - 1 == half_notes: # etc. if not shorthand: return 'minor ' + current[0] return 'b' + current[1] elif maj - 2 >= half_notes: if not shorthand: return 'diminished ' + current[0] return 'b' * (maj - half_notes) + current[1]
[ "def", "determine", "(", "note1", ",", "note2", ",", "shorthand", "=", "False", ")", ":", "# Corner case for unisons ('A' and 'Ab', for instance)", "if", "note1", "[", "0", "]", "==", "note2", "[", "0", "]", ":", "def", "get_val", "(", "note", ")", ":", "\"\"\"Private function: count the value of accidentals.\"\"\"", "r", "=", "0", "for", "x", "in", "note", "[", "1", ":", "]", ":", "if", "x", "==", "'b'", ":", "r", "-=", "1", "elif", "x", "==", "'#'", ":", "r", "+=", "1", "return", "r", "x", "=", "get_val", "(", "note1", ")", "y", "=", "get_val", "(", "note2", ")", "if", "x", "==", "y", ":", "if", "not", "shorthand", ":", "return", "'major unison'", "return", "'1'", "elif", "x", "<", "y", ":", "if", "not", "shorthand", ":", "return", "'augmented unison'", "return", "'#1'", "elif", "x", "-", "y", "==", "1", ":", "if", "not", "shorthand", ":", "return", "'minor unison'", "return", "'b1'", "else", ":", "if", "not", "shorthand", ":", "return", "'diminished unison'", "return", "'bb1'", "# Other intervals", "n1", "=", "notes", ".", "fifths", ".", "index", "(", "note1", "[", "0", "]", ")", "n2", "=", "notes", ".", "fifths", ".", "index", "(", "note2", "[", "0", "]", ")", "number_of_fifth_steps", "=", "n2", "-", "n1", "if", "n2", "<", "n1", ":", "number_of_fifth_steps", "=", "len", "(", "notes", ".", "fifths", ")", "-", "n1", "+", "n2", "# [name, shorthand_name, half notes for major version of this interval]", "fifth_steps", "=", "[", "[", "'unison'", ",", "'1'", ",", "0", "]", ",", "[", "'fifth'", ",", "'5'", ",", "7", "]", ",", "[", "'second'", ",", "'2'", ",", "2", "]", ",", "[", "'sixth'", ",", "'6'", ",", "9", "]", ",", "[", "'third'", ",", "'3'", ",", "4", "]", ",", "[", "'seventh'", ",", "'7'", ",", "11", "]", ",", "[", "'fourth'", ",", "'4'", ",", "5", "]", ",", "]", "# Count half steps between note1 and note2", "half_notes", "=", "measure", "(", "note1", ",", "note2", ")", "# Get the proper list from the number of fifth steps", "current", "=", "fifth_steps", "[", "number_of_fifth_steps", "]", "# maj = number of major steps for this interval", "maj", "=", "current", "[", "2", "]", "# if maj is equal to the half steps between note1 and note2 the interval is", "# major or perfect", "if", "maj", "==", "half_notes", ":", "# Corner cases for perfect fifths and fourths", "if", "current", "[", "0", "]", "==", "'fifth'", ":", "if", "not", "shorthand", ":", "return", "'perfect fifth'", "elif", "current", "[", "0", "]", "==", "'fourth'", ":", "if", "not", "shorthand", ":", "return", "'perfect fourth'", "if", "not", "shorthand", ":", "return", "'major '", "+", "current", "[", "0", "]", "return", "current", "[", "1", "]", "elif", "maj", "+", "1", "<=", "half_notes", ":", "# if maj + 1 is equal to half_notes, the interval is augmented.", "if", "not", "shorthand", ":", "return", "'augmented '", "+", "current", "[", "0", "]", "return", "'#'", "*", "(", "half_notes", "-", "maj", ")", "+", "current", "[", "1", "]", "elif", "maj", "-", "1", "==", "half_notes", ":", "# etc.", "if", "not", "shorthand", ":", "return", "'minor '", "+", "current", "[", "0", "]", "return", "'b'", "+", "current", "[", "1", "]", "elif", "maj", "-", "2", ">=", "half_notes", ":", "if", "not", "shorthand", ":", "return", "'diminished '", "+", "current", "[", "0", "]", "return", "'b'", "*", "(", "maj", "-", "half_notes", ")", "+", "current", "[", "1", "]" ]
Name the interval between note1 and note2. Examples: >>> determine('C', 'E') 'major third' >>> determine('C', 'Eb') 'minor third' >>> determine('C', 'E#') 'augmented third' >>> determine('C', 'Ebb') 'diminished third' This works for all intervals. Note that there are corner cases for major fifths and fourths: >>> determine('C', 'G') 'perfect fifth' >>> determine('C', 'F') 'perfect fourth'
[ "Name", "the", "interval", "between", "note1", "and", "note2", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L304-L408
train
236,214
bspaans/python-mingus
mingus/core/intervals.py
from_shorthand
def from_shorthand(note, interval, up=True): """Return the note on interval up or down. Examples: >>> from_shorthand('A', 'b3') 'C' >>> from_shorthand('D', '2') 'E' >>> from_shorthand('E', '2', False) 'D' """ # warning should be a valid note. if not notes.is_valid_note(note): return False # [shorthand, interval function up, interval function down] shorthand_lookup = [ ['1', major_unison, major_unison], ['2', major_second, minor_seventh], ['3', major_third, minor_sixth], ['4', major_fourth, major_fifth], ['5', major_fifth, major_fourth], ['6', major_sixth, minor_third], ['7', major_seventh, minor_second], ] # Looking up last character in interval in shorthand_lookup and calling that # function. val = False for shorthand in shorthand_lookup: if shorthand[0] == interval[-1]: if up: val = shorthand[1](note) else: val = shorthand[2](note) # warning Last character in interval should be 1-7 if val == False: return False # Collect accidentals for x in interval: if x == '#': if up: val = notes.augment(val) else: val = notes.diminish(val) elif x == 'b': if up: val = notes.diminish(val) else: val = notes.augment(val) else: return val
python
def from_shorthand(note, interval, up=True): """Return the note on interval up or down. Examples: >>> from_shorthand('A', 'b3') 'C' >>> from_shorthand('D', '2') 'E' >>> from_shorthand('E', '2', False) 'D' """ # warning should be a valid note. if not notes.is_valid_note(note): return False # [shorthand, interval function up, interval function down] shorthand_lookup = [ ['1', major_unison, major_unison], ['2', major_second, minor_seventh], ['3', major_third, minor_sixth], ['4', major_fourth, major_fifth], ['5', major_fifth, major_fourth], ['6', major_sixth, minor_third], ['7', major_seventh, minor_second], ] # Looking up last character in interval in shorthand_lookup and calling that # function. val = False for shorthand in shorthand_lookup: if shorthand[0] == interval[-1]: if up: val = shorthand[1](note) else: val = shorthand[2](note) # warning Last character in interval should be 1-7 if val == False: return False # Collect accidentals for x in interval: if x == '#': if up: val = notes.augment(val) else: val = notes.diminish(val) elif x == 'b': if up: val = notes.diminish(val) else: val = notes.augment(val) else: return val
[ "def", "from_shorthand", "(", "note", ",", "interval", ",", "up", "=", "True", ")", ":", "# warning should be a valid note.", "if", "not", "notes", ".", "is_valid_note", "(", "note", ")", ":", "return", "False", "# [shorthand, interval function up, interval function down]", "shorthand_lookup", "=", "[", "[", "'1'", ",", "major_unison", ",", "major_unison", "]", ",", "[", "'2'", ",", "major_second", ",", "minor_seventh", "]", ",", "[", "'3'", ",", "major_third", ",", "minor_sixth", "]", ",", "[", "'4'", ",", "major_fourth", ",", "major_fifth", "]", ",", "[", "'5'", ",", "major_fifth", ",", "major_fourth", "]", ",", "[", "'6'", ",", "major_sixth", ",", "minor_third", "]", ",", "[", "'7'", ",", "major_seventh", ",", "minor_second", "]", ",", "]", "# Looking up last character in interval in shorthand_lookup and calling that", "# function.", "val", "=", "False", "for", "shorthand", "in", "shorthand_lookup", ":", "if", "shorthand", "[", "0", "]", "==", "interval", "[", "-", "1", "]", ":", "if", "up", ":", "val", "=", "shorthand", "[", "1", "]", "(", "note", ")", "else", ":", "val", "=", "shorthand", "[", "2", "]", "(", "note", ")", "# warning Last character in interval should be 1-7", "if", "val", "==", "False", ":", "return", "False", "# Collect accidentals", "for", "x", "in", "interval", ":", "if", "x", "==", "'#'", ":", "if", "up", ":", "val", "=", "notes", ".", "augment", "(", "val", ")", "else", ":", "val", "=", "notes", ".", "diminish", "(", "val", ")", "elif", "x", "==", "'b'", ":", "if", "up", ":", "val", "=", "notes", ".", "diminish", "(", "val", ")", "else", ":", "val", "=", "notes", ".", "augment", "(", "val", ")", "else", ":", "return", "val" ]
Return the note on interval up or down. Examples: >>> from_shorthand('A', 'b3') 'C' >>> from_shorthand('D', '2') 'E' >>> from_shorthand('E', '2', False) 'D'
[ "Return", "the", "note", "on", "interval", "up", "or", "down", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L410-L463
train
236,215
bspaans/python-mingus
mingus/core/intervals.py
is_consonant
def is_consonant(note1, note2, include_fourths=True): """Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether the interval is (or sounds like) a unison, third, sixth, perfect fourth or perfect fifth. In classical music the fourth is considered dissonant when used contrapuntal, which is why you can choose to exclude it. """ return (is_perfect_consonant(note1, note2, include_fourths) or is_imperfect_consonant(note1, note2))
python
def is_consonant(note1, note2, include_fourths=True): """Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether the interval is (or sounds like) a unison, third, sixth, perfect fourth or perfect fifth. In classical music the fourth is considered dissonant when used contrapuntal, which is why you can choose to exclude it. """ return (is_perfect_consonant(note1, note2, include_fourths) or is_imperfect_consonant(note1, note2))
[ "def", "is_consonant", "(", "note1", ",", "note2", ",", "include_fourths", "=", "True", ")", ":", "return", "(", "is_perfect_consonant", "(", "note1", ",", "note2", ",", "include_fourths", ")", "or", "is_imperfect_consonant", "(", "note1", ",", "note2", ")", ")" ]
Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether the interval is (or sounds like) a unison, third, sixth, perfect fourth or perfect fifth. In classical music the fourth is considered dissonant when used contrapuntal, which is why you can choose to exclude it.
[ "Return", "True", "if", "the", "interval", "is", "consonant", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L465-L479
train
236,216
bspaans/python-mingus
mingus/core/intervals.py
is_perfect_consonant
def is_perfect_consonant(note1, note2, include_fourths=True): """Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are considered dissonant when used contrapuntal, which is why you can exclude them. """ dhalf = measure(note1, note2) return dhalf in [0, 7] or include_fourths and dhalf == 5
python
def is_perfect_consonant(note1, note2, include_fourths=True): """Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are considered dissonant when used contrapuntal, which is why you can exclude them. """ dhalf = measure(note1, note2) return dhalf in [0, 7] or include_fourths and dhalf == 5
[ "def", "is_perfect_consonant", "(", "note1", ",", "note2", ",", "include_fourths", "=", "True", ")", ":", "dhalf", "=", "measure", "(", "note1", ",", "note2", ")", "return", "dhalf", "in", "[", "0", ",", "7", "]", "or", "include_fourths", "and", "dhalf", "==", "5" ]
Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are considered dissonant when used contrapuntal, which is why you can exclude them.
[ "Return", "True", "if", "the", "interval", "is", "a", "perfect", "consonant", "one", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L481-L491
train
236,217
bspaans/python-mingus
mingus/containers/composition.py
Composition.add_track
def add_track(self, track): """Add a track to the composition. Raise an UnexpectedObjectError if the argument is not a mingus.containers.Track object. """ if not hasattr(track, 'bars'): raise UnexpectedObjectError("Unexpected object '%s', " "expecting a mingus.containers.Track object" % track) self.tracks.append(track) self.selected_tracks = [len(self.tracks) - 1]
python
def add_track(self, track): """Add a track to the composition. Raise an UnexpectedObjectError if the argument is not a mingus.containers.Track object. """ if not hasattr(track, 'bars'): raise UnexpectedObjectError("Unexpected object '%s', " "expecting a mingus.containers.Track object" % track) self.tracks.append(track) self.selected_tracks = [len(self.tracks) - 1]
[ "def", "add_track", "(", "self", ",", "track", ")", ":", "if", "not", "hasattr", "(", "track", ",", "'bars'", ")", ":", "raise", "UnexpectedObjectError", "(", "\"Unexpected object '%s', \"", "\"expecting a mingus.containers.Track object\"", "%", "track", ")", "self", ".", "tracks", ".", "append", "(", "track", ")", "self", ".", "selected_tracks", "=", "[", "len", "(", "self", ".", "tracks", ")", "-", "1", "]" ]
Add a track to the composition. Raise an UnexpectedObjectError if the argument is not a mingus.containers.Track object.
[ "Add", "a", "track", "to", "the", "composition", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/composition.py#L55-L65
train
236,218
bspaans/python-mingus
mingus/containers/composition.py
Composition.add_note
def add_note(self, note): """Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted. """ for n in self.selected_tracks: self.tracks[n] + note
python
def add_note(self, note): """Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted. """ for n in self.selected_tracks: self.tracks[n] + note
[ "def", "add_note", "(", "self", ",", "note", ")", ":", "for", "n", "in", "self", ".", "selected_tracks", ":", "self", ".", "tracks", "[", "n", "]", "+", "note" ]
Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted.
[ "Add", "a", "note", "to", "the", "selected", "tracks", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/composition.py#L67-L73
train
236,219
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
cfunc
def cfunc(name, result, *args): """Build and apply a ctypes prototype complete with parameter flags.""" atypes = [] aflags = [] for arg in args: atypes.append(arg[1]) aflags.append((arg[2], arg[0]) + arg[3:]) return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags))
python
def cfunc(name, result, *args): """Build and apply a ctypes prototype complete with parameter flags.""" atypes = [] aflags = [] for arg in args: atypes.append(arg[1]) aflags.append((arg[2], arg[0]) + arg[3:]) return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags))
[ "def", "cfunc", "(", "name", ",", "result", ",", "*", "args", ")", ":", "atypes", "=", "[", "]", "aflags", "=", "[", "]", "for", "arg", "in", "args", ":", "atypes", ".", "append", "(", "arg", "[", "1", "]", ")", "aflags", ".", "append", "(", "(", "arg", "[", "2", "]", ",", "arg", "[", "0", "]", ")", "+", "arg", "[", "3", ":", "]", ")", "return", "CFUNCTYPE", "(", "result", ",", "*", "atypes", ")", "(", "(", "name", ",", "_fl", ")", ",", "tuple", "(", "aflags", ")", ")" ]
Build and apply a ctypes prototype complete with parameter flags.
[ "Build", "and", "apply", "a", "ctypes", "prototype", "complete", "with", "parameter", "flags", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L41-L48
train
236,220
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
fluid_synth_write_s16_stereo
def fluid_synth_write_s16_stereo(synth, len): """Return generated samples in stereo 16-bit format. Return value is a Numpy array of samples. """ import numpy buf = create_string_buffer(len * 4) fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2) return numpy.fromstring(buf[:], dtype=numpy.int16)
python
def fluid_synth_write_s16_stereo(synth, len): """Return generated samples in stereo 16-bit format. Return value is a Numpy array of samples. """ import numpy buf = create_string_buffer(len * 4) fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2) return numpy.fromstring(buf[:], dtype=numpy.int16)
[ "def", "fluid_synth_write_s16_stereo", "(", "synth", ",", "len", ")", ":", "import", "numpy", "buf", "=", "create_string_buffer", "(", "len", "*", "4", ")", "fluid_synth_write_s16", "(", "synth", ",", "len", ",", "buf", ",", "0", ",", "2", ",", "buf", ",", "1", ",", "2", ")", "return", "numpy", ".", "fromstring", "(", "buf", "[", ":", "]", ",", "dtype", "=", "numpy", ".", "int16", ")" ]
Return generated samples in stereo 16-bit format. Return value is a Numpy array of samples.
[ "Return", "generated", "samples", "in", "stereo", "16", "-", "bit", "format", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L132-L140
train
236,221
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
Synth.start
def start(self, driver=None): """Start audio output driver in separate background thread. Call this function any time after creating the Synth object. If you don't call this function, use get_samples() to generate samples. Optional keyword argument: driver: which audio driver to use for output Possible choices: 'alsa', 'oss', 'jack', 'portaudio' 'sndmgr', 'coreaudio', 'Direct Sound', 'dsound', 'pulseaudio' Not all drivers will be available for every platform, it depends on which drivers were compiled into FluidSynth for your platform. """ if driver is not None: assert driver in [ 'alsa', 'oss', 'jack', 'portaudio', 'sndmgr', 'coreaudio', 'Direct Sound', 'dsound', 'pulseaudio' ] fluid_settings_setstr(self.settings, 'audio.driver', driver) self.audio_driver = new_fluid_audio_driver(self.settings, self.synth)
python
def start(self, driver=None): """Start audio output driver in separate background thread. Call this function any time after creating the Synth object. If you don't call this function, use get_samples() to generate samples. Optional keyword argument: driver: which audio driver to use for output Possible choices: 'alsa', 'oss', 'jack', 'portaudio' 'sndmgr', 'coreaudio', 'Direct Sound', 'dsound', 'pulseaudio' Not all drivers will be available for every platform, it depends on which drivers were compiled into FluidSynth for your platform. """ if driver is not None: assert driver in [ 'alsa', 'oss', 'jack', 'portaudio', 'sndmgr', 'coreaudio', 'Direct Sound', 'dsound', 'pulseaudio' ] fluid_settings_setstr(self.settings, 'audio.driver', driver) self.audio_driver = new_fluid_audio_driver(self.settings, self.synth)
[ "def", "start", "(", "self", ",", "driver", "=", "None", ")", ":", "if", "driver", "is", "not", "None", ":", "assert", "driver", "in", "[", "'alsa'", ",", "'oss'", ",", "'jack'", ",", "'portaudio'", ",", "'sndmgr'", ",", "'coreaudio'", ",", "'Direct Sound'", ",", "'dsound'", ",", "'pulseaudio'", "]", "fluid_settings_setstr", "(", "self", ".", "settings", ",", "'audio.driver'", ",", "driver", ")", "self", ".", "audio_driver", "=", "new_fluid_audio_driver", "(", "self", ".", "settings", ",", "self", ".", "synth", ")" ]
Start audio output driver in separate background thread. Call this function any time after creating the Synth object. If you don't call this function, use get_samples() to generate samples. Optional keyword argument: driver: which audio driver to use for output Possible choices: 'alsa', 'oss', 'jack', 'portaudio' 'sndmgr', 'coreaudio', 'Direct Sound', 'dsound', 'pulseaudio' Not all drivers will be available for every platform, it depends on which drivers were compiled into FluidSynth for your platform.
[ "Start", "audio", "output", "driver", "in", "separate", "background", "thread", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L164-L194
train
236,222
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
Synth.program_select
def program_select(self, chan, sfid, bank, preset): """Select a program.""" return fluid_synth_program_select(self.synth, chan, sfid, bank, preset)
python
def program_select(self, chan, sfid, bank, preset): """Select a program.""" return fluid_synth_program_select(self.synth, chan, sfid, bank, preset)
[ "def", "program_select", "(", "self", ",", "chan", ",", "sfid", ",", "bank", ",", "preset", ")", ":", "return", "fluid_synth_program_select", "(", "self", ".", "synth", ",", "chan", ",", "sfid", ",", "bank", ",", "preset", ")" ]
Select a program.
[ "Select", "a", "program", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L210-L212
train
236,223
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
Synth.noteon
def noteon(self, chan, key, vel): """Play a note.""" if key < 0 or key > 128: return False if chan < 0: return False if vel < 0 or vel > 128: return False return fluid_synth_noteon(self.synth, chan, key, vel)
python
def noteon(self, chan, key, vel): """Play a note.""" if key < 0 or key > 128: return False if chan < 0: return False if vel < 0 or vel > 128: return False return fluid_synth_noteon(self.synth, chan, key, vel)
[ "def", "noteon", "(", "self", ",", "chan", ",", "key", ",", "vel", ")", ":", "if", "key", "<", "0", "or", "key", ">", "128", ":", "return", "False", "if", "chan", "<", "0", ":", "return", "False", "if", "vel", "<", "0", "or", "vel", ">", "128", ":", "return", "False", "return", "fluid_synth_noteon", "(", "self", ".", "synth", ",", "chan", ",", "key", ",", "vel", ")" ]
Play a note.
[ "Play", "a", "note", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L214-L222
train
236,224
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
Synth.noteoff
def noteoff(self, chan, key): """Stop a note.""" if key < 0 or key > 128: return False if chan < 0: return False return fluid_synth_noteoff(self.synth, chan, key)
python
def noteoff(self, chan, key): """Stop a note.""" if key < 0 or key > 128: return False if chan < 0: return False return fluid_synth_noteoff(self.synth, chan, key)
[ "def", "noteoff", "(", "self", ",", "chan", ",", "key", ")", ":", "if", "key", "<", "0", "or", "key", ">", "128", ":", "return", "False", "if", "chan", "<", "0", ":", "return", "False", "return", "fluid_synth_noteoff", "(", "self", ".", "synth", ",", "chan", ",", "key", ")" ]
Stop a note.
[ "Stop", "a", "note", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L224-L230
train
236,225
bspaans/python-mingus
mingus/midi/pyfluidsynth.py
Synth.cc
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft to loud) 64: sustain 91: reverb 93: chorus """ return fluid_synth_cc(self.synth, chan, ctrl, val)
python
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft to loud) 64: sustain 91: reverb 93: chorus """ return fluid_synth_cc(self.synth, chan, ctrl, val)
[ "def", "cc", "(", "self", ",", "chan", ",", "ctrl", ",", "val", ")", ":", "return", "fluid_synth_cc", "(", "self", ".", "synth", ",", "chan", ",", "ctrl", ",", "val", ")" ]
Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft to loud) 64: sustain 91: reverb 93: chorus
[ "Send", "control", "change", "value", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L242-L256
train
236,226
bspaans/python-mingus
mingus/core/notes.py
is_valid_note
def is_valid_note(note): """Return True if note is in a recognised format. False if not.""" if not _note_dict.has_key(note[0]): return False for post in note[1:]: if post != 'b' and post != '#': return False return True
python
def is_valid_note(note): """Return True if note is in a recognised format. False if not.""" if not _note_dict.has_key(note[0]): return False for post in note[1:]: if post != 'b' and post != '#': return False return True
[ "def", "is_valid_note", "(", "note", ")", ":", "if", "not", "_note_dict", ".", "has_key", "(", "note", "[", "0", "]", ")", ":", "return", "False", "for", "post", "in", "note", "[", "1", ":", "]", ":", "if", "post", "!=", "'b'", "and", "post", "!=", "'#'", ":", "return", "False", "return", "True" ]
Return True if note is in a recognised format. False if not.
[ "Return", "True", "if", "note", "is", "in", "a", "recognised", "format", ".", "False", "if", "not", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L73-L80
train
236,227
bspaans/python-mingus
mingus/core/notes.py
reduce_accidentals
def reduce_accidentals(note): """Reduce any extra accidentals to proper notes. Example: >>> reduce_accidentals('C####') 'E' """ val = note_to_int(note[0]) for token in note[1:]: if token == 'b': val -= 1 elif token == '#': val += 1 else: raise NoteFormatError("Unknown note format '%s'" % note) if val >= note_to_int(note[0]): return int_to_note(val%12) else: return int_to_note(val%12, 'b')
python
def reduce_accidentals(note): """Reduce any extra accidentals to proper notes. Example: >>> reduce_accidentals('C####') 'E' """ val = note_to_int(note[0]) for token in note[1:]: if token == 'b': val -= 1 elif token == '#': val += 1 else: raise NoteFormatError("Unknown note format '%s'" % note) if val >= note_to_int(note[0]): return int_to_note(val%12) else: return int_to_note(val%12, 'b')
[ "def", "reduce_accidentals", "(", "note", ")", ":", "val", "=", "note_to_int", "(", "note", "[", "0", "]", ")", "for", "token", "in", "note", "[", "1", ":", "]", ":", "if", "token", "==", "'b'", ":", "val", "-=", "1", "elif", "token", "==", "'#'", ":", "val", "+=", "1", "else", ":", "raise", "NoteFormatError", "(", "\"Unknown note format '%s'\"", "%", "note", ")", "if", "val", ">=", "note_to_int", "(", "note", "[", "0", "]", ")", ":", "return", "int_to_note", "(", "val", "%", "12", ")", "else", ":", "return", "int_to_note", "(", "val", "%", "12", ",", "'b'", ")" ]
Reduce any extra accidentals to proper notes. Example: >>> reduce_accidentals('C####') 'E'
[ "Reduce", "any", "extra", "accidentals", "to", "proper", "notes", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L101-L119
train
236,228
bspaans/python-mingus
mingus/core/notes.py
remove_redundant_accidentals
def remove_redundant_accidentals(note): """Remove redundant sharps and flats from the given note. Examples: >>> remove_redundant_accidentals('C##b') 'C#' >>> remove_redundant_accidentals('Eb##b') 'E' """ val = 0 for token in note[1:]: if token == 'b': val -= 1 elif token == '#': val += 1 result = note[0] while val > 0: result = augment(result) val -= 1 while val < 0: result = diminish(result) val += 1 return result
python
def remove_redundant_accidentals(note): """Remove redundant sharps and flats from the given note. Examples: >>> remove_redundant_accidentals('C##b') 'C#' >>> remove_redundant_accidentals('Eb##b') 'E' """ val = 0 for token in note[1:]: if token == 'b': val -= 1 elif token == '#': val += 1 result = note[0] while val > 0: result = augment(result) val -= 1 while val < 0: result = diminish(result) val += 1 return result
[ "def", "remove_redundant_accidentals", "(", "note", ")", ":", "val", "=", "0", "for", "token", "in", "note", "[", "1", ":", "]", ":", "if", "token", "==", "'b'", ":", "val", "-=", "1", "elif", "token", "==", "'#'", ":", "val", "+=", "1", "result", "=", "note", "[", "0", "]", "while", "val", ">", "0", ":", "result", "=", "augment", "(", "result", ")", "val", "-=", "1", "while", "val", "<", "0", ":", "result", "=", "diminish", "(", "result", ")", "val", "+=", "1", "return", "result" ]
Remove redundant sharps and flats from the given note. Examples: >>> remove_redundant_accidentals('C##b') 'C#' >>> remove_redundant_accidentals('Eb##b') 'E'
[ "Remove", "redundant", "sharps", "and", "flats", "from", "the", "given", "note", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L121-L143
train
236,229
bspaans/python-mingus
mingus/extra/musicxml.py
_gcd
def _gcd(a=None, b=None, terms=None): """Return greatest common divisor using Euclid's Algorithm.""" if terms: return reduce(lambda a, b: _gcd(a, b), terms) else: while b: (a, b) = (b, a % b) return a
python
def _gcd(a=None, b=None, terms=None): """Return greatest common divisor using Euclid's Algorithm.""" if terms: return reduce(lambda a, b: _gcd(a, b), terms) else: while b: (a, b) = (b, a % b) return a
[ "def", "_gcd", "(", "a", "=", "None", ",", "b", "=", "None", ",", "terms", "=", "None", ")", ":", "if", "terms", ":", "return", "reduce", "(", "lambda", "a", ",", "b", ":", "_gcd", "(", "a", ",", "b", ")", ",", "terms", ")", "else", ":", "while", "b", ":", "(", "a", ",", "b", ")", "=", "(", "b", ",", "a", "%", "b", ")", "return", "a" ]
Return greatest common divisor using Euclid's Algorithm.
[ "Return", "greatest", "common", "divisor", "using", "Euclid", "s", "Algorithm", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/musicxml.py#L43-L50
train
236,230
bspaans/python-mingus
mingus/core/keys.py
get_key_signature
def get_key_signature(key='C'): """Return the key signature. 0 for C or a, negative numbers for flat key signatures, positive numbers for sharp key signatures. """ if not is_valid_key(key): raise NoteFormatError("unrecognized format for key '%s'" % key) for couple in keys: if key in couple: accidentals = keys.index(couple) - 7 return accidentals
python
def get_key_signature(key='C'): """Return the key signature. 0 for C or a, negative numbers for flat key signatures, positive numbers for sharp key signatures. """ if not is_valid_key(key): raise NoteFormatError("unrecognized format for key '%s'" % key) for couple in keys: if key in couple: accidentals = keys.index(couple) - 7 return accidentals
[ "def", "get_key_signature", "(", "key", "=", "'C'", ")", ":", "if", "not", "is_valid_key", "(", "key", ")", ":", "raise", "NoteFormatError", "(", "\"unrecognized format for key '%s'\"", "%", "key", ")", "for", "couple", "in", "keys", ":", "if", "key", "in", "couple", ":", "accidentals", "=", "keys", ".", "index", "(", "couple", ")", "-", "7", "return", "accidentals" ]
Return the key signature. 0 for C or a, negative numbers for flat key signatures, positive numbers for sharp key signatures.
[ "Return", "the", "key", "signature", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L73-L85
train
236,231
bspaans/python-mingus
mingus/core/keys.py
get_key_signature_accidentals
def get_key_signature_accidentals(key='C'): """Return the list of accidentals present into the key signature.""" accidentals = get_key_signature(key) res = [] if accidentals < 0: for i in range(-accidentals): res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b')) elif accidentals > 0: for i in range(accidentals): res.append('{0}{1}'.format(notes.fifths[i], '#')) return res
python
def get_key_signature_accidentals(key='C'): """Return the list of accidentals present into the key signature.""" accidentals = get_key_signature(key) res = [] if accidentals < 0: for i in range(-accidentals): res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b')) elif accidentals > 0: for i in range(accidentals): res.append('{0}{1}'.format(notes.fifths[i], '#')) return res
[ "def", "get_key_signature_accidentals", "(", "key", "=", "'C'", ")", ":", "accidentals", "=", "get_key_signature", "(", "key", ")", "res", "=", "[", "]", "if", "accidentals", "<", "0", ":", "for", "i", "in", "range", "(", "-", "accidentals", ")", ":", "res", ".", "append", "(", "'{0}{1}'", ".", "format", "(", "list", "(", "reversed", "(", "notes", ".", "fifths", ")", ")", "[", "i", "]", ",", "'b'", ")", ")", "elif", "accidentals", ">", "0", ":", "for", "i", "in", "range", "(", "accidentals", ")", ":", "res", ".", "append", "(", "'{0}{1}'", ".", "format", "(", "notes", ".", "fifths", "[", "i", "]", ",", "'#'", ")", ")", "return", "res" ]
Return the list of accidentals present into the key signature.
[ "Return", "the", "list", "of", "accidentals", "present", "into", "the", "key", "signature", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L87-L98
train
236,232
bspaans/python-mingus
mingus/core/keys.py
get_notes
def get_notes(key='C'): """Return an ordered list of the notes in this natural key. Examples: >>> get_notes('F') ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'] >>> get_notes('c') ['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb'] """ if _key_cache.has_key(key): return _key_cache[key] if not is_valid_key(key): raise NoteFormatError("unrecognized format for key '%s'" % key) result = [] # Calculate notes altered_notes = map(operator.itemgetter(0), get_key_signature_accidentals(key)) if get_key_signature(key) < 0: symbol = 'b' elif get_key_signature(key) > 0: symbol = '#' raw_tonic_index = base_scale.index(key.upper()[0]) for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7): if note in altered_notes: result.append('%s%s' % (note, symbol)) else: result.append(note) # Save result to cache _key_cache[key] = result return result
python
def get_notes(key='C'): """Return an ordered list of the notes in this natural key. Examples: >>> get_notes('F') ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'] >>> get_notes('c') ['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb'] """ if _key_cache.has_key(key): return _key_cache[key] if not is_valid_key(key): raise NoteFormatError("unrecognized format for key '%s'" % key) result = [] # Calculate notes altered_notes = map(operator.itemgetter(0), get_key_signature_accidentals(key)) if get_key_signature(key) < 0: symbol = 'b' elif get_key_signature(key) > 0: symbol = '#' raw_tonic_index = base_scale.index(key.upper()[0]) for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7): if note in altered_notes: result.append('%s%s' % (note, symbol)) else: result.append(note) # Save result to cache _key_cache[key] = result return result
[ "def", "get_notes", "(", "key", "=", "'C'", ")", ":", "if", "_key_cache", ".", "has_key", "(", "key", ")", ":", "return", "_key_cache", "[", "key", "]", "if", "not", "is_valid_key", "(", "key", ")", ":", "raise", "NoteFormatError", "(", "\"unrecognized format for key '%s'\"", "%", "key", ")", "result", "=", "[", "]", "# Calculate notes", "altered_notes", "=", "map", "(", "operator", ".", "itemgetter", "(", "0", ")", ",", "get_key_signature_accidentals", "(", "key", ")", ")", "if", "get_key_signature", "(", "key", ")", "<", "0", ":", "symbol", "=", "'b'", "elif", "get_key_signature", "(", "key", ")", ">", "0", ":", "symbol", "=", "'#'", "raw_tonic_index", "=", "base_scale", ".", "index", "(", "key", ".", "upper", "(", ")", "[", "0", "]", ")", "for", "note", "in", "islice", "(", "cycle", "(", "base_scale", ")", ",", "raw_tonic_index", ",", "raw_tonic_index", "+", "7", ")", ":", "if", "note", "in", "altered_notes", ":", "result", ".", "append", "(", "'%s%s'", "%", "(", "note", ",", "symbol", ")", ")", "else", ":", "result", ".", "append", "(", "note", ")", "# Save result to cache", "_key_cache", "[", "key", "]", "=", "result", "return", "result" ]
Return an ordered list of the notes in this natural key. Examples: >>> get_notes('F') ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'] >>> get_notes('c') ['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']
[ "Return", "an", "ordered", "list", "of", "the", "notes", "in", "this", "natural", "key", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L100-L134
train
236,233
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.attach
def attach(self, listener): """Attach an object that should be notified of events. The object should have a notify(msg_type, param_dict) function. """ if listener not in self.listeners: self.listeners.append(listener)
python
def attach(self, listener): """Attach an object that should be notified of events. The object should have a notify(msg_type, param_dict) function. """ if listener not in self.listeners: self.listeners.append(listener)
[ "def", "attach", "(", "self", ",", "listener", ")", ":", "if", "listener", "not", "in", "self", ".", "listeners", ":", "self", ".", "listeners", ".", "append", "(", "listener", ")" ]
Attach an object that should be notified of events. The object should have a notify(msg_type, param_dict) function.
[ "Attach", "an", "object", "that", "should", "be", "notified", "of", "events", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L90-L96
train
236,234
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.detach
def detach(self, listener): """Detach a listening object so that it won't receive any events anymore.""" if listener in self.listeners: self.listeners.remove(listener)
python
def detach(self, listener): """Detach a listening object so that it won't receive any events anymore.""" if listener in self.listeners: self.listeners.remove(listener)
[ "def", "detach", "(", "self", ",", "listener", ")", ":", "if", "listener", "in", "self", ".", "listeners", ":", "self", ".", "listeners", ".", "remove", "(", "listener", ")" ]
Detach a listening object so that it won't receive any events anymore.
[ "Detach", "a", "listening", "object", "so", "that", "it", "won", "t", "receive", "any", "events", "anymore", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L98-L102
train
236,235
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.notify_listeners
def notify_listeners(self, msg_type, params): """Send a message to all the observers.""" for c in self.listeners: c.notify(msg_type, params)
python
def notify_listeners(self, msg_type, params): """Send a message to all the observers.""" for c in self.listeners: c.notify(msg_type, params)
[ "def", "notify_listeners", "(", "self", ",", "msg_type", ",", "params", ")", ":", "for", "c", "in", "self", ".", "listeners", ":", "c", ".", "notify", "(", "msg_type", ",", "params", ")" ]
Send a message to all the observers.
[ "Send", "a", "message", "to", "all", "the", "observers", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L104-L107
train
236,236
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.set_instrument
def set_instrument(self, channel, instr, bank=0): """Set the channel to the instrument _instr_.""" self.instr_event(channel, instr, bank) self.notify_listeners(self.MSG_INSTR, {'channel': int(channel), 'instr': int(instr), 'bank': int(bank)})
python
def set_instrument(self, channel, instr, bank=0): """Set the channel to the instrument _instr_.""" self.instr_event(channel, instr, bank) self.notify_listeners(self.MSG_INSTR, {'channel': int(channel), 'instr': int(instr), 'bank': int(bank)})
[ "def", "set_instrument", "(", "self", ",", "channel", ",", "instr", ",", "bank", "=", "0", ")", ":", "self", ".", "instr_event", "(", "channel", ",", "instr", ",", "bank", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_INSTR", ",", "{", "'channel'", ":", "int", "(", "channel", ")", ",", "'instr'", ":", "int", "(", "instr", ")", ",", "'bank'", ":", "int", "(", "bank", ")", "}", ")" ]
Set the channel to the instrument _instr_.
[ "Set", "the", "channel", "to", "the", "instrument", "_instr_", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L109-L113
train
236,237
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.control_change
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel, control, value) self.notify_listeners(self.MSG_CC, {'channel': int(channel), 'control': int(control), 'value': int(value)}) return True
python
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel, control, value) self.notify_listeners(self.MSG_CC, {'channel': int(channel), 'control': int(control), 'value': int(value)}) return True
[ "def", "control_change", "(", "self", ",", "channel", ",", "control", ",", "value", ")", ":", "if", "control", "<", "0", "or", "control", ">", "128", ":", "return", "False", "if", "value", "<", "0", "or", "value", ">", "128", ":", "return", "False", "self", ".", "cc_event", "(", "channel", ",", "control", ",", "value", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_CC", ",", "{", "'channel'", ":", "int", "(", "channel", ")", ",", "'control'", ":", "int", "(", "control", ")", ",", "'value'", ":", "int", "(", "value", ")", "}", ")", "return", "True" ]
Send a control change message. See the MIDI specification for more information.
[ "Send", "a", "control", "change", "message", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L115-L127
train
236,238
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.stop_Note
def stop_Note(self, note, channel=1): """Stop a note on a channel. If Note.channel is set, it will take presedence over the channel argument given here. """ if hasattr(note, 'channel'): channel = note.channel self.stop_event(int(note) + 12, int(channel)) self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel), 'note': int(note) + 12}) self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel), 'note': note}) return True
python
def stop_Note(self, note, channel=1): """Stop a note on a channel. If Note.channel is set, it will take presedence over the channel argument given here. """ if hasattr(note, 'channel'): channel = note.channel self.stop_event(int(note) + 12, int(channel)) self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel), 'note': int(note) + 12}) self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel), 'note': note}) return True
[ "def", "stop_Note", "(", "self", ",", "note", ",", "channel", "=", "1", ")", ":", "if", "hasattr", "(", "note", ",", "'channel'", ")", ":", "channel", "=", "note", ".", "channel", "self", ".", "stop_event", "(", "int", "(", "note", ")", "+", "12", ",", "int", "(", "channel", ")", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_STOP_INT", ",", "{", "'channel'", ":", "int", "(", "channel", ")", ",", "'note'", ":", "int", "(", "note", ")", "+", "12", "}", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_STOP_NOTE", ",", "{", "'channel'", ":", "int", "(", "channel", ")", ",", "'note'", ":", "note", "}", ")", "return", "True" ]
Stop a note on a channel. If Note.channel is set, it will take presedence over the channel argument given here.
[ "Stop", "a", "note", "on", "a", "channel", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L147-L160
train
236,239
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.stop_everything
def stop_everything(self): """Stop all the notes on all channels.""" for x in range(118): for c in range(16): self.stop_Note(x, c)
python
def stop_everything(self): """Stop all the notes on all channels.""" for x in range(118): for c in range(16): self.stop_Note(x, c)
[ "def", "stop_everything", "(", "self", ")", ":", "for", "x", "in", "range", "(", "118", ")", ":", "for", "c", "in", "range", "(", "16", ")", ":", "self", ".", "stop_Note", "(", "x", ",", "c", ")" ]
Stop all the notes on all channels.
[ "Stop", "all", "the", "notes", "on", "all", "channels", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L162-L166
train
236,240
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.play_NoteContainer
def play_NoteContainer(self, nc, channel=1, velocity=100): """Play the Notes in the NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel, 'velocity': velocity}) if nc is None: return True for note in nc: if not self.play_Note(note, channel, velocity): return False return True
python
def play_NoteContainer(self, nc, channel=1, velocity=100): """Play the Notes in the NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel, 'velocity': velocity}) if nc is None: return True for note in nc: if not self.play_Note(note, channel, velocity): return False return True
[ "def", "play_NoteContainer", "(", "self", ",", "nc", ",", "channel", "=", "1", ",", "velocity", "=", "100", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_NC", ",", "{", "'notes'", ":", "nc", ",", "'channel'", ":", "channel", ",", "'velocity'", ":", "velocity", "}", ")", "if", "nc", "is", "None", ":", "return", "True", "for", "note", "in", "nc", ":", "if", "not", "self", ".", "play_Note", "(", "note", ",", "channel", ",", "velocity", ")", ":", "return", "False", "return", "True" ]
Play the Notes in the NoteContainer nc.
[ "Play", "the", "Notes", "in", "the", "NoteContainer", "nc", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L168-L177
train
236,241
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.stop_NoteContainer
def stop_NoteContainer(self, nc, channel=1): """Stop playing the notes in NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel}) if nc is None: return True for note in nc: if not self.stop_Note(note, channel): return False return True
python
def stop_NoteContainer(self, nc, channel=1): """Stop playing the notes in NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel}) if nc is None: return True for note in nc: if not self.stop_Note(note, channel): return False return True
[ "def", "stop_NoteContainer", "(", "self", ",", "nc", ",", "channel", "=", "1", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_NC", ",", "{", "'notes'", ":", "nc", ",", "'channel'", ":", "channel", "}", ")", "if", "nc", "is", "None", ":", "return", "True", "for", "note", "in", "nc", ":", "if", "not", "self", ".", "stop_Note", "(", "note", ",", "channel", ")", ":", "return", "False", "return", "True" ]
Stop playing the notes in NoteContainer nc.
[ "Stop", "playing", "the", "notes", "in", "NoteContainer", "nc", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L179-L188
train
236,242
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.play_Bar
def play_Bar(self, bar, channel=1, bpm=120): """Play a Bar object. Return a dictionary with the bpm lemma set on success, an empty dict on some kind of failure. The tempo can be changed by setting the bpm attribute on a NoteContainer. """ self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel' : channel, 'bpm': bpm}) # length of a quarter note qn_length = 60.0 / bpm for nc in bar: if not self.play_NoteContainer(nc[2], channel, 100): return {} # Change the quarter note length if the NoteContainer has a bpm # attribute if hasattr(nc[2], 'bpm'): bpm = nc[2].bpm qn_length = 60.0 / bpm ms = qn_length * (4.0 / nc[1]) self.sleep(ms) self.notify_listeners(self.MSG_SLEEP, {'s': ms}) self.stop_NoteContainer(nc[2], channel) return {'bpm': bpm}
python
def play_Bar(self, bar, channel=1, bpm=120): """Play a Bar object. Return a dictionary with the bpm lemma set on success, an empty dict on some kind of failure. The tempo can be changed by setting the bpm attribute on a NoteContainer. """ self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel' : channel, 'bpm': bpm}) # length of a quarter note qn_length = 60.0 / bpm for nc in bar: if not self.play_NoteContainer(nc[2], channel, 100): return {} # Change the quarter note length if the NoteContainer has a bpm # attribute if hasattr(nc[2], 'bpm'): bpm = nc[2].bpm qn_length = 60.0 / bpm ms = qn_length * (4.0 / nc[1]) self.sleep(ms) self.notify_listeners(self.MSG_SLEEP, {'s': ms}) self.stop_NoteContainer(nc[2], channel) return {'bpm': bpm}
[ "def", "play_Bar", "(", "self", ",", "bar", ",", "channel", "=", "1", ",", "bpm", "=", "120", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_BAR", ",", "{", "'bar'", ":", "bar", ",", "'channel'", ":", "channel", ",", "'bpm'", ":", "bpm", "}", ")", "# length of a quarter note", "qn_length", "=", "60.0", "/", "bpm", "for", "nc", "in", "bar", ":", "if", "not", "self", ".", "play_NoteContainer", "(", "nc", "[", "2", "]", ",", "channel", ",", "100", ")", ":", "return", "{", "}", "# Change the quarter note length if the NoteContainer has a bpm", "# attribute", "if", "hasattr", "(", "nc", "[", "2", "]", ",", "'bpm'", ")", ":", "bpm", "=", "nc", "[", "2", "]", ".", "bpm", "qn_length", "=", "60.0", "/", "bpm", "ms", "=", "qn_length", "*", "(", "4.0", "/", "nc", "[", "1", "]", ")", "self", ".", "sleep", "(", "ms", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_SLEEP", ",", "{", "'s'", ":", "ms", "}", ")", "self", ".", "stop_NoteContainer", "(", "nc", "[", "2", "]", ",", "channel", ")", "return", "{", "'bpm'", ":", "bpm", "}" ]
Play a Bar object. Return a dictionary with the bpm lemma set on success, an empty dict on some kind of failure. The tempo can be changed by setting the bpm attribute on a NoteContainer.
[ "Play", "a", "Bar", "object", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L190-L217
train
236,243
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.play_Track
def play_Track(self, track, channel=1, bpm=120): """Play a Track object.""" self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel' : channel, 'bpm': bpm}) for bar in track: res = self.play_Bar(bar, channel, bpm) if res != {}: bpm = res['bpm'] else: return {} return {'bpm': bpm}
python
def play_Track(self, track, channel=1, bpm=120): """Play a Track object.""" self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel' : channel, 'bpm': bpm}) for bar in track: res = self.play_Bar(bar, channel, bpm) if res != {}: bpm = res['bpm'] else: return {} return {'bpm': bpm}
[ "def", "play_Track", "(", "self", ",", "track", ",", "channel", "=", "1", ",", "bpm", "=", "120", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_TRACK", ",", "{", "'track'", ":", "track", ",", "'channel'", ":", "channel", ",", "'bpm'", ":", "bpm", "}", ")", "for", "bar", "in", "track", ":", "res", "=", "self", ".", "play_Bar", "(", "bar", ",", "channel", ",", "bpm", ")", "if", "res", "!=", "{", "}", ":", "bpm", "=", "res", "[", "'bpm'", "]", "else", ":", "return", "{", "}", "return", "{", "'bpm'", ":", "bpm", "}" ]
Play a Track object.
[ "Play", "a", "Track", "object", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L296-L306
train
236,244
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.play_Tracks
def play_Tracks(self, tracks, channels, bpm=120): """Play a list of Tracks. If an instance of MidiInstrument is used then the instrument will be set automatically. """ self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks, 'channels': channels, 'bpm': bpm}) # Set the right instruments for x in range(len(tracks)): instr = tracks[x].instrument if isinstance(instr, MidiInstrument): try: i = instr.names.index(instr.name) except: i = 1 self.set_instrument(channels[x], i) else: self.set_instrument(channels[x], 1) current_bar = 0 max_bar = len(tracks[0]) # Play the bars while current_bar < max_bar: playbars = [] for tr in tracks: playbars.append(tr[current_bar]) res = self.play_Bars(playbars, channels, bpm) if res != {}: bpm = res['bpm'] else: return {} current_bar += 1 return {'bpm': bpm}
python
def play_Tracks(self, tracks, channels, bpm=120): """Play a list of Tracks. If an instance of MidiInstrument is used then the instrument will be set automatically. """ self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks, 'channels': channels, 'bpm': bpm}) # Set the right instruments for x in range(len(tracks)): instr = tracks[x].instrument if isinstance(instr, MidiInstrument): try: i = instr.names.index(instr.name) except: i = 1 self.set_instrument(channels[x], i) else: self.set_instrument(channels[x], 1) current_bar = 0 max_bar = len(tracks[0]) # Play the bars while current_bar < max_bar: playbars = [] for tr in tracks: playbars.append(tr[current_bar]) res = self.play_Bars(playbars, channels, bpm) if res != {}: bpm = res['bpm'] else: return {} current_bar += 1 return {'bpm': bpm}
[ "def", "play_Tracks", "(", "self", ",", "tracks", ",", "channels", ",", "bpm", "=", "120", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_TRACKS", ",", "{", "'tracks'", ":", "tracks", ",", "'channels'", ":", "channels", ",", "'bpm'", ":", "bpm", "}", ")", "# Set the right instruments", "for", "x", "in", "range", "(", "len", "(", "tracks", ")", ")", ":", "instr", "=", "tracks", "[", "x", "]", ".", "instrument", "if", "isinstance", "(", "instr", ",", "MidiInstrument", ")", ":", "try", ":", "i", "=", "instr", ".", "names", ".", "index", "(", "instr", ".", "name", ")", "except", ":", "i", "=", "1", "self", ".", "set_instrument", "(", "channels", "[", "x", "]", ",", "i", ")", "else", ":", "self", ".", "set_instrument", "(", "channels", "[", "x", "]", ",", "1", ")", "current_bar", "=", "0", "max_bar", "=", "len", "(", "tracks", "[", "0", "]", ")", "# Play the bars", "while", "current_bar", "<", "max_bar", ":", "playbars", "=", "[", "]", "for", "tr", "in", "tracks", ":", "playbars", ".", "append", "(", "tr", "[", "current_bar", "]", ")", "res", "=", "self", ".", "play_Bars", "(", "playbars", ",", "channels", ",", "bpm", ")", "if", "res", "!=", "{", "}", ":", "bpm", "=", "res", "[", "'bpm'", "]", "else", ":", "return", "{", "}", "current_bar", "+=", "1", "return", "{", "'bpm'", ":", "bpm", "}" ]
Play a list of Tracks. If an instance of MidiInstrument is used then the instrument will be set automatically.
[ "Play", "a", "list", "of", "Tracks", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L308-L342
train
236,245
bspaans/python-mingus
mingus/midi/sequencer.py
Sequencer.play_Composition
def play_Composition(self, composition, channels=None, bpm=120): """Play a Composition object.""" self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition' : composition, 'channels': channels, 'bpm': bpm}) if channels == None: channels = map(lambda x: x + 1, range(len(composition.tracks))) return self.play_Tracks(composition.tracks, channels, bpm)
python
def play_Composition(self, composition, channels=None, bpm=120): """Play a Composition object.""" self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition' : composition, 'channels': channels, 'bpm': bpm}) if channels == None: channels = map(lambda x: x + 1, range(len(composition.tracks))) return self.play_Tracks(composition.tracks, channels, bpm)
[ "def", "play_Composition", "(", "self", ",", "composition", ",", "channels", "=", "None", ",", "bpm", "=", "120", ")", ":", "self", ".", "notify_listeners", "(", "self", ".", "MSG_PLAY_COMPOSITION", ",", "{", "'composition'", ":", "composition", ",", "'channels'", ":", "channels", ",", "'bpm'", ":", "bpm", "}", ")", "if", "channels", "==", "None", ":", "channels", "=", "map", "(", "lambda", "x", ":", "x", "+", "1", ",", "range", "(", "len", "(", "composition", ".", "tracks", ")", ")", ")", "return", "self", ".", "play_Tracks", "(", "composition", ".", "tracks", ",", "channels", ",", "bpm", ")" ]
Play a Composition object.
[ "Play", "a", "Composition", "object", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L344-L350
train
236,246
bspaans/python-mingus
mingus/extra/fft.py
_find_log_index
def _find_log_index(f): """Look up the index of the frequency f in the frequency table. Return the nearest index. """ global _last_asked, _log_cache (begin, end) = (0, 128) # Most calls are sequential, this keeps track of the last value asked for so # that we need to search much, much less. if _last_asked is not None: (lastn, lastval) = _last_asked if f >= lastval: if f <= _log_cache[lastn]: _last_asked = (lastn, f) return lastn elif f <= _log_cache[lastn + 1]: _last_asked = (lastn + 1, f) return lastn + 1 begin = lastn # Do some range checking if f > _log_cache[127] or f <= 0: return 128 # Binary search related algorithm to find the index while begin != end: n = (begin + end) // 2 c = _log_cache[n] cp = _log_cache[n - 1] if n != 0 else 0 if cp < f <= c: _last_asked = (n, f) return n if f < c: end = n else: begin = n _last_asked = (begin, f) return begin
python
def _find_log_index(f): """Look up the index of the frequency f in the frequency table. Return the nearest index. """ global _last_asked, _log_cache (begin, end) = (0, 128) # Most calls are sequential, this keeps track of the last value asked for so # that we need to search much, much less. if _last_asked is not None: (lastn, lastval) = _last_asked if f >= lastval: if f <= _log_cache[lastn]: _last_asked = (lastn, f) return lastn elif f <= _log_cache[lastn + 1]: _last_asked = (lastn + 1, f) return lastn + 1 begin = lastn # Do some range checking if f > _log_cache[127] or f <= 0: return 128 # Binary search related algorithm to find the index while begin != end: n = (begin + end) // 2 c = _log_cache[n] cp = _log_cache[n - 1] if n != 0 else 0 if cp < f <= c: _last_asked = (n, f) return n if f < c: end = n else: begin = n _last_asked = (begin, f) return begin
[ "def", "_find_log_index", "(", "f", ")", ":", "global", "_last_asked", ",", "_log_cache", "(", "begin", ",", "end", ")", "=", "(", "0", ",", "128", ")", "# Most calls are sequential, this keeps track of the last value asked for so", "# that we need to search much, much less.", "if", "_last_asked", "is", "not", "None", ":", "(", "lastn", ",", "lastval", ")", "=", "_last_asked", "if", "f", ">=", "lastval", ":", "if", "f", "<=", "_log_cache", "[", "lastn", "]", ":", "_last_asked", "=", "(", "lastn", ",", "f", ")", "return", "lastn", "elif", "f", "<=", "_log_cache", "[", "lastn", "+", "1", "]", ":", "_last_asked", "=", "(", "lastn", "+", "1", ",", "f", ")", "return", "lastn", "+", "1", "begin", "=", "lastn", "# Do some range checking", "if", "f", ">", "_log_cache", "[", "127", "]", "or", "f", "<=", "0", ":", "return", "128", "# Binary search related algorithm to find the index", "while", "begin", "!=", "end", ":", "n", "=", "(", "begin", "+", "end", ")", "//", "2", "c", "=", "_log_cache", "[", "n", "]", "cp", "=", "_log_cache", "[", "n", "-", "1", "]", "if", "n", "!=", "0", "else", "0", "if", "cp", "<", "f", "<=", "c", ":", "_last_asked", "=", "(", "n", ",", "f", ")", "return", "n", "if", "f", "<", "c", ":", "end", "=", "n", "else", ":", "begin", "=", "n", "_last_asked", "=", "(", "begin", ",", "f", ")", "return", "begin" ]
Look up the index of the frequency f in the frequency table. Return the nearest index.
[ "Look", "up", "the", "index", "of", "the", "frequency", "f", "in", "the", "frequency", "table", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L45-L83
train
236,247
bspaans/python-mingus
mingus/extra/fft.py
find_frequencies
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(data) uniquePts = numpy.ceil((n + 1) / 2.0) # Scale by the length (n) and square the value to get the amplitude p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]] p[0] = p[0] / 2 if n % 2 == 0: p[-1] = p[-1] / 2 # Generate the frequencies and zip with the amplitudes s = freq / float(n) freqArray = numpy.arange(0, uniquePts * s, s) return zip(freqArray, p)
python
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(data) uniquePts = numpy.ceil((n + 1) / 2.0) # Scale by the length (n) and square the value to get the amplitude p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]] p[0] = p[0] / 2 if n % 2 == 0: p[-1] = p[-1] / 2 # Generate the frequencies and zip with the amplitudes s = freq / float(n) freqArray = numpy.arange(0, uniquePts * s, s) return zip(freqArray, p)
[ "def", "find_frequencies", "(", "data", ",", "freq", "=", "44100", ",", "bits", "=", "16", ")", ":", "# Fast fourier transform", "n", "=", "len", "(", "data", ")", "p", "=", "_fft", "(", "data", ")", "uniquePts", "=", "numpy", ".", "ceil", "(", "(", "n", "+", "1", ")", "/", "2.0", ")", "# Scale by the length (n) and square the value to get the amplitude", "p", "=", "[", "(", "abs", "(", "x", ")", "/", "float", "(", "n", ")", ")", "**", "2", "*", "2", "for", "x", "in", "p", "[", "0", ":", "uniquePts", "]", "]", "p", "[", "0", "]", "=", "p", "[", "0", "]", "/", "2", "if", "n", "%", "2", "==", "0", ":", "p", "[", "-", "1", "]", "=", "p", "[", "-", "1", "]", "/", "2", "# Generate the frequencies and zip with the amplitudes", "s", "=", "freq", "/", "float", "(", "n", ")", "freqArray", "=", "numpy", ".", "arange", "(", "0", ",", "uniquePts", "*", "s", ",", "s", ")", "return", "zip", "(", "freqArray", ",", "p", ")" ]
Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio.
[ "Convert", "audio", "data", "into", "a", "frequency", "-", "amplitude", "table", "using", "fast", "fourier", "transformation", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L85-L107
train
236,248
bspaans/python-mingus
mingus/extra/fft.py
find_Note
def find_Note(data, freq, bits): """Get the frequencies, feed them to find_notes and the return the Note with the highest amplitude.""" data = find_frequencies(data, freq, bits) return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0]
python
def find_Note(data, freq, bits): """Get the frequencies, feed them to find_notes and the return the Note with the highest amplitude.""" data = find_frequencies(data, freq, bits) return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0]
[ "def", "find_Note", "(", "data", ",", "freq", ",", "bits", ")", ":", "data", "=", "find_frequencies", "(", "data", ",", "freq", ",", "bits", ")", "return", "sorted", "(", "find_notes", "(", "data", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "[", "-", "1", "]", "[", "0", "]" ]
Get the frequencies, feed them to find_notes and the return the Note with the highest amplitude.
[ "Get", "the", "frequencies", "feed", "them", "to", "find_notes", "and", "the", "return", "the", "Note", "with", "the", "highest", "amplitude", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L146-L150
train
236,249
bspaans/python-mingus
mingus/extra/fft.py
analyze_chunks
def analyze_chunks(data, freq, bits, chunksize=512): """Cut the one channel data in chunks and analyzes them separately. Making the chunksize a power of two works fastest. """ res = [] while data != []: f = find_frequencies(data[:chunksize], freq, bits) res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0]) data = data[chunksize:] return res
python
def analyze_chunks(data, freq, bits, chunksize=512): """Cut the one channel data in chunks and analyzes them separately. Making the chunksize a power of two works fastest. """ res = [] while data != []: f = find_frequencies(data[:chunksize], freq, bits) res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0]) data = data[chunksize:] return res
[ "def", "analyze_chunks", "(", "data", ",", "freq", ",", "bits", ",", "chunksize", "=", "512", ")", ":", "res", "=", "[", "]", "while", "data", "!=", "[", "]", ":", "f", "=", "find_frequencies", "(", "data", "[", ":", "chunksize", "]", ",", "freq", ",", "bits", ")", "res", ".", "append", "(", "sorted", "(", "find_notes", "(", "f", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ")", "[", "-", "1", "]", "[", "0", "]", ")", "data", "=", "data", "[", "chunksize", ":", "]", "return", "res" ]
Cut the one channel data in chunks and analyzes them separately. Making the chunksize a power of two works fastest.
[ "Cut", "the", "one", "channel", "data", "in", "chunks", "and", "analyzes", "them", "separately", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L152-L162
train
236,250
bspaans/python-mingus
mingus/extra/fft.py
find_melody
def find_melody(file='440_480_clean.wav', chunksize=512): """Cut the sample into chunks and analyze each chunk. Return a list [(Note, chunks)] where chunks is the number of chunks where that note is the most dominant. If two consequent chunks turn out to return the same Note they are grouped together. This is an experimental function. """ (data, freq, bits) = data_from_file(file) res = [] for d in analyze_chunks(data, freq, bits, chunksize): if res != []: if res[-1][0] == d: val = res[-1][1] res[-1] = (d, val + 1) else: res.append((d, 1)) else: res.append((d, 1)) return [(x, freq) for (x, freq) in res]
python
def find_melody(file='440_480_clean.wav', chunksize=512): """Cut the sample into chunks and analyze each chunk. Return a list [(Note, chunks)] where chunks is the number of chunks where that note is the most dominant. If two consequent chunks turn out to return the same Note they are grouped together. This is an experimental function. """ (data, freq, bits) = data_from_file(file) res = [] for d in analyze_chunks(data, freq, bits, chunksize): if res != []: if res[-1][0] == d: val = res[-1][1] res[-1] = (d, val + 1) else: res.append((d, 1)) else: res.append((d, 1)) return [(x, freq) for (x, freq) in res]
[ "def", "find_melody", "(", "file", "=", "'440_480_clean.wav'", ",", "chunksize", "=", "512", ")", ":", "(", "data", ",", "freq", ",", "bits", ")", "=", "data_from_file", "(", "file", ")", "res", "=", "[", "]", "for", "d", "in", "analyze_chunks", "(", "data", ",", "freq", ",", "bits", ",", "chunksize", ")", ":", "if", "res", "!=", "[", "]", ":", "if", "res", "[", "-", "1", "]", "[", "0", "]", "==", "d", ":", "val", "=", "res", "[", "-", "1", "]", "[", "1", "]", "res", "[", "-", "1", "]", "=", "(", "d", ",", "val", "+", "1", ")", "else", ":", "res", ".", "append", "(", "(", "d", ",", "1", ")", ")", "else", ":", "res", ".", "append", "(", "(", "d", ",", "1", ")", ")", "return", "[", "(", "x", ",", "freq", ")", "for", "(", "x", ",", "freq", ")", "in", "res", "]" ]
Cut the sample into chunks and analyze each chunk. Return a list [(Note, chunks)] where chunks is the number of chunks where that note is the most dominant. If two consequent chunks turn out to return the same Note they are grouped together. This is an experimental function.
[ "Cut", "the", "sample", "into", "chunks", "and", "analyze", "each", "chunk", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L164-L186
train
236,251
bspaans/python-mingus
mingus/midi/midi_file_out.py
write_Note
def write_Note(file, note, bpm=120, repeat=0, verbose=False): """Expect a Note object from mingus.containers and save it into a MIDI file, specified in file. You can set the velocity and channel in Note.velocity and Note.channel. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.set_deltatime('\x00') t.play_Note(note) t.set_deltatime("\x48") t.stop_Note(note) repeat -= 1 return m.write_file(file, verbose)
python
def write_Note(file, note, bpm=120, repeat=0, verbose=False): """Expect a Note object from mingus.containers and save it into a MIDI file, specified in file. You can set the velocity and channel in Note.velocity and Note.channel. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.set_deltatime('\x00') t.play_Note(note) t.set_deltatime("\x48") t.stop_Note(note) repeat -= 1 return m.write_file(file, verbose)
[ "def", "write_Note", "(", "file", ",", "note", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "MidiTrack", "(", "bpm", ")", "m", ".", "tracks", "=", "[", "t", "]", "while", "repeat", ">=", "0", ":", "t", ".", "set_deltatime", "(", "'\\x00'", ")", "t", ".", "play_Note", "(", "note", ")", "t", ".", "set_deltatime", "(", "\"\\x48\"", ")", "t", ".", "stop_Note", "(", "note", ")", "repeat", "-=", "1", "return", "m", ".", "write_file", "(", "file", ",", "verbose", ")" ]
Expect a Note object from mingus.containers and save it into a MIDI file, specified in file. You can set the velocity and channel in Note.velocity and Note.channel.
[ "Expect", "a", "Note", "object", "from", "mingus", ".", "containers", "and", "save", "it", "into", "a", "MIDI", "file", "specified", "in", "file", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L71-L86
train
236,252
bspaans/python-mingus
mingus/midi/midi_file_out.py
write_NoteContainer
def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False): """Write a mingus.NoteContainer to a MIDI file.""" m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.set_deltatime('\x00') t.play_NoteContainer(notecontainer) t.set_deltatime("\x48") t.stop_NoteContainer(notecontainer) repeat -= 1 return m.write_file(file, verbose)
python
def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False): """Write a mingus.NoteContainer to a MIDI file.""" m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.set_deltatime('\x00') t.play_NoteContainer(notecontainer) t.set_deltatime("\x48") t.stop_NoteContainer(notecontainer) repeat -= 1 return m.write_file(file, verbose)
[ "def", "write_NoteContainer", "(", "file", ",", "notecontainer", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "MidiTrack", "(", "bpm", ")", "m", ".", "tracks", "=", "[", "t", "]", "while", "repeat", ">=", "0", ":", "t", ".", "set_deltatime", "(", "'\\x00'", ")", "t", ".", "play_NoteContainer", "(", "notecontainer", ")", "t", ".", "set_deltatime", "(", "\"\\x48\"", ")", "t", ".", "stop_NoteContainer", "(", "notecontainer", ")", "repeat", "-=", "1", "return", "m", ".", "write_file", "(", "file", ",", "verbose", ")" ]
Write a mingus.NoteContainer to a MIDI file.
[ "Write", "a", "mingus", ".", "NoteContainer", "to", "a", "MIDI", "file", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L88-L99
train
236,253
bspaans/python-mingus
mingus/midi/midi_file_out.py
write_Bar
def write_Bar(file, bar, bpm=120, repeat=0, verbose=False): """Write a mingus.Bar to a MIDI file. Both the key and the meter are written to the file as well. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.play_Bar(bar) repeat -= 1 return m.write_file(file, verbose)
python
def write_Bar(file, bar, bpm=120, repeat=0, verbose=False): """Write a mingus.Bar to a MIDI file. Both the key and the meter are written to the file as well. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.play_Bar(bar) repeat -= 1 return m.write_file(file, verbose)
[ "def", "write_Bar", "(", "file", ",", "bar", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "MidiTrack", "(", "bpm", ")", "m", ".", "tracks", "=", "[", "t", "]", "while", "repeat", ">=", "0", ":", "t", ".", "play_Bar", "(", "bar", ")", "repeat", "-=", "1", "return", "m", ".", "write_file", "(", "file", ",", "verbose", ")" ]
Write a mingus.Bar to a MIDI file. Both the key and the meter are written to the file as well.
[ "Write", "a", "mingus", ".", "Bar", "to", "a", "MIDI", "file", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L101-L112
train
236,254
bspaans/python-mingus
mingus/midi/midi_file_out.py
write_Track
def write_Track(file, track, bpm=120, repeat=0, verbose=False): """Write a mingus.Track to a MIDI file. Write the name to the file and set the instrument if the instrument has the attribute instrument_nr, which represents the MIDI instrument number. The class MidiInstrument in mingus.containers.Instrument has this attribute by default. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.play_Track(track) repeat -= 1 return m.write_file(file, verbose)
python
def write_Track(file, track, bpm=120, repeat=0, verbose=False): """Write a mingus.Track to a MIDI file. Write the name to the file and set the instrument if the instrument has the attribute instrument_nr, which represents the MIDI instrument number. The class MidiInstrument in mingus.containers.Instrument has this attribute by default. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.play_Track(track) repeat -= 1 return m.write_file(file, verbose)
[ "def", "write_Track", "(", "file", ",", "track", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "MidiTrack", "(", "bpm", ")", "m", ".", "tracks", "=", "[", "t", "]", "while", "repeat", ">=", "0", ":", "t", ".", "play_Track", "(", "track", ")", "repeat", "-=", "1", "return", "m", ".", "write_file", "(", "file", ",", "verbose", ")" ]
Write a mingus.Track to a MIDI file. Write the name to the file and set the instrument if the instrument has the attribute instrument_nr, which represents the MIDI instrument number. The class MidiInstrument in mingus.containers.Instrument has this attribute by default.
[ "Write", "a", "mingus", ".", "Track", "to", "a", "MIDI", "file", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L114-L128
train
236,255
bspaans/python-mingus
mingus/midi/midi_file_out.py
write_Composition
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False): """Write a mingus.Composition to a MIDI file.""" m = MidiFile() t = [] for x in range(len(composition.tracks)): t += [MidiTrack(bpm)] m.tracks = t while repeat >= 0: for i in range(len(composition.tracks)): m.tracks[i].play_Track(composition.tracks[i]) repeat -= 1 return m.write_file(file, verbose)
python
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False): """Write a mingus.Composition to a MIDI file.""" m = MidiFile() t = [] for x in range(len(composition.tracks)): t += [MidiTrack(bpm)] m.tracks = t while repeat >= 0: for i in range(len(composition.tracks)): m.tracks[i].play_Track(composition.tracks[i]) repeat -= 1 return m.write_file(file, verbose)
[ "def", "write_Composition", "(", "file", ",", "composition", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "[", "]", "for", "x", "in", "range", "(", "len", "(", "composition", ".", "tracks", ")", ")", ":", "t", "+=", "[", "MidiTrack", "(", "bpm", ")", "]", "m", ".", "tracks", "=", "t", "while", "repeat", ">=", "0", ":", "for", "i", "in", "range", "(", "len", "(", "composition", ".", "tracks", ")", ")", ":", "m", ".", "tracks", "[", "i", "]", ".", "play_Track", "(", "composition", ".", "tracks", "[", "i", "]", ")", "repeat", "-=", "1", "return", "m", ".", "write_file", "(", "file", ",", "verbose", ")" ]
Write a mingus.Composition to a MIDI file.
[ "Write", "a", "mingus", ".", "Composition", "to", "a", "MIDI", "file", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L130-L141
train
236,256
bspaans/python-mingus
mingus/midi/midi_file_out.py
MidiFile.get_midi_data
def get_midi_data(self): """Collect and return the raw, binary MIDI data from the tracks.""" tracks = [t.get_midi_data() for t in self.tracks if t.track_data != ''] return self.header() + ''.join(tracks)
python
def get_midi_data(self): """Collect and return the raw, binary MIDI data from the tracks.""" tracks = [t.get_midi_data() for t in self.tracks if t.track_data != ''] return self.header() + ''.join(tracks)
[ "def", "get_midi_data", "(", "self", ")", ":", "tracks", "=", "[", "t", ".", "get_midi_data", "(", ")", "for", "t", "in", "self", ".", "tracks", "if", "t", ".", "track_data", "!=", "''", "]", "return", "self", ".", "header", "(", ")", "+", "''", ".", "join", "(", "tracks", ")" ]
Collect and return the raw, binary MIDI data from the tracks.
[ "Collect", "and", "return", "the", "raw", "binary", "MIDI", "data", "from", "the", "tracks", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L37-L40
train
236,257
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
train
236,258
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
train
236,259
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
train
236,260
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
train
236,261
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
train
236,262
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
train
236,263
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
train
236,264
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
train
236,265
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
train
236,266
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
train
236,267
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
train
236,268
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
train
236,269
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
train
236,270
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
train
236,271
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
train
236,272
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
train
236,273
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
train
236,274
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
train
236,275
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
train
236,276
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
train
236,277
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
train
236,278
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
train
236,279
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
train
236,280
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
train
236,281
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
train
236,282
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
train
236,283
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
train
236,284
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
train
236,285
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
train
236,286
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
train
236,287
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
train
236,288
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
train
236,289
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
train
236,290
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
train
236,291
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
train
236,292
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
train
236,293
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
train
236,294
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
train
236,295
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
train
236,296
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
train
236,297
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
train
236,298
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
train
236,299