Allows user to save all lyrics within an Artist object
180526
def save_lyrics(self, extension='json', overwrite=False,
                    verbose=True, binary_encoding=False):
        """"""
        extension = extension.lstrip(".")
        assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT"

        for song in self.songs:
            song.save_lyrics(extension=extension, overwrite=overwrite, verbose=verbose, binary_encoding=binary_encoding)
759127
def save_srm(self, filename):
        
        with open(filename, 'wb') as fp:
            raw_data = bread.write(self._song_data, spec.song)
            fp.write(raw_data)
401024
function organizer(flat, tags, treeDescriptor, leafDescriptor) {
    var tree = {};
    flat.forEach(function (song) {
        var treePtr = tree;
        var depth = 1;

        // strPossibleKeys can be like "albumArtist|artist", or just "album" for instance
        treeDescriptor.forEach(function (strPossibleKeys) {
            var possibleKeys = strPossibleKeys.split("|");
            var valueForKey = undefined;
            for (var key in possibleKeys) {
                valueForKey = song[possibleKeys[key]];
                if (valueForKey !== undefined && valueForKey !== "") {
                    break;
                }
            }
            if (valueForKey === undefined) {
                valueForKey = "";
            }
            if (!treePtr[valueForKey]) {
                if (depth === treeDescriptor.length) {
                    treePtr[valueForKey] = { tags: {}, mpd: [] };
                } else {
                    treePtr[valueForKey] = { tags: {}, mpd: {} };
                }
                var mostCommonKey = possibleKeys[possibleKeys.length - 1];
                if (tags[mostCommonKey] && tags[mostCommonKey][valueForKey]) {
                    treePtr[valueForKey].tags = tags[mostCommonKey][valueForKey];
                }
            }
            treePtr = treePtr[valueForKey].mpd;
            depth++;
        });
        var leaf = {};
        if (leafDescriptor) {
            leafDescriptor.forEach(function (key) {
                leaf[key] = song[key];
            });
        } else {
            leaf = song;
        }
        if (tags["song"] && tags["song"][song.file]) {
            leaf.tags = tags["song"][song.file];
        }
        treePtr.push(leaf);
    });
    return { root: tree };
}
1138709
def save(self):
        
        data = super().save()
        data['levels'] = self.levels
        if self.parsers is None:
            data['parsers'] = None
        else:
            data['parsers'] = [parser.save() for parser in self.parsers]
        return data
561029
function toMetaString(obj) {
  var attrs = _.map(obj, function(_v, _k) {
    return _k + '="' + _.escape(_v) + '"';
  });

  var res = _.compact(attrs).join(" ");
  return res ? "<meta " + res + ">" : "";
}
7524
def track_to_ref(track, with_track_no=False):
    """"""
    if with_track_no and track.track_no > 0:
        name = '%d - ' % track.track_no
    else:
        name = ''
    for artist in track.artists:
        if len(name) > 0:
            name += ', '
        name += artist.name
    if (len(name)) > 0:
        name += ' - '
    name += track.name
    return Ref.track(uri=track.uri, name=name)
379065
function saveText() {
        var uriContent = "data:application/octet-stream," + encodeURIComponent(editor.getSession().getValue());
        document.location.href = uriContent;
    }
1253348
def export(self):
        
        return {'artists': self._artists,
                'radio': self._radio,
                'recent_artists': self._recent_artists,
                'songs_already_seen': self._songs_already_seen}
242172
def get_lyrics_genius(song_title):
    '''
    
    '''
    base_url = "http://api.genius.com"
    headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
    search_url = base_url + "/search"
    data = {'q': song_title}

    response = requests.get(search_url, data=data, headers=headers)
    json = response.json()
    song_api_path = json["response"]["hits"][0]["result"]["api_path"]

    song_url = base_url + song_api_path
    response = requests.get(song_url, headers=headers)
    json = response.json()
    path = json["response"]["song"]["path"]
    page_url = "http://genius.com" + path

    page = requests.get(page_url)
    soup = BeautifulSoup(page.text, "html.parser")
    div = soup.find('div',{'class': 'song_body-lyrics'})
    lyrics = div.find('p').getText()
  
    return lyrics
