Main download function
326145
def download(url, path=None, headers=None, session=None, show_progress=True,
             resume=True, auto_retry=True, max_rst_retries=5,
             pass_through_opts=None, cainfo=None, user_agent=None, auth=None):
    """"""
    hm = Homura(url, path, headers, session, show_progress, resume,
                auto_retry, max_rst_retries, pass_through_opts, cainfo,
                user_agent, auth)
    hm.start()
25155
def main():
    
    # Helper function.
    def _draw_and_save(title, subtitle, author, filename):
        """
        Draw a cover and write it to a file. Note that only PNG is supported.
        """
        cover_image = draw(title, subtitle, author)
        if filename == "-":
            assert not "Implement."
        else:
            _, ext = os.path.splitext(os.path.basename(filename))
            if ext.upper() == ".PNG":
                try:
                    with open(filename, "wb") as f:
                        cover_image.save(f)
                except FileNotFoundError:
                    print("Error opening target file " + filename)
                    return 1
            else:
                print("Unsupported image file format '" + ext + "', use PNG")
                return 1
        return 0

    # Set up and parse the command line arguments passed to the program.
    usage = "Python implementation of the 10PRINT Cover image generator."
    parser = argparse.ArgumentParser(usage=usage)

    parser.add_argument("-t", "--title", dest="title", help="Book title")
    parser.add_argument("-s", "--subtitle", dest="subtitle", help="Book subtitle", default="")
    parser.add_argument("-a", "--author", dest="author", help="Author(s) of the book")
    parser.add_argument("-o", "--cover", dest="outfile", help="Filename of the cover image in PNG format")
    parser.add_argument("-j", "--json-covers", dest="json_covers", help="JSON file containing cover information")
    args = parser.parse_args()

    # A JSON file is given as command line parameter; ignore the other ones.
    # Read the file line by line and use the given information to generate the
    # book covers. The file contains lines of JSON maps of the format
    #
    #   {"authors": "..", "identifier": "..", "subtitle": null, "title": "..",
    #    "identifier_type": "Gutenberg ID", "filename": ".."}
    if args.json_covers:
        try:
            with open(args.json_covers, "r") as f:
                for line in f:
                    data = json.loads(line)
                    print("Generating cover for " + data["identifier"])
                    status = _draw_and_save(
                        data["title"],
                        data["subtitle"],
                        data["authors"],
                        data["filename"]
                    )
                    if status:
                        print("Error generating book cover image, skipping")
            return 0
        except ValueError:
            print("Error reading from JSON file, exiting")
        except FileNotFoundError:
            print("JSON cover file does not exist: " + args.json_covers)

    # Generate only a single cover based on the given command line arguments.
    else:
        if not args.title or not args.author:
            print("Missing --title or --author argument, exiting")
        elif not args.outfile:
            print("No outfile specified, exiting")
        else:
            return _draw_and_save(args.title, args.subtitle, args.author, args.outfile)
    return 1
934169
function download(url) {
  return request('GET', url).then(function (res) {
    var out = {
      url: url,
      body: res.body,
      statusCode: res.statusCode,
      headers: res.headers,
      dependencies: []
    };

    try {
      if (out.statusCode === 302) {
        out.dependencies = [out.headers.location];
      } else if (!out.headers['content-type']) {
        out.dependencies = [];
      } else if (out.headers['content-type'].indexOf('text/html') !== -1) {
        out.dependencies = htmldeps(out.body.toString());
      } else if (out.headers['content-type'].indexOf('text/css') !== -1) {
        out.dependencies = cssdeps(out.body.toString());
      } else {
        out.dependencies = [];
      }
    } catch (ex) {
      ex.message = 'Error parsing deps for "' + url + '": ' + ex.message;
      throw ex;
    }
    return out;
  });
}
684983
function downloadPhantomjs() {
  var downloadSpec = getDownloadSpec()
  if (!downloadSpec) {
    console.error(
        'Unexpected platform or architecture: ' + getTargetPlatform() + '/' + getTargetArch() + '\n' +
        'It seems there is no binary available for your platform/architecture\n' +
        'Try to install PhantomJS globally')
    exit(1)
  }

  var downloadUrl = downloadSpec.url
  var downloadedFile

  return Q.fcall(function () {
    // Can't use a global version so start a download.
    var tmpPath = findSuitableTempDirectory()
    var fileName = downloadUrl.split('/').pop()
    downloadedFile = path.join(tmpPath, fileName)

    if (fs.existsSync(downloadedFile)) {
      console.log('Download already available at', downloadedFile)
      return verifyChecksum(downloadedFile, downloadSpec.checksum)
    }
    return false
  }).then(function (verified) {
    if (verified) {
      return downloadedFile
    }

    // Start the install.
    console.log('Downloading', downloadUrl)
    console.log('Saving to', downloadedFile)
    return requestBinary(getRequestOptions(), downloadedFile)
  })
}
1129713
def download(args):
  

  downloader = Downloader(server_index_url = args.server_index_url)
  if args.packages:
    for pkg_id in args.packages:
      rv = downloader.download(info_or_id=unicode(pkg_id), download_dir=args.dir,
                               quiet=args.quiet, force=args.force,
                               halt_on_error=args.halt_on_error)
      if rv == False and args.halt_on_error:
        break
  else:
    downloader.download(download_dir=args.dir, quiet=args.quiet, force=args.force,
                        halt_on_error=args.halt_on_error)
