This callback for the download function is used to print the download bar
430614
def report_bar(bytes_so_far, total_size, speed, eta):
    '''
    
    '''
    percent = int(bytes_so_far * 100 / total_size)
    current = approximate_size(bytes_so_far).center(9)
    total = approximate_size(total_size).center(9)
    shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
    sys.stdout.write(
        " {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
                                                      '=' * (shaded - 1),
                                                      '>',
                                                      ' ' * (AVAIL_WIDTH - shaded),
                                                      current,
                                                      total,
                                                      (approximate_size(speed) + '/s').center(11),
                                                      eta.center(10)))
    sys.stdout.write("\r")
    sys.stdout.flush()
97186
function softwareUpdate_download(channel, waitForFinish, timeout) {
    waitForFinish = waitForFinish ? waitForFinish : true;

    // Check that the correct channel has been set
    this._controller.assert(function() {
      return channel == this.channel;
    }, "The current update channel is identical to the specified one.", this);

    // Click the next button
    var next = this.getElement({type: "button", subtype: "next"});
    this._controller.click(next);

    // Wait for the download page - if it fails the update was already cached
    try {
      this.waitForWizardPage(WIZARD_PAGES.downloading);

      if (waitForFinish)
        this.waitforDownloadFinished(timeout);
    } catch (ex) {
      this.waitForWizardPage(WIZARD_PAGES.finished);
    }
  }
1177402
def download_content_gui(**args):
	
	global row

	if not args ['directory']:
		args ['directory'] = args ['query'].replace(' ', '-')

	root1 = Frame(root)
	t1 = threading.Thread(target = search_function,  args = (root1,
						  args['query'], args['website'], args['file_type'], args['limit'],args['option']))
	t1.start()
	task(root1)
	t1.join()

	#new frame for progress bar 
	row = Frame(root)
	row.pack()
	if args['parallel']:
		download_parallel_gui(row, links,  args['directory'], args['min_file_size'], 
								 args['max_file_size'], args['no_redirects'])
	else:
		download_series_gui(row, links, args['directory'], args['min_file_size'],
								 args['max_file_size'], args['no_redirects'])
1181129
def download(link, outdir='.', chunk_size=4096):
    '''
    
    '''
    url = None
    fh = None
    eta = 'unknown '
    bytes_so_far = 0
    filename = filename_from_url(link) or "."
    cj = cjar.CookieJar()

    # get filename for temp file in current directory
    (fd_tmp, tmpfile) = tempfile.mkstemp(
        ".tmp", prefix=filename + ".", dir=outdir)
    os.close(fd_tmp)
    os.unlink(tmpfile)

    try:
        opener = ulib.build_opener(ulib.HTTPCookieProcessor(cj))
        url = opener.open(link)
        fh = open(tmpfile, mode='wb')

        headers = url.info()
        try:
            total_size = int(headers['Content-Length'])
        except (ValueError, KeyError, TypeError):
            total_size = 'unknown'

        try:
            md5_header = headers['Content-MD5']
        except (ValueError, KeyError, TypeError):
            md5_header = None

        # Define which callback we're gonna use
        if total_size != 'unknown':
            if CONSOLE_WIDTH > 57:
                reporthook = report_bar
            else:
                reporthook = report_onlysize
        else:
            reporthook = report_unknown

        # Below are the registers to calculate network transfer rate
        time_register = time()
        speed = 0.0
        speed_list = []
        bytes_register = 0.0
        eta = 'unknown '

        # Loop that reads in chunks, calculates speed and does the callback to
        # print the progress
        while True:
            chunk = url.read(chunk_size)
            # Update Download Speed every 1 second
            if time() - time_register > 0.5:
                speed = (bytes_so_far - bytes_register) / \
                    (time() - time_register)
                speed_list.append(speed)

                # Set register properly for future use
                time_register = time()
                bytes_register = bytes_so_far

                # Estimative of remaining download time
                if total_size != 'unknown' and len(speed_list) == 3:
                    speed_mean = sum(speed_list) / 3
                    eta_sec = int((total_size - bytes_so_far) / speed_mean)
                    eta = str(datetime.timedelta(seconds=eta_sec))
                    speed_list = []

            bytes_so_far += len(chunk)

            if not chunk:
                sys.stdout.write('\n')
                break

            fh.write(chunk)
            reporthook(bytes_so_far, total_size, speed, eta)
    except KeyboardInterrupt:
        print('\n\nCtrl + C: Download aborted by user')
        print('Partial downloaded file:\n{0}'.format(os.path.abspath(tmpfile)))
        sys.exit(1)
    finally:
        if url:
            url.close()
        if fh:
            fh.close()

    filenamealt = filename_from_headers(headers)
    if filenamealt:
        filename = filenamealt

    # add numeric '(x)' suffix if filename already exists
    if os.path.exists(os.path.join(outdir, filename)):
        filename = filename_fix_existing(filename, outdir)
    filename = os.path.join(outdir, filename)

    shutil.move(tmpfile, filename)

    # Check if sizes matches
    if total_size != 'unknown' and total_size != bytes_so_far:
        print(
            '\n\nWARNING!! Downloaded file size mismatches... Probably corrupted...')

    # Check md5 if it was in html header
    if md5_header:
        print('\nValidating MD5 checksum...')
        if md5_header == md5sum(filename):
            print('MD5 checksum passed!')
        else:
            print('MD5 checksum do NOT passed!!!')

    return filename