525422
public Lyrics getLyrics(int trackID) throws MusixMatchException {
		Lyrics lyrics = null;
		LyricsGetMessage message = null;
		Map<String, Object> params = new HashMap<String, Object>();

		params.put(Constants.API_KEY, apiKey);
		params.put(Constants.TRACK_ID, new String("" + trackID));

		String response = null;

		response = MusixMatchRequest.sendRequest(Helper.getURLString(
				Methods.TRACK_LYRICS_GET, params));

		Gson gson = new Gson();

		try {
			message = gson.fromJson(response, LyricsGetMessage.class);
		} catch (JsonParseException jpe) {
			handleErrorResponse(response);
		}

		lyrics = message.getContainer().getBody().getLyrics();

		return lyrics;
	}
428354
def get_audiomack_data(url):
    

    data = {}
    request = requests.get(url)

    mp3_url = request.text.split('class="player-icon download-song" title="Download" href="')[1].split('"')[0]
    artist = request.text.split('<span class="artist">')[1].split('</span>')[0].strip()
    title = request.text.split('<span class="artist">')[1].split('</span>')[1].split('</h1>')[0].strip()
    artwork_url = request.text.split('<a class="lightbox-trigger" href="')[1].split('" data')[0].strip()

    data['mp3_url'] = mp3_url
    data['title'] = title
    data['artist'] = artist
    data['artwork_url'] = artwork_url
    data['year'] = None

    return data
1149601
def extract_listing(pid):
    """"""
    print("Extracting tracklisting...")
    listing_etree = open_listing_page(pid + '/segments.inc')
    track_divs = listing_etree.xpath('//div[@class="segment__track"]')

    listing = []
    for track_div in track_divs:
        try:
            artist_names = track_div.xpath('.//span[@property="byArtist"]'
                                           '//span[@class="artist"]/text()')
        except ValueError:
            artist_names = ['']

        if not artist_names:
            artist_names = ['']

        if len(artist_names) > 1:
            artists = ', '.join(artist_names[:-1]) + ' & ' + artist_names[-1]
        else:
            artists = artist_names[0]

        try:
            title, = track_div.xpath('.//p/span[@property="name"]/text()')
        except ValueError:
            title = ''

        try:
            label, = track_div.xpath('.//abbr[@title="Record Label"]'
                                     '/span[@property="name"]/text()')
        except ValueError:
            label = ''
        listing.append((artists, title, label))
    return listing
300274
def lyricswikia(song):
    
    artist = song.artist.title()
    artist = normalize(artist, ' ', '_')
    title = song.title
    title = normalize(title, ' ', '_')

    url = 'https://lyrics.wikia.com/wiki/{}:{}'.format(artist, title)
    soup = get_url(url)
    text = ''
    content = soup.find('div', class_='lyricbox')
    if not content:
        return ''

    for unformat in content.findChildren(['i', 'b']):
        unformat.unwrap()
    for remove in content.findChildren(['div', 'span']):
        remove.decompose()

    nlcount = 0
    for line in content.children:
        if line is None or line == '<br/>' or line == '\n':
            if nlcount == 2:
                text += '\n\n'
                nlcount = 0
            else:
                nlcount += 1
        else:
            nlcount = 0
            text += str(line).replace('<br/>', '\n')
    return text.strip()
1210848
def _do_create(di):
    """"""
    track = di['track'].strip()
    artists = di['artist']
    if isinstance(artists, StringType):
        artists = [artists]

    # todo: handle case where different artists have a song with the same title
    tracks = Track.objects.filter(title=track, state='published')
    if tracks:
        track = tracks[0]
        track_created = False
    else:
        track = Track.objects.create(title=track, state='published')
        track_created = True

    last_played = di.get('last_played', None)
    if last_played and (track.last_played != last_played):
        track.last_played = last_played
        track.save()

    if track_created:
        track.length = di.get('length', 240)
        track.sites = Site.objects.all()
        track.save(set_image=False)
        for artist in artists:
            track.create_credit(artist.strip(), 'artist')
        # Set image last since we need credits set
        track.set_image()