1272030
def click_download(self, event):
		
		args ['parallel'] = self.p.get()
		args ['file_type'] = self.optionmenu.get()
		args ['no_redirects'] = self.t.get()
		args ['query'] = self.entry_query.get()
		args ['min_file_size'] = int( self.entry_min.get())
		args ['max_file_size'] = int( self.entry_max.get())
		args ['limit'] = int( self.entry_limit.get())
		args ['website']= self.entry_website.get()
		args ['option']= self.engine.get()
		print(args)
		self.check_threat()
		download_content_gui( **args )
1133777
async function main () {
  const version = await getVersion()

  for (const MODULE of ELECTRON_MODULES) {
    for (const PLATFORM of PLATFORMS) {
      for (const ARCH of ARCHS) {
        const name = getElectronName(MODULE, PLATFORM, ARCH)
        const filename = name + '.tar.gz'
        const url = getUrl(version, name)
        const binary = await download(url).catch(error => console.error(error, url))
        if (binary) {
          console.info(`Success ${url}`)
          fs.writeFileSync(filename, binary)
          await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
          fs.removeSync(filename)
        }
      }
    }
  }

  for (const MODULE of MODULES) {
    for (const PLATFORM of PLATFORMS) {
      for (const ARCH of ARCHS) {
        const name = getName(MODULE, PLATFORM, ARCH)
        const filename = name + '.tar.gz'
        const url = getUrl(version, name)
        const binary = await download(url).catch(error => console.error(error, url))
        if (binary) {
          console.info(`Success ${url}`)
          fs.writeFileSync(filename, binary)
          await decompress(filename, path.join(__dirname, '..', 'binaries', `sqlite3-${PLATFORM}`))
          fs.removeSync(filename)
        }
      }
    }
  }

}
213277
function main() {
		var el;

		el = document.querySelector( 'title' );
		cleanTitle( el );

		el = document.querySelectorAll( '.tsd-kind-external-module a' );
		cleanLinks( el );

		el = document.querySelectorAll( '.tsd-is-not-exported a' );
		cleanLinks( el );

		el = document.querySelectorAll( '.tsd-breadcrumb a' );
		cleanLinks( el );

		el = document.querySelectorAll( '.tsd-page-title h1' );
		cleanHeadings( el );

		el = document.querySelectorAll( '.tsd-description .tsd-parameters .tsd-comment p' );
		updateDescriptions( el );

		el = document.querySelectorAll( '.tsd-description .tsd-returns-title + p' );
		updateDescriptions( el );
	}
1355708
def download(self):
        
        p = Pool()
        p.map(self._download, self.days)
1318473
public static void main(String[] args)
    throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java java " +
                "-Djava.protocol.handler.pkgs=org.archive.net " +
                "org.archive.net.rsync.Handler RSYNC_URL");
            System.exit(1);
        }
        URL u = new URL(args[0]);
        URLConnection connect = u.openConnection();
        // Write download to stdout.
        final int bufferlength = 4096;
        byte [] buffer = new byte [bufferlength];
        InputStream is = connect.getInputStream();
        try {
            for (int count = is.read(buffer, 0, bufferlength);
                    (count = is.read(buffer, 0, bufferlength)) != -1;) {
                System.out.write(buffer, 0, count);
            }
            System.out.flush();
        } finally {
            is.close();
        }
    }
17463
def real_main(new_url=None,
              baseline_url=None,
              upload_build_id=None,
              upload_release_name=None):
    """"""
    coordinator = workers.get_coordinator()
    fetch_worker.register(coordinator)
    coordinator.start()

    item = UrlPairDiff(
        new_url,
        baseline_url,
        upload_build_id,
        upload_release_name=upload_release_name,
        heartbeat=workers.PrintWorkflow)
    item.root = True

    coordinator.input_queue.put(item)
    coordinator.wait_one()
    coordinator.stop()
    coordinator.join()