923057
def download(self, url, show_status=True):
        
        import requests

        file_name = url.split('/')[-1]
        file_path = os.path.join(self.data_directory, file_name)

        # Do not download the data if it already exists
        if self.is_downloaded(file_path):
            return file_path

        with open(file_path, 'wb') as open_file:
            print('Downloading %s' % url)
            response = requests.get(url, stream=True)
            total_length = response.headers.get('content-length')

            if total_length is None:
                # No content length header
                open_file.write(response.content)
            else:
                download = 0
                total_length = int(total_length)
                for data in response.iter_content(chunk_size=4096):
                    download += len(data)
                    open_file.write(data)
                    if show_status:
                        done = int(50 * download / total_length)
                        sys.stdout.write('\r[%s%s]' % ('=' * done, ' ' * (50 - done)))
                        sys.stdout.flush()

            # Add a new line after the download bar
            sys.stdout.write('\n')

        print('Download location: %s' % file_path)
        return file_path
568535
def maybe_download_and_extract():
  """"""
  dest_directory = "/tmp/cifar"
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
          float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
    tarfile.open(filepath, 'r:gz').extractall(dest_directory)
542294
private static int printProgress(String str, long received,
      long advertisedSize, int lastPrinted) {
    if (advertisedSize == 0)
      return 0;
    int currentPercent = (int) ((received * 100) / advertisedSize);
    if (currentPercent != lastPrinted)
      FLOG.info("Downloading: " + str + ", completed: " + currentPercent);
    return currentPercent;
  }
879866
def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
        

        local_file_name = local_file_name if local_file_name else url.split('/')[-1]
        filepath = os.path.join(cls.data_path, local_file_name)

        if not os.path.exists(filepath) or force:
            try:
                headers = requests.head(url, allow_redirects=True).headers
                length = headers.get('Content-Length')

                logger.info("Starting download of {} file with {} bytes ...".format(url, length))

                widgets = [
                    'Downloading file please wait...', progressbar.Percentage(),
                    ' ', progressbar.Bar(),
                    ' ', progressbar.ETA(),
                    ' ', progressbar.FileTransferSpeed(),
                ]
                bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()

                r = requests.get(url, stream=True)

                with open(filepath, 'wb') as f:
                    total_chunk = 0

                    for chunk in r.iter_content(chunk_size):
                        if chunk:
                            f.write(chunk)
                            total_chunk += chunk_size
                            bar.update(total_chunk)

                bar.finish()

            except:
                if os.path.exists(filepath):
                    os.remove(filepath)

                raise

        return filepath