784431
function(wav_file_obj) {

    // console.log("~~~~~~~~~ TOP write_wav ~~~~~~~~~");

    // --- iterate across all properties of given audio file object to see things like sample_rate

    // var sampleRate  = 44100;    // defaults to be overridden in below switch statement
    // var bitDepth    = 16;
    // var numChannels = 1;
    // var pcm_format = 16;
    // var audio_format = 1; // raw PCM


    var sample_rate  = 44100;    // defaults to be overridden in below switch statement
    var bit_depth    = 16;
    var num_channels = 1;
    var pcm_format = 16;   // valid values of Chunk size :   16 or 18 or 40
    var audio_format = 1; // raw PCM

    var path = "unknown_filename_must_populate_filename";
    // var data_length = wav_file_obj.buffer.length;
    var data_length = "unknown_filename_must_populate_buffer";




    // show_object_with_buffer(wav_file_obj, "in write_wav");


    // shared_utils.show_object(wav_file_obj, "total",
    //         "in write_wav", 10);



    for (var property in wav_file_obj) {

        // console.log("1111111  write_wav ", property, wav_file_obj[property]);

        if (wav_file_obj.hasOwnProperty(property)) {

            switch (property) {

                case "sample_rate" : {

                    sample_rate = wav_file_obj[property];
                    break;
                }

                case "bit_depth" : {

                    bit_depth = wav_file_obj[property];
                    break;
                }

                case "num_channels" : {

                    num_channels = wav_file_obj[property];
                    break;
                }

                case "filename" : {

                    path = wav_file_obj[property];
                    break;
                }

                case "buffer" : {

                    data_length = wav_file_obj[property].length;
                    break;
                }

                // --- default - catch all if not identifed above

                default :

                console.log("NOTICE - write_wav ignore this ... seeing property NOT on authorized list : ", 
                                property, " value ", wav_file_obj[property]);
                process.exit(8);

                break;
            };
        };
    };

    // console.log("FFFFFFFF sample_rate  ", sample_rate);
    // console.log("FFFFFFFF bit_depth    ", bit_depth);
    // console.log("FFFFFFFF num_channels ", num_channels);
    // console.log("FFFFFFFF data_length ", data_length);
    // console.log("FFFFFFFF filename ", path);


    // ---

    var size_header = 44;   // constant number of bytes in WAV header as per spec

    var RIFF = new Buffer('RIFF');  // each of these constant MUST remain 4 bytes in size
    var WAVE = new Buffer('WAVE');
    var fmt  = new Buffer('fmt ');
    var data = new Buffer('data');

    // ---

    // var path = wav_file_obj.filename;

    // console.log("/////////// about to write wav output file path ", path);
    // console.log("size buffer to write  ", wav_file_obj.buffer.length);  // deal with 1 channel for now

    // console.log(shared_utils.checkEndian()); // stens TODO - confirm we are on little endian else fiddle

    // ---

    // var data_length = wav_file_obj.buffer.length;

    var entire_size_file = data_length + size_header;

    var write_stream = fs.createWriteStream(path);

    // This is here incase any errors occur
    write_stream.on('error', function (err) {

        console.log("ERROR - seeing error in write_stream");
        console.log(err);
        // process.exit(8);
        return;
    });

    // ---


    write_stream.on('finish', function() {

        // console.error('all writes are now complete.');
    });



    // ---

    var header = new Buffer(size_header);
    var offset = 0;

    // write the "RIFF" identifier
    RIFF.copy(header, offset);  //  chunckID 0 offset  4 bytes
    offset += 4;


    var chunckSize = entire_size_file - 8;
    // write the file size minus the identifier and this 32-bit int
    // header['writeUInt32' + this.endianness](entire_size_file - 8, offset);
    header.writeUInt32LE(chunckSize, offset);   //  chunckSize 4 offset 4 bytes
    offset += 4;
    

    // write the "WAVE" identifier
    WAVE.copy(header, offset);                  // format   8 offset 4 bytes
    offset += 4;


    // write the "fmt " sub-chunk identifier
    fmt.copy(header, offset);                   //  subchunk1ID 12 offset 4 bytes
    offset += 4;


    // write the size of the "fmt " chunk
    // XXX: value of 16 is hard-coded for raw PCM format. other formats have
    // different size.
    // header['writeUInt32' + this.endianness](16, offset);
    // var pcm_format = 16;
    header.writeUInt32LE(pcm_format, offset);   //  subchunk1Size 16 offset 4 bytes
    offset += 4;
    // console.log('write pcm_format ', pcm_format, " post incr offset ", offset);
    // valid values of Chunk size :   16 or 18 or 40



    // write the audio format code
    // header['writeUInt16' + this.endianness](this.format, offset);
    // var audio_format = 1; // raw PCM
    header.writeUInt16LE(audio_format, offset);   //  audioFormat  20 offset 2 bytes    
    offset += 2;
    // console.log('write audio_format ', audio_format, " post incr offset ", offset);


    // write the number of channels
    // var num_channels = 1;
    // header['writeUInt16' + this.endianness](this.channels, offset);
    header.writeUInt16LE(num_channels, offset);   //  num_channels  22 offset 2 bytes     
    offset += 2;

    // console.log('write num_channels ', num_channels, " post incr offset ", offset);

    // write the sample rate
    // var sampleRate = 44100;
    // header['writeUInt32' + this.endianness](this.sampleRate, offset);
    header.writeUInt32LE(sample_rate, offset);   //  sampleRate  24 offset 4 bytes     
    offset += 4;
    // console.log('write sample_rate ', sample_rate, " post incr offset ", offset);


    // var bitDepth = 16;
    // write the byte rate
    var byteRate = this.byteRate;
    if (null == byteRate) {

        byteRate = sample_rate * num_channels * bit_depth / 8;

        // console.log("on write byteRate was null so post calculation its ", byteRate);
    }
    // header['writeUInt32' + this.endianness](byteRate, offset);
    header.writeUInt32LE(byteRate, offset);   //  byteRate  28 offset 4 bytes
    offset += 4;
    // console.log("on write ... byteRate ", byteRate);
    // console.log("on write ... sample_rate ", sample_rate);
    // console.log("on write ... num_channels ", num_channels);
    // console.log("on write ... bit_depth ", bit_depth);


    // console.log('write byteRate ', byteRate, " post incr offset ", offset);


    // write the block align
    var blockAlign = this.blockAlign;
    if (null == blockAlign) {
    blockAlign = num_channels * bit_depth / 8;
    }
    // header['writeUInt16' + this.endianness](blockAlign, offset);
    header.writeUInt16LE(blockAlign, offset);   //  blockAlign  32 offset 2 bytes     
    offset += 2;
    // console.log("on write ... blockAlign ", blockAlign);


    // write the bits per sample
    var bitsPerSample = bit_depth;
    // header['writeUInt16' + this.endianness](this.bitDepth, offset);
    header.writeUInt16LE(bitsPerSample, offset);    //  bitsPerSample  34 offset 2 bytes     
    offset += 2;

    // offset += 2;                                    // filler_01  36 offset 2 bytes - just ignore

    // write the "data" sub-chunk ID
    data.copy(header, offset);                      // subchunk2ID  36 offset 4 bytes
    offset += 4;

    // write the remaining length of the rest of the data
    // header['writeUInt32' + this.endianness](dataLength, offset);
    var subchunk2Size = data_length;
    header.writeUInt32LE(data_length, offset);   //  subchunk2Size  40 offset 4 bytes
    offset += 4;

    if (! (44 == offset)) {

        var err_msg = "ERROR - input file header must contain " + size_header + 
                            " bytes it incorrectly contains : " + offset;

        console.log(err_msg);
        // process.exit(4);
        return;
    }

    // console.log("end of write ........... offset ", offset);

    // ---

    write_stream.write(header);

    // ---

    var buffer_to_file = new Buffer( new Int16Array(wav_file_obj.buffer) );


    write_stream.write(buffer_to_file);

    // console.log("wav_file_obj.buffer ", wav_file_obj.buffer.length);

    // console.log("~~~~~~~~~ BOT write_wav ~~~~~~~~~");

}
391747
def save(self, file_path, note_df):
        '''
        
            
        '''

        chord = pretty_midi.PrettyMIDI()
        for program in note_df.program.drop_duplicates().values.tolist():
            df = note_df[note_df.program == program]
            midi_obj = pretty_midi.Instrument(program=program)
            for i in range(df.shape[0]):
                note = pretty_midi.Note(
                    velocity=int(df.iloc[i, :]["velocity"]),
                    pitch=int(df.iloc[i, :]["pitch"]),
                    start=float(df.iloc[i, :]["start"]), 
                    end=float(df.iloc[i, :]["end"])
                )
                # Add it to our cello instrument
                midi_obj.notes.append(note)
            # Add the cello instrument to the PrettyMIDI object
            chord.instruments.append(midi_obj)
        # Write out the MIDI data
        chord.write(file_path)
138451
def lyricscom(song):
    
    artist = song.artist.lower()
    artist = normalize(artist, ' ', '+')
    title = song.title

    url = 'https://www.lyrics.com/artist/{}'.format(artist)
    soup = get_url(url)
    location = ''
    for a in soup.select('tr a'):
        if a.string.lower() == title.lower():
            location = a['href']
            break
    if location == '':
        return ''

    url = 'https://www.lyrics.com' + location
    soup = get_url(url)
    body = soup.find(id='lyric-body-text')
    if not body:
        return ''

    return body.get_text().strip()