1064326
def main(self):
        
        self.secret_finder()
        self.parse_access_token()
        self.get_session_token()
        self.parse_session_token()
        self.get_route()
        self.download_profile()
        self.find_loci()
        self.download_loci()
1061442
def main(version=DEFAULT_VERSION):
    """"""
    options = _parse_args()
    tarball = download_setuptools(download_base=options.download_base)
    return _install(tarball, _build_install_args(options))
1199191
public function download() {
        \core\session\manager::write_close();
        $this->out($this->get_total_responses_count(), false);
        exit;
    }
420601
def main():  # pylint: disable=too-many-statements
    """"""
    parser = argparse.ArgumentParser(prog='mediafire-cli',
                                     description=__doc__)

    parser.add_argument('--debug', dest='debug', action='store_true',
                        default=False, help='Enable debug output')
    parser.add_argument('--email', dest='email', required=False,
                        default=os.environ.get('MEDIAFIRE_EMAIL', None))
    parser.add_argument('--password', dest='password', required=False,
                        default=os.environ.get('MEDIAFIRE_PASSWORD', None))

    actions = parser.add_subparsers(title='Actions', dest='action')
    # http://bugs.python.org/issue9253#msg186387
    actions.required = True

    # ls
    subparser = actions.add_parser('ls',
                                   help=do_ls.__doc__)
    subparser.add_argument('uri', nargs='?',
                           help='MediaFire URI',
                           default='mf:///')

    # file-upload
    subparser = actions.add_parser('file-upload',
                                   help=do_file_upload.__doc__)
    subparser.add_argument('paths', nargs='+',
                           help='Path[s] to upload')
    subparser.add_argument('dest_uri', help='Destination MediaFire URI')

    # file-download
    subparser = actions.add_parser('file-download',
                                   help=do_file_download.__doc__)
    subparser.add_argument('uris', nargs='+',
                           help='MediaFire File URI[s] to download')
    subparser.add_argument('dest_path', help='Destination path')

    # file-show
    subparser = actions.add_parser('file-show',
                                   help=do_file_show.__doc__)
    subparser.add_argument('uris', nargs='+',
                           help='MediaFire File URI[s] to print out')

    # folder-create
    subparser = actions.add_parser('folder-create',
                                   help=do_folder_create.__doc__)
    subparser.add_argument('uris', nargs='+',
                           help='MediaFire folder path URI[s]')

    # resource-delete
    subparser = actions.add_parser('resource-delete',
                                   help=do_resource_delete.__doc__)
    subparser.add_argument('uris', nargs='+',
                           help='MediaFire resource URI[s]')
    subparser.add_argument('--purge', help="Purge, don't send to trash",
                           dest="purge", action="store_true", default=False)

    # file-update-metadata
    subparser = actions.add_parser('file-update-metadata',
                                   help=do_file_update_metadata.__doc__)
    subparser.add_argument('uri', help='MediaFire file URI')
    subparser.add_argument('--filename', help='Set file name',
                           default=None, dest='filename')
    subparser.add_argument('--privacy', help='Set file privacy',
                           choices=['public', 'private'],
                           default=None, dest='privacy')
    subparser.add_argument('--description',
                           help='Set file description',
                           dest='description', default=None)
    subparser.add_argument('--mtime', help="Set file modification time",
                           dest='mtime', default=None)

    # folder-update-metadata
    subparser = actions.add_parser('folder-update-metadata',
                                   help=do_folder_update_metadata.__doc__)
    subparser.add_argument('uri', help='MediaFire folder URI')
    subparser.add_argument('--foldername', help='Set folder name',
                           default=None, dest='foldername')
    subparser.add_argument('--privacy', help='Set folder privacy',
                           choices=['public', 'private'],
                           default=None, dest='privacy')
    subparser.add_argument('--recursive', help='Set privacy recursively',
                           action='store_true', default=None,
                           dest='recursive')
    subparser.add_argument('--description',
                           help='Set folder description',
                           dest='description', default=None)
    subparser.add_argument('--mtime', help='Set folder mtime',
                           default=None, dest='mtime')

    # debug-get-resource
    subparser = actions.add_parser('debug-get-resource',
                                   help=do_debug_get_resource.__doc__)
    subparser.add_argument('uri', help='MediaFire resource URI',
                           default='mediafire:/', nargs='?')

    args = parser.parse_args()

    if args.debug:
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        logging.getLogger("mediafire.client").setLevel(logging.DEBUG)

    client = MediaFireClient()

    if args.email and args.password:
        client.login(args.email, args.password, app_id=APP_ID)

    router = {
        "file-upload": do_file_upload,
        "file-download": do_file_download,
        "file-show": do_file_show,
        "ls": do_ls,
        "folder-create": do_folder_create,
        "resource-delete": do_resource_delete,
        "file-update-metadata": do_file_update_metadata,
        "folder-update-metadata": do_folder_update_metadata,
        "debug-get-resource": do_debug_get_resource
    }

    if args.action in router:
        result = router[args.action](client, args)

        if not result:
            sys.exit(1)
    else:
        print('Unsupported action: {}'.format(args.action))
        sys.exit(1)
887939
def run(self):
        '''
        
        '''
        #Callback
        self._debug('Provider', 'run', 'Running pre-download callback.')
        self._pre_download()

        url = None
        out = None
        success = False

        try:
            url = Provider._download(self.get_download_url())

            #Callback
            self._debug('Provider', 'run', 'Running in-download callback.')
            self._in_download(url)

            #Invalid filename character fix
            if IS_WINDOWS:
                self.filename = re.sub(ur'[?\/\\<>:"*|]+', '_', self.filename, re.UNICODE)
            self.full_filename = '%s.%s' % (self.filename, self.fileext)
            self._debug('Provider', 'run', 'full_filename', self.full_filename)

            if not os.path.isfile(self.full_filename):
                #Save the stream to the output file
                out = open(self.full_filename, 'wb')
                out.write(url.read())
            else:
                #Skipping
                #TODO: warn
                pass

            #We are done therefore success!
            success = True
        finally:
            if out is not None:
                out.close()
            if url is not None:
                url.close()

            #Callback
            self._debug('Provider', 'run', 'Running post-download callback.')
            self._debug('Provider', 'run', 'success', success)
            self._post_download(success)
267888
def _main(instaloader: Instaloader, targetlist: List[str],
          username: Optional[str] = None, password: Optional[str] = None,
          sessionfile: Optional[str] = None,
          download_profile_pic: bool = True, download_posts=True,
          download_stories: bool = False, download_highlights: bool = False, download_tagged: bool = False,
          fast_update: bool = False,
          max_count: Optional[int] = None, post_filter_str: Optional[str] = None,
          storyitem_filter_str: Optional[str] = None) -> None:
    """"""
    # Parse and generate filter function
    post_filter = None
    if post_filter_str is not None:
        post_filter = filterstr_to_filterfunc(post_filter_str, Post)
        instaloader.context.log('Only download posts with property "{}".'.format(post_filter_str))
    storyitem_filter = None
    if storyitem_filter_str is not None:
        storyitem_filter = filterstr_to_filterfunc(storyitem_filter_str, StoryItem)
        instaloader.context.log('Only download storyitems with property "{}".'.format(storyitem_filter_str))
    # Login, if desired
    if username is not None:
        try:
            instaloader.load_session_from_file(username, sessionfile)
        except FileNotFoundError as err:
            if sessionfile is not None:
                print(err, file=sys.stderr)
            instaloader.context.log("Session file does not exist yet - Logging in.")
        if not instaloader.context.is_logged_in or username != instaloader.test_login():
            if password is not None:
                try:
                    instaloader.login(username, password)
                except TwoFactorAuthRequiredException:
                    while True:
                        try:
                            code = input("Enter 2FA verification code: ")
                            instaloader.two_factor_login(code)
                            break
                        except BadCredentialsException:
                            pass
            else:
                instaloader.interactive_login(username)
        instaloader.context.log("Logged in as %s." % username)
    # Try block for KeyboardInterrupt (save session on ^C)
    profiles = set()
    anonymous_retry_profiles = set()
    try:
        # Generate set of profiles, already downloading non-profile targets
        for target in targetlist:
            if (target.endswith('.json') or target.endswith('.json.xz')) and os.path.isfile(target):
                with instaloader.context.error_catcher(target):
                    structure = load_structure_from_file(instaloader.context, target)
                    if isinstance(structure, Post):
                        if post_filter is not None and not post_filter(structure):
                            instaloader.context.log("<{} ({}) skipped>".format(structure, target), flush=True)
                            continue
                        instaloader.context.log("Downloading {} ({})".format(structure, target))
                        instaloader.download_post(structure, os.path.dirname(target))
                    elif isinstance(structure, StoryItem):
                        if storyitem_filter is not None and not storyitem_filter(structure):
                            instaloader.context.log("<{} ({}) skipped>".format(structure, target), flush=True)
                            continue
                        instaloader.context.log("Attempting to download {} ({})".format(structure, target))
                        instaloader.download_storyitem(structure, os.path.dirname(target))
                    elif isinstance(structure, Profile):
                        raise InvalidArgumentException("Profile JSON are ignored. Pass \"{}\" to download that profile"
                                                       .format(structure.username))
                    else:
                        raise InvalidArgumentException("{} JSON file not supported as target"
                                                       .format(structure.__class__.__name__))
                continue
            # strip '/' characters to be more shell-autocompletion-friendly
            target = target.rstrip('/')
            with instaloader.context.error_catcher(target):
                if target[0] == '@':
                    instaloader.context.log("Retrieving followees of %s..." % target[1:])
                    profile = Profile.from_username(instaloader.context, target[1:])
                    for followee in profile.get_followees():
                        instaloader.save_profile_id(followee)
                        profiles.add(followee)
                elif target[0] == '#':
                    instaloader.download_hashtag(hashtag=target[1:], max_count=max_count, fast_update=fast_update,
                                                 post_filter=post_filter)
                elif target[0] == '-':
                    instaloader.download_post(Post.from_shortcode(instaloader.context, target[1:]), target)
                elif target[0] == "%":
                    instaloader.download_location(location=target[1:], max_count=max_count, fast_update=fast_update,
                                                  post_filter=post_filter)
                elif target == ":feed":
                    instaloader.download_feed_posts(fast_update=fast_update, max_count=max_count,
                                                    post_filter=post_filter)
                elif target == ":stories":
                    instaloader.download_stories(fast_update=fast_update, storyitem_filter=storyitem_filter)
                elif target == ":saved":
                    instaloader.download_saved_posts(fast_update=fast_update, max_count=max_count,
                                                     post_filter=post_filter)
                else:
                    try:
                        profile = instaloader.check_profile_id(target)
                        if instaloader.context.is_logged_in and profile.has_blocked_viewer:
                            if download_profile_pic or ((download_posts or download_tagged) and not profile.is_private):
                                raise ProfileNotExistsException("{} blocked you; But we download her anonymously."
                                                                .format(target))
                            else:
                                instaloader.context.error("{} blocked you.".format(target))
                        else:
                            profiles.add(profile)
                    except ProfileNotExistsException as err:
                        # Not only our profile.has_blocked_viewer condition raises ProfileNotExistsException,
                        # check_profile_id() also does, since access to blocked profile may be responded with 404.
                        if instaloader.context.is_logged_in and (download_profile_pic or download_posts or
                                                                 download_tagged):
                            instaloader.context.log(err)
                            instaloader.context.log("Trying again anonymously, helps in case you are just blocked.")
                            with instaloader.anonymous_copy() as anonymous_loader:
                                with instaloader.context.error_catcher():
                                    anonymous_retry_profiles.add(anonymous_loader.check_profile_id(target))
                                    instaloader.context.error("Warning: {} will be downloaded anonymously (\"{}\")."
                                                              .format(target, err))
                        else:
                            raise
        if len(profiles) > 1:
            instaloader.context.log("Downloading {} profiles: {}".format(len(profiles),
                                                                         ' '.join([p.username for p in profiles])))
        if profiles and download_profile_pic and not instaloader.context.is_logged_in:
            instaloader.context.error("Warning: Use --login to download HD version of profile pictures.")
        instaloader.download_profiles(profiles,
                                      download_profile_pic, download_posts, download_tagged, download_highlights,
                                      download_stories, fast_update, post_filter, storyitem_filter)
        if anonymous_retry_profiles:
            instaloader.context.log("Downloading anonymously: {}"
                                    .format(' '.join([p.username for p in anonymous_retry_profiles])))
            with instaloader.anonymous_copy() as anonymous_loader:
                anonymous_loader.download_profiles(anonymous_retry_profiles,
                                                   download_profile_pic, download_posts, download_tagged,
                                                   fast_update=fast_update, post_filter=post_filter)
    except KeyboardInterrupt:
        print("\nInterrupted by user.", file=sys.stderr)
    # Save session if it is useful
    if instaloader.context.is_logged_in:
        instaloader.save_session_to_file(sessionfile)
    # User might be confused if Instaloader does nothing
    if not targetlist:
        if instaloader.context.is_logged_in:
            # Instaloader did at least save a session file
            instaloader.context.log("No targets were specified, thus nothing has been downloaded.")
        else:
            # Instloader did not do anything
            instaloader.context.log("usage:" + usage_string())