1162562
function download(url, callback) {
	let reqData = URL.parse(url);
	reqData.servername = reqData.hostname;
	reqData.headers = {"User-Agent": "node-steam-user data parser"};
	reqData.method = "GET";

	// This will crash if there's an error. But that's fine.
	HTTPS.request(reqData, function(res) {
		let data = "";
		res.on('data', function(chunk) {
			data += chunk;
		});

		res.on('end', function() {
			callback(data);
		});
	}).end();
}
918104
function _cmdDownloadFile(downloadId, url, proxy, callback, pCallback) {
    // Backwards compatibility check, added in 0.37
    if (typeof proxy === "function") {
        callback = proxy;
        proxy = undefined;
    }

    if (pendingDownloads[downloadId]) {
        callback(Errors.DOWNLOAD_ID_IN_USE, null);
        return;
    }

    var req = request.get({
        url: url,
        encoding: null,
        proxy: proxy
    },
        // Note: we could use the traditional "response"/"data"/"end" events too if we wanted to stream data
        // incrementally, limit download size, etc. - but the simple callback is good enough for our needs.
        function (error, response, body) {
            if (error) {
                // Usually means we never got a response - server is down, no DNS entry, etc.
                _endDownload(downloadId, Errors.NO_SERVER_RESPONSE);
                return;
            }
            if (response.statusCode !== 200) {
                _endDownload(downloadId, [Errors.BAD_HTTP_STATUS, response.statusCode]);
                return;
            }

            var stream = temp.createWriteStream("brackets");
            if (!stream) {
                _endDownload(downloadId, Errors.CANNOT_WRITE_TEMP);
                return;
            }
            pendingDownloads[downloadId].localPath = stream.path;
            pendingDownloads[downloadId].outStream = stream;

            stream.write(body);
            _endDownload(downloadId);
        });

    pendingDownloads[downloadId] = { request: req, callback: callback };
}
400775
def DownloadResource(url, path):
    ''''''
    import requests
    from six import BytesIO
    import zipfile
    print("Downloading... {} to {}".format(url, path))
    r = requests.get(url, stream=True)
    z = zipfile.ZipFile(BytesIO(r.content))
    z.extractall(path)
    print("Completed download and extraction.")
448907
def get_download_link(self):
        
        url = None
        if not self.get("downloadable"):
            try:
                url = self.client.get_location(
                    self.client.STREAM_URL % self.get("id"))
            except serror as e:
                print(e)

        if not url:
            try:
                url = self.client.get_location(
                    self.client.DOWNLOAD_URL % self.get("id"))
            except serror as e:
                print(e)

        return url
1089563
def handle_log_data(self, m):
        ''''''
        if self.download_file is None:
            return
        # lose some data
        # import random
        # if random.uniform(0,1) < 0.05:
        #    print('dropping ', str(m))
        #    return
        if m.ofs != self.download_ofs:
            self.download_file.seek(m.ofs)
            self.download_ofs = m.ofs
        if m.count != 0:
            data = m.data[:m.count]
            s = ''.join(str(chr(x)) for x in data)
            self.download_file.write(s)
            self.download_set.add(m.ofs // 90)
            self.download_ofs += m.count
        self.download_last_timestamp = time.time()
        if m.count == 0 or (m.count < 90 and len(self.download_set) == 1 + (m.ofs // 90)):
            dt = time.time() - self.download_start
            self.download_file.close()
            size = os.path.getsize(self.download_filename)
            speed = size / (1000.0 * dt)
            print("Finished downloading %s (%u bytes %u seconds, %.1f kbyte/sec %u retries)" % (
                self.download_filename,
                size,
                dt, speed,
                self.retries))
            self.download_file = None
            self.download_filename = None
            self.download_set = set()
417642
def download_file_with_progress_bar(url):
    
    request = requests.get(url, stream=True)
    if request.status_code == 404:
        msg = ('there was a 404 error trying to reach {} \nThis probably '
               'means the requested version does not exist.'.format(url))
        logger.error(msg)
        sys.exit()
    total_size = int(request.headers["Content-Length"])
    chunk_size = 1024
    bars = int(total_size / chunk_size)
    bytes_io = io.BytesIO()
    pbar = tqdm(request.iter_content(chunk_size=chunk_size), total=bars,
                unit="kb", leave=False)
    for chunk in pbar:
        bytes_io.write(chunk)
    return bytes_io
1299749
def _download_images(self):
        

        print('\nDownloading Images for the Query: ' + self._imageQuery)

        try:
            self._initialize_progress_bar()

            # Initialize and assign work to the threads in the threadpool
            threadPool = Pool(self._threadCount)
            threadPool.map(self._download_image, self._imageURLs)

            threadPool.close()
            threadPool.join()

            # Download each image individually
            # [self._download_image(imageURL) for imageURL in self._imageURLs]

            self._downloadProgressBar.finish()

        except Exception as exception:
            print('Error - Image Download: ' + format(exception))
585758
function download(input, output) {
	if (!output) output = input.split("/").pop();
	var file = fs.createWriteStream(output);
	var request = http.get(input, response => { response.pipe(file); });
}
943780
def get(self):
        """"""
        method_name = "_download_" + self.name
        method = getattr(self, method_name)
        return method()