Write a mingus.Composition to a MIDI file.
15956
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)
564168
def save_lyrics(self, filename=None, extension='json', verbose=True,
                    overwrite=None, binary_encoding=False):
        """"""
        extension = extension.lstrip(".")
        assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT"

        # Determine the filename
        if filename:
            for ext in ["txt", "TXT", "json", "JSON"]:
                filename = filename.replace("." + ext, "")
            filename += "." + extension
        else:
            filename = "Lyrics_{}_{}.{}".format(self.artist.replace(" ", ""),
                                                self.title.replace(" ", ""),
                                                extension).lower()
            filename = self._sanitize_filename(filename)

        # Check if file already exists
        write_file = False
        if not os.path.isfile(filename):
            write_file = True
        elif overwrite:
            write_file = True
        else:
            if input("{} already exists. Overwrite?\n(y/n): ".format(filename)).lower() == 'y':
                write_file = True

        # Format lyrics as either .txt or .json
        if extension == 'json':
            lyrics_to_write = {'songs': [], 'artist': self.artist}
            lyrics_to_write['songs'].append(self.to_dict())
        else:
            lyrics_to_write = self.lyrics

        if binary_encoding:
            lyrics_to_write = lyrics_to_write.encode('utf8')

        # Write the lyrics to either a .json or .txt file
        if write_file:
            with open(filename, 'wb' if binary_encoding else 'w') as lyrics_file:
                if extension == 'json':
                    json.dump(lyrics_to_write, lyrics_file)
                else:
                    lyrics_file.write(lyrics_to_write)
            if verbose:
                print('Wrote {} to {}.'.format(self.title, filename))
        else:
            if verbose:
                print('Skipping file save.\n')
        return lyrics_to_write
1208453
def write(self, out):
        """"""
        out.write_string(self.cpu, len(self.cpu))
        out.write_string(self.os, len(self.os))
871064
def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8"):
  
  with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
    with codecs.open(tmp_path, "wb", encoding=encoding) as f:
      f.write(string)
772647
def from_Composition(composition):
    """"""
    # warning Throw exception
    if not hasattr(composition, 'tracks'):
        return False
    result = '\\header { title = "%s" composer = "%s" opus = "%s" } '\
         % (composition.title, composition.author, composition.subtitle)
    for track in composition.tracks:
        result += from_Track(track) + ' '
    return result[:-1]
534480
def write_moc(self):
        """"""

        if self.moc is None:
            raise CommandError('No MOC information present for output')

        filename = self.params.pop()
        self.moc.write(filename)
240031
def write(self, out):
        """"""
        out.write_string(self.text, len(self.text))
132868
def write_str(self, s):
        """"""
        self.write(s)
        self.room -= len(s)
72616
def main(input_dir, output_dir):
    """"""

    import ballet.util.log
    ballet.util.log.enable(logger=logger, level='INFO', echo=False)
    ballet.util.log.enable(logger=ballet.util.log.logger, level='INFO',
                           echo=False)

    X_df, y_df = load_data(input_dir=input_dir)
    out = build()

    mapper_X = out['mapper_X']
    encoder_y = out['encoder_y']

    X_ft = mapper_X.transform(X_df)
    y_ft = encoder_y.transform(y_df)

    save_features(X_ft, output_dir)
    save_targets(y_ft, output_dir)
588369
def simple_write(filename, group, times, features,
                 properties=None, item='item', mode='a'):
    """"""
    write(filename, group, [item], [times], [features], mode=mode,
          properties=[properties] if properties is not None else None)
866167
def write(self, arg, **kwargs):
        """"""
        if hasattr(arg, 'seek'):
            self._tofile(arg, **kwargs)
        else:
            with open(arg, 'wb') as fid:
                self._tofile(fid, **kwargs)
132924
def add_note(self, note, octave=None, dynamics={}):
        
        if type(note) == str:
            if octave is not None:
                note = Note(note, octave, dynamics)
            elif len(self.notes) == 0:
                note = Note(note, 4, dynamics)
            else:
                if Note(note, self.notes[-1].octave) < self.notes[-1]:
                    note = Note(note, self.notes[-1].octave + 1, dynamics)
                else:
                    note = Note(note, self.notes[-1].octave, dynamics)
        if not hasattr(note, 'name'):
            raise UnexpectedObjectError("Object '%s' was not expected. "
                    "Expecting a mingus.containers.Note object." % note)
        if note not in self.notes:
            self.notes.append(note)
            self.notes.sort()
        return self.notes
1287300
function MIDINotMIDIError() {
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);

    this.name = this.constructor.name;
    this.message = 'Not a valid MIDI file';
}
590900
def writeOutput(self, filename, samples, srcFs, targetFs):
        
        import librosa
        inputLength = samples.shape[-1]
        if srcFs != targetFs:
            if inputLength < targetFs:
                logger.info("Input signal is too short (" + str(inputLength) +
                            " samples) for resampling to " + str(targetFs) + "Hz")
                outputSamples = samples
                targetFs = srcFs
            else:
                logger.info("Resampling " + str(inputLength) + " samples from " + str(srcFs) + "Hz to " +
                            str(targetFs) + "Hz")
                outputSamples = librosa.resample(samples, srcFs, targetFs, res_type='kaiser_fast')
        else:
            outputSamples = samples
        logger.info("Writing output to " + filename)
        maxv = np.iinfo(np.int32).max
        librosa.output.write_wav(filename, (outputSamples * maxv).astype(np.int32), targetFs)
        logger.info("Output written to " + filename)
308568
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)
785560
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False):
    ''''''

    files = {}

    working_segments = []

    audio = AudioSegment.empty()

    if layer:
        total_time = max([s['end'] - s['start'] for s in segments]) * 1000
        audio = AudioSegment.silent(duration=total_time)

    for i, s in enumerate(segments):
        try:
            start = s['start'] * 1000
            end = s['end'] * 1000
            f = s['file'].replace('.transcription.txt', '')
            if f not in files:
                if f.endswith('.wav'):
                    files[f] = AudioSegment.from_wav(f)
                elif f.endswith('.mp3'):
                    files[f] = AudioSegment.from_mp3(f)

            segment = files[f][start:end]

            print(start, end, f)

            if layer:
                audio = audio.overlay(segment, times=1)
            else:
                if i > 0:
                    audio = audio.append(segment, crossfade=crossfade)
                else:
                    audio = audio + segment

            if padding > 0:
                audio = audio + AudioSegment.silent(duration=padding)

            s['duration'] = len(segment)
            working_segments.append(s)
        except:
            continue

    audio.export(out, format=os.path.splitext(out)[1].replace('.', ''))
    return working_segments
496450
def midi_outputs(self):
        
        return self.client.get_ports(is_midi=True, is_physical=True, is_output=True)