Returns Torrent object created from a file or a directory.

        :param str src_path:
        :rtype: Torrent
11586
def create_from(cls, src_path):
        
        is_dir = isdir(src_path)
        target_files, size_data = cls._get_target_files_info(src_path)

        SIZE_MIN = 32768  # 32 KiB
        SIZE_DEFAULT = 262144  # 256 KiB
        SIZE_MAX = 1048576  # 1 MiB

        CHUNKS_MIN = 1000  # todo use those limits as advised
        CHUNKS_MAX = 2200

        size_piece = SIZE_MIN
        if size_data > SIZE_MIN:
            size_piece = SIZE_DEFAULT

        if size_piece > SIZE_MAX:
            size_piece = SIZE_MAX

        def read(filepath):
            with open(filepath, 'rb') as f:
                while True:
                    chunk = f.read(size_piece - len(pieces_buffer))
                    chunk_size = len(chunk)
                    if chunk_size == 0:
                        break
                    yield chunk

        pieces = bytearray()
        pieces_buffer = bytearray()

        for fpath, _, _ in target_files:
            for chunk in read(fpath):
                pieces_buffer += chunk

                if len(pieces_buffer) == size_piece:
                    pieces += sha1(pieces_buffer).digest()[:20]
                    pieces_buffer = bytearray()

        if len(pieces_buffer):
            pieces += sha1(pieces_buffer).digest()[:20]
            pieces_buffer = bytearray()

        info = {
            'name': basename(src_path),
            'pieces': bytes(pieces),
            'piece length': size_piece,
        }

        if is_dir:
            files = []

            for _, length, path in target_files:
                files.append({'length': length, 'path': path})

            info['files'] = files

        else:
            info['length'] = target_files[0][1]

        torrent = cls({'info': info})
        torrent.created_by = get_app_version()
        torrent.creation_date = datetime.utcnow()

        return torrent
1191288
def download(self, url, dir_path, filename=None):
        
        if not filename:
            filename = url.rsplit('/', 1)[1]
        path = os.path.join(dir_path, filename)

        content = self.fetch(url)
        with open(path, "wb") as f:
            f.write(content)

        return path
190817
def files(self):
        
        files = []
        info = self._struct.get('info')

        if not info:
            return files

        if 'files' in info:
            base = info['name']

            for f in info['files']:
                files.append(TorrentFile(join(base, *f['path']), f['length']))

        else:
            files.append(TorrentFile(info['name'], info['length']))

        return files
1226633
def __generate_file(self, file_path):
        
        file_path = os.path.expanduser(file_path)
        if not os.path.exists(os.path.dirname(file_path)):
            self.logger.debug("Directories missing! Creating directories for %s..." % file_path)
            os.makedirs(os.path.dirname(file_path))
        if not os.path.exists(file_path):
            open(file_path, "w+").close()
        return file_path
75485
def download_links(self, dir_path):
    
    links = self.links
    if not path.exists(dir_path):
      makedirs(dir_path)
    for i, url in enumerate(links):
      if 'start' in self.cseargs:
        i += int(self.cseargs['start'])
      ext = self.cseargs['fileType']
      ext = '.html' if ext == '' else '.' + ext
      file_name = self.cseargs['q'].replace(' ', '_') + '_' + str(i) + ext
      file_path = path.join(dir_path, file_name)
      r = requests.get(url, stream=True)
      if r.status_code == 200:
        with open(file_path, 'wb') as f:
          r.raw.decode_content = True
          shutil.copyfileobj(r.raw, f)
900637
def get_file_content(self, path):
        
        id = self._get_id_for_path(path)
        blob = self.repository._repo[id]
        return blob.as_pretty_string()
417324
def create_directory(self, path):
        
        _complain_ifclosed(self.closed)
        return self.fs.create_directory(path)
248910
def create_dir_rec(path: Path):
    
    if not path.exists():
        Path.mkdir(path, parents=True, exist_ok=True)
276810
def download_file(self, file_path, range=None):
        
        headers = {"range": range} if range else None
        url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path)
        return self.session.get(
            url, headers=headers, proxy=self.proxy, proxy_auth=self.proxy_auth
        )
640435
def get_remote_file(self, remote_path, local_path):
        
        sftp_client = self.transport.open_sftp_client()
        LOG.debug('Get the remote file. '
                  'Source=%(src)s. Target=%(target)s.' %
                  {'src': remote_path, 'target': local_path})
        try:
            sftp_client.get(remote_path, local_path)
        except Exception as ex:
            LOG.error('Failed to secure copy. Reason: %s.' %
                      six.text_type(ex))
            raise SFtpExecutionError(err=ex)
1155254
def from_path(cls, path):
    
    if os.path.exists(path) is False:
      raise errors.InvalidPathError(path)
    return cls(path=path)
318442
def _fetch_parent_path(self, request: Request, use_cache: bool=True):
        '''
        '''
        directory_url = to_dir_path_url(request.url_info)

        if use_cache:
            if directory_url in self._processor.listing_cache:
                return self._processor.listing_cache[directory_url]

        directory_request = copy.deepcopy(request)
        directory_request.url = directory_url

        _logger.debug('Check if URL {} is file with {}.', request.url,
                      directory_url)

        with self._processor.ftp_client.session() as session:
            try:
                yield from session.start_listing(directory_request)
            except FTPServerError:
                _logger.debug('Got an error. Assume is file.')

                if use_cache:
                    self._processor.listing_cache[directory_url] = None

                return

            temp_file = tempfile.NamedTemporaryFile(
                dir=self._item_session.app_session.root_path,
                prefix='tmp-wpull-list'
            )

            with temp_file as file:
                directory_response = yield from session.download_listing(
                    file, duration_timeout=self._fetch_rule.duration_timeout)

        if use_cache:
            self._processor.listing_cache[directory_url] = \
                directory_response.files

        return directory_response.files
183567
def check_create_folder(folder_path):
    
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    return folder_path
523918
def info(torrent_path):
    """"""

    my_torrent = Torrent.from_file(torrent_path)

    size = my_torrent.total_size

    click.secho('Name: %s' % my_torrent.name, fg='blue')
    click.secho('Files:')
    for file_tuple in my_torrent.files:
        click.secho(file_tuple.name)

    click.secho('Hash: %s' % my_torrent.info_hash, fg='blue')
    click.secho('Size: %s (%s)' % (humanize_filesize(size), size), fg='blue')
    click.secho('Magnet: %s' % my_torrent.get_magnet(), fg='yellow')
146735
def from_path(cls, path: pathlib.Path) -> 'Directory':
        
        if not path.is_dir():
            raise ValueError('Path does not point to a directory')
        return Directory(path.name, {entity.name: Entity.from_path(entity)
                                     for entity in path.iterdir()})
403000
def from_folder(cls, path:PathOrStr, train:PathOrStr='train', valid:PathOrStr='valid',
                    valid_pct=None, classes:Collection=None, **kwargs:Any)->'ImageDataBunch':
        ""
        path=Path(path)
        il = ImageList.from_folder(path)
        if valid_pct is None: src = il.split_by_folder(train=train, valid=valid)
        else: src = il.split_by_rand_pct(valid_pct)
        src = src.label_from_folder(classes=classes)
        return cls.create_from_ll(src, **kwargs)
724436
def do_get(self, from_path, to_path):
        
        to_file = open(os.path.expanduser(to_path), "wb")

        self.n.downloadFile(self.current_path + "/" + from_path, to_path)