Copies every track to its own wav file in the given folder.
        Every track will be stored at ``target_path/track_id.wav``.
327547
def relocate_audio_to_wav_files(self, target_path):
        

        if not os.path.isdir(target_path):
            os.makedirs(target_path)

        new_tracks = {}

        # First create a new container track for all existing tracks
        for track in self.tracks.values():
            track_path = os.path.join(target_path, '{}.wav'.format(track.idx))
            sr = track.sampling_rate
            samples = track.read_samples()

            audio.write_wav(track_path, samples, sr=sr)
            new_track = tracks.FileTrack(track.idx, track_path)

            new_tracks[track.idx] = new_track

        # Update track list of corpus
        self._tracks = new_tracks

        # Update utterances to point to new tracks
        for utterance in self.utterances.values():
            new_track = self.tracks[utterance.track.idx]
            utterance.track = new_track
757090
def copy_dir(self, path):
        
        for directory in path:
            if os.path.isdir(path):
                full_path = os.path.join(self.archive_dir, directory.lstrip('/'))
                logger.debug("Copying %s to %s", directory, full_path)
                shutil.copytree(directory, full_path)
            else:
                logger.debug("Not a directory: %s", directory)
        return path
1176729
def train(train_dir=None, train_csv=None, epochs=30, batch_size=32):
    """"""

    if not train_dir or not os.path.exists(train_dir) or not train_csv:
        warnings.warn("No train directory could be found ")
        return
    # Make a dataset from the local folder containing Audio data
    print("\nMaking an Audio Dataset...\n")
    tick = time.time()
    aud_dataset = AudioFolderDataset(train_dir, train_csv=train_csv, file_format='.wav', skip_header=True)
    tock = time.time()

    print("Loading the dataset took ", (tock-tick), " seconds.")
    print("\n=======================================\n")
    print("Number of output classes = ", len(aud_dataset.synsets))
    print("\nThe labels are : \n")
    print(aud_dataset.synsets)
    # Get the model to train
    net = model.get_net(len(aud_dataset.synsets))
    print("\nNeural Network = \n")
    print(net)
    print("\nModel - Neural Network Generated!\n")
    print("=======================================\n")

    #Define the loss - Softmax CE Loss
    softmax_loss = gluon.loss.SoftmaxCELoss(from_logits=False, sparse_label=True)
    print("Loss function initialized!\n")
    print("=======================================\n")

    #Define the trainer with the optimizer
    trainer = gluon.Trainer(net.collect_params(), 'adadelta')
    print("Optimizer - Trainer function initialized!\n")
    print("=======================================\n")
    print("Loading the dataset to the Gluon's OOTB Dataloader...")

    #Getting the data loader out of the AudioDataset and passing the transform
    from transforms import MFCC
    aud_transform = MFCC()
    tick = time.time()

    audio_train_loader = gluon.data.DataLoader(aud_dataset.transform_first(aud_transform), batch_size=32, shuffle=True)
    tock = time.time()
    print("Time taken to load data and apply transform here is ", (tock-tick), " seconds.")
    print("=======================================\n")


    print("Starting the training....\n")
    # Training loop
    tick = time.time()
    batch_size = batch_size
    num_examples = len(aud_dataset)

    for epoch in range(epochs):
        cumulative_loss = 0
        for data, label in audio_train_loader:
            with autograd.record():
                output = net(data)
                loss = softmax_loss(output, label)
            loss.backward()

            trainer.step(batch_size)
            cumulative_loss += mx.nd.sum(loss).asscalar()

        if epoch%5 == 0:
            train_accuracy = evaluate_accuracy(audio_train_loader, net)
            print("Epoch {}. Loss: {} Train accuracy : {} ".format(epoch, cumulative_loss/num_examples, train_accuracy))
            print("\n------------------------------\n")

    train_accuracy = evaluate_accuracy(audio_train_loader, net)
    tock = time.time()
    print("\nFinal training accuracy: ", train_accuracy)

    print("Training the sound classification for ", epochs, " epochs, MLP model took ", (tock-tick), " seconds")
    print("====================== END ======================\n")

    print("Trying to save the model parameters here...")
    net.save_parameters("./net.params")
    print("Saved the model parameters in current directory.")
33004
def copy(from_path, to_path)
      resp = request('/files/copy', from_path: from_path, to_path: to_path)
      parse_tagged_response(resp)
    end
410190
def copy_file(self, path):
        
        if "*" in path:
            paths = _expand_paths(path)
            if paths:
                for path in paths:
                    self._copy_file(path)
        else:
            if os.path.isfile(path):
                return self._copy_file(path)
            else:
                logger.debug("File %s does not exist", path)
                return False
841746
function(dir, kits, file) {
                        var fillindex = kits.indexOf(file);
                        if (fillindex != -1) {
                            var copySnippet = path.join(dir, file);
                            var copySrc = copySnippet.replace(snipConfig, srcFile);
                            var data = fs.readFileSync(copySnippet, 'utf-8');
                            fse.ensureFileSync(copySrc);
                            fs.writeFileSync(copySrc, data, 'utf-8');
                            // console.log("copySnippet:",copySnippet,"...copySrc",copySrc)
                        }
                    }
907593
def share(track_id=None, url=None, users=None):
    

    client = get_client()

    if url:
        track_id = client.get('/resolve', url=url).id

    if not users:
        return client.get('/tracks/%d/permissions' % track_id)

    permissions = {'user_id': []}

    for username in users:
        # check cache for user
        user = settings.users.get(username, None)
        if user:
            permissions['user_id'].append(user['id'])
        else:
            user = client.get('/resolve', url='http://soundcloud.com/%s' % username)
            permissions['user_id'].append(user.id)
            settings.users[username] = user.obj
    settings.save()

    return client.put('/tracks/%d/permissions' % track_id, permissions=permissions)
980376
def download_tracks(client, tracks, num_tracks=sys.maxsize, downloadable=False, folders=False, custom_path='', id3_extras={}):
    

    filenames = []

    for i, track in enumerate(tracks):

        # "Track" and "Resource" objects are actually different,
        # even though they're the same.
        if isinstance(track, soundcloud.resource.Resource):

            try:

                t_track = {}
                t_track['downloadable'] = track.downloadable
                t_track['streamable'] = track.streamable
                t_track['title'] = track.title
                t_track['user'] = {'username': track.user['username']}
                t_track['release_year'] = track.release
                t_track['genre'] = track.genre
                t_track['artwork_url'] = track.artwork_url
                if track.downloadable:
                    t_track['stream_url'] = track.download_url
                else:
                    if downloadable:
                        puts_safe(colored.red("Skipping") + colored.white(": " + track.title))
                        continue
                    if hasattr(track, 'stream_url'):
                        t_track['stream_url'] = track.stream_url
                    else:
                        t_track['direct'] = True
                        streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams?client_id=%s&app_version=%s" % (
                        str(track.id), AGGRESSIVE_CLIENT_ID, APP_VERSION)
                        response = requests.get(streams_url).json()
                        t_track['stream_url'] = response['http_mp3_128_url']

                track = t_track
            except Exception as e:
                puts_safe(colored.white(track.title) + colored.red(' is not downloadable.'))
                continue

        if i > num_tracks - 1:
            continue
        try:
            if not track.get('stream_url', False):
                puts_safe(colored.white(track['title']) + colored.red(' is not downloadable.'))
                continue
            else:
                track_artist = sanitize_filename(track['user']['username'])
                track_title = sanitize_filename(track['title'])
                track_filename = track_artist + ' - ' + track_title + '.mp3'

                if folders:
                    track_artist_path = join(custom_path, track_artist)
                    if not exists(track_artist_path):
                        mkdir(track_artist_path)
                    track_filename = join(track_artist_path, track_filename)
                else:
                    track_filename = join(custom_path, track_filename)

                if exists(track_filename):
                    puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_title))
                    continue

                puts_safe(colored.green("Downloading") + colored.white(": " + track['title']))


                if track.get('direct', False):
                    location = track['stream_url']
                else:
                    stream = client.get(track['stream_url'], allow_redirects=False, limit=200)
                    if hasattr(stream, 'location'):
                        location = stream.location
                    else:
                        location = stream.url

                filename = download_file(location, track_filename)
                tagged = tag_file(filename,
                         artist=track['user']['username'],
                         title=track['title'],
                         year=track['release_year'],
                         genre=track['genre'],
                         album=id3_extras.get('album', None),
                         artwork_url=track['artwork_url'])

                if not tagged:
                    wav_filename = filename[:-3] + 'wav'
                    os.rename(filename, wav_filename)
                    filename = wav_filename

                filenames.append(filename)
        except Exception as e:
            puts_safe(colored.red("Problem downloading ") + colored.white(track['title']))
            puts_safe(e)

    return filenames
498453
def _copy_files(source, target):
    
    source_files = listdir(source)
    if not exists(target):
        makedirs(target)
    for filename in source_files:
        full_filename = join(source, filename)
        if isfile(full_filename):
            shutil.copy(full_filename, target)
1059828
def copy_files
      files_to_copy.each do |origin, destination|
        template(origin, destination, force: true)
      end
    end
627845
def trackSeek(path, artist, album, track, trackNum, fmt):
    """"""
    hiddenName = "(Hidden Track).{}".format(fmt)
    trackName = track + ".{}".format(fmt)
    songIn = instantiateSong(path)
    times = findGap(songIn)
    saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1]), artist, album, trackNum)
    # return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenName)]
    return [trackName, hiddenName]
1257310
def save(self, path):
        ''' 
        '''
        # IMPORTANT WARNING: saves entire source video
        self.clip.write_videofile(path, audio_fps=self.clip.audio.fps)
810838
def out_putfile(self, fpath):
        
        with open(fpath, 'w') as csv_file:
            output = csv.writer(csv_file)
            output.writerows(self.__raw_data)
1019671
def run_on_changes(paths)
      validate_at_least_one_target('copy')
      with_all_target_paths(paths) do |from_path, to_path|
        to_dir = File.dirname(to_path)
        if !File.directory?(to_dir) && options[:mkpath]
          UI.info("creating directory #{to_dir}") if options[:verbose]
          FileUtils.mkpath(to_dir)
        end
        validate_to_path(to_path)
        UI.info("copying to #{to_path}") if options[:verbose]
        copy(from_path, to_path)
      end
    end
295223
def save(path)
      File.open(path,'w') do |file|
        each { |word| file.puts word }
      end

      return self
    end
1202131
def load_midi_file(path):
    """"""

    midi_notes = []
    def register_note(track, channel, pitch, velocity, start, end):
        midi_notes.append((pitch, start, end))
    midi.register_note = register_note

    global m
    m = midi.MidiFile()
    m.open(midi_path)
    m.read()
    m.close()

    for (pitch, start, end) in midi_notes:
        start /= m.ticksPerQuarterNote
        end /= m.ticksPerQuarterNote
        yield (pitch, start, end)
47294
def write_wave(path, audio, sample_rate):
    
    with contextlib.closing(wave.open(path, 'wb')) as wf:
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(sample_rate)
        wf.writeframes(audio)