idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
24,000 | def add_tar_opts ( cmdlist , compression , verbosity ) : progname = os . path . basename ( cmdlist [ 0 ] ) if compression == 'gzip' : cmdlist . append ( '-z' ) elif compression == 'compress' : cmdlist . append ( '-Z' ) elif compression == 'bzip2' : cmdlist . append ( '-j' ) elif compression in ( 'lzma' , 'xz' ) and progname == 'bsdtar' : cmdlist . append ( '--%s' % compression ) elif compression in ( 'lzma' , 'xz' , 'lzip' ) : program = compression cmdlist . extend ( [ '--use-compress-program' , program ] ) if verbosity > 1 : cmdlist . append ( '--verbose' ) if progname == 'tar' : cmdlist . append ( '--force-local' ) | Add tar options to cmdlist . |
24,001 | def list_zip ( archive , compression , cmd , verbosity , interactive ) : try : with zipfile . ZipFile ( archive , "r" ) as zfile : for name in zfile . namelist ( ) : if verbosity >= 0 : print ( name ) except Exception as err : msg = "error listing %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | List member of a ZIP archive with the zipfile Python module . |
24,002 | def extract_zip ( archive , compression , cmd , verbosity , interactive , outdir ) : try : with zipfile . ZipFile ( archive ) as zfile : zfile . extractall ( outdir ) except Exception as err : msg = "error extracting %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | Extract a ZIP archive with the zipfile Python module . |
24,003 | def create_zip ( archive , compression , cmd , verbosity , interactive , filenames ) : try : with zipfile . ZipFile ( archive , 'w' ) as zfile : for filename in filenames : if os . path . isdir ( filename ) : write_directory ( zfile , filename ) else : zfile . write ( filename ) except Exception as err : msg = "error creating %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | Create a ZIP archive with the zipfile Python module . |
24,004 | def write_directory ( zfile , directory ) : for dirpath , dirnames , filenames in os . walk ( directory ) : zfile . write ( dirpath ) for filename in filenames : zfile . write ( os . path . join ( dirpath , filename ) ) | Write recursively all directories and filenames to zipfile instance . |
24,005 | def extract_shn ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ util . shell_quote ( cmd ) ] outfile = util . get_single_outfile ( outdir , archive , extension = ".wav" ) cmdlist . extend ( [ '-x' , '-' , util . shell_quote ( outfile ) , '<' , util . shell_quote ( archive ) ] ) return ( cmdlist , { 'shell' : True } ) | Decompress a SHN archive to a WAV file . |
24,006 | def create_shn ( archive , compression , cmd , verbosity , interactive , filenames ) : if len ( filenames ) > 1 : raise util . PatoolError ( "multiple filenames for shorten not supported" ) cmdlist = [ util . shell_quote ( cmd ) ] cmdlist . extend ( [ '-' , util . shell_quote ( archive ) , '<' , util . shell_quote ( filenames [ 0 ] ) ] ) return ( cmdlist , { 'shell' : True } ) | Compress a WAV file to a SHN archive . |
24,007 | def extract_dms ( archive , compression , cmd , verbosity , interactive , outdir ) : check_archive_ext ( archive ) cmdlist = [ cmd , '-d' , outdir ] if verbosity > 1 : cmdlist . append ( '-v' ) cmdlist . extend ( [ 'u' , archive ] ) return cmdlist | Extract a DMS archive . |
24,008 | def list_dms ( archive , compression , cmd , verbosity , interactive ) : check_archive_ext ( archive ) return [ cmd , 'v' , archive ] | List a DMS archive . |
24,009 | def list_xz ( archive , compression , cmd , verbosity , interactive ) : cmdlist = [ cmd ] cmdlist . append ( '-l' ) if verbosity > 1 : cmdlist . append ( '-v' ) cmdlist . append ( archive ) return cmdlist | List a XZ archive . |
24,010 | def extract_lzma ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ util . shell_quote ( cmd ) , '--format=lzma' ] if verbosity > 1 : cmdlist . append ( '-v' ) outfile = util . get_single_outfile ( outdir , archive ) cmdlist . extend ( [ '-c' , '-d' , '--' , util . shell_quote ( archive ) , '>' , util . shell_quote ( outfile ) ] ) return ( cmdlist , { 'shell' : True } ) | Extract an LZMA archive . |
24,011 | def extract_ace ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , 'x' ] if not outdir . endswith ( '/' ) : outdir += '/' cmdlist . extend ( [ archive , outdir ] ) return cmdlist | Extract an ACE archive . |
24,012 | def list_ace ( archive , compression , cmd , verbosity , interactive ) : cmdlist = [ cmd ] if verbosity > 1 : cmdlist . append ( 'v' ) else : cmdlist . append ( 'l' ) cmdlist . append ( archive ) return cmdlist | List an ACE archive . |
24,013 | def extract_bzip2 ( archive , compression , cmd , verbosity , interactive , outdir ) : targetname = util . get_single_outfile ( outdir , archive ) try : with bz2 . BZ2File ( archive ) as bz2file : with open ( targetname , 'wb' ) as targetfile : data = bz2file . read ( READ_SIZE_BYTES ) while data : targetfile . write ( data ) data = bz2file . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error extracting %s to %s: %s" % ( archive , targetname , err ) raise util . PatoolError ( msg ) return None | Extract a BZIP2 archive with the bz2 Python module . |
24,014 | def create_bzip2 ( archive , compression , cmd , verbosity , interactive , filenames ) : if len ( filenames ) > 1 : raise util . PatoolError ( 'multi-file compression not supported in Python bz2' ) try : with bz2 . BZ2File ( archive , 'wb' ) as bz2file : filename = filenames [ 0 ] with open ( filename , 'rb' ) as srcfile : data = srcfile . read ( READ_SIZE_BYTES ) while data : bz2file . write ( data ) data = srcfile . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error creating %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | Create a BZIP2 archive with the bz2 Python module . |
24,015 | def extract_lzh ( archive , compression , cmd , verbosity , interactive , outdir ) : opts = 'x' if verbosity > 1 : opts += 'v' opts += "w=%s" % outdir return [ cmd , opts , archive ] | Extract a LZH archive . |
24,016 | def list_lzh ( archive , compression , cmd , verbosity , interactive ) : cmdlist = [ cmd ] if verbosity > 1 : cmdlist . append ( 'v' ) else : cmdlist . append ( 'l' ) cmdlist . append ( archive ) return cmdlist | List a LZH archive . |
24,017 | def extract_ape ( archive , compression , cmd , verbosity , interactive , outdir ) : outfile = util . get_single_outfile ( outdir , archive , extension = ".wav" ) return [ cmd , archive , outfile , '-d' ] | Decompress an APE archive to a WAV file . |
24,018 | def extract_adf ( archive , compression , cmd , verbosity , interactive , outdir ) : return [ cmd , archive , '-d' , outdir ] | Extract an ADF archive . |
24,019 | def extract_lrzip ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , '-d' ] if verbosity > 1 : cmdlist . append ( '-v' ) outfile = util . get_single_outfile ( outdir , archive ) cmdlist . extend ( [ "-o" , outfile , os . path . abspath ( archive ) ] ) return cmdlist | Extract a LRZIP archive . |
24,020 | def list_bzip2 ( archive , compression , cmd , verbosity , interactive ) : return stripext ( cmd , archive , verbosity ) | List a BZIP2 archive . |
24,021 | def list_ape ( archive , compression , cmd , verbosity , interactive ) : return stripext ( cmd , archive , verbosity , extension = ".wav" ) | List an APE archive . |
24,022 | def stripext ( cmd , archive , verbosity , extension = "" ) : if verbosity >= 0 : print ( util . stripext ( archive ) + extension ) return None | Print the name without suffix . |
24,023 | def extract_ar ( archive , compression , cmd , verbosity , interactive , outdir ) : opts = 'x' if verbosity > 1 : opts += 'v' cmdlist = [ cmd , opts , os . path . abspath ( archive ) ] return ( cmdlist , { 'cwd' : outdir } ) | Extract a AR archive . |
24,024 | def list_ar ( archive , compression , cmd , verbosity , interactive ) : opts = 't' if verbosity > 1 : opts += 'v' return [ cmd , opts , archive ] | List a AR archive . |
24,025 | def create_ar ( archive , compression , cmd , verbosity , interactive , filenames ) : opts = 'rc' if verbosity > 1 : opts += 'v' cmdlist = [ cmd , opts , archive ] cmdlist . extend ( filenames ) return cmdlist | Create a AR archive . |
24,026 | def extract_cab ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , '-d' , outdir ] if verbosity > 0 : cmdlist . append ( '-v' ) cmdlist . append ( archive ) return cmdlist | Extract a CAB archive . |
24,027 | def list_cab ( archive , compression , cmd , verbosity , interactive ) : cmdlist = [ cmd , '-l' ] if verbosity > 0 : cmdlist . append ( '-v' ) cmdlist . append ( archive ) return cmdlist | List a CAB archive . |
24,028 | def extract_rzip ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , '-d' , '-k' ] if verbosity > 1 : cmdlist . append ( '-v' ) outfile = util . get_single_outfile ( outdir , archive ) cmdlist . extend ( [ "-o" , outfile , archive ] ) return cmdlist | Extract an RZIP archive . |
24,029 | def program_supports_compression ( program , compression ) : if program in ( 'tar' , ) : return compression in ( 'gzip' , 'bzip2' , 'xz' , 'lzip' , 'compress' , 'lzma' ) + py_lzma elif program in ( 'star' , 'bsdtar' , 'py_tarfile' ) : return compression in ( 'gzip' , 'bzip2' ) + py_lzma return False | Decide if the given program supports the compression natively . |
24,030 | def get_archive_format ( filename ) : mime , compression = util . guess_mime ( filename ) if not ( mime or compression ) : raise util . PatoolError ( "unknown archive format for file `%s'" % filename ) if mime in ArchiveMimetypes : format = ArchiveMimetypes [ mime ] else : raise util . PatoolError ( "unknown archive format for file `%s' (mime-type is `%s')" % ( filename , mime ) ) if format == compression : compression = None return format , compression | Detect filename archive format and optional compression . |
24,031 | def check_archive_format ( format , compression ) : if format not in ArchiveFormats : raise util . PatoolError ( "unknown archive format `%s'" % format ) if compression is not None and compression not in ArchiveCompressions : raise util . PatoolError ( "unkonwn archive compression `%s'" % compression ) | Make sure format and compression is known . |
24,032 | def find_archive_program ( format , command , program = None ) : commands = ArchivePrograms [ format ] programs = [ ] if program is not None : programs . append ( program ) for key in ( None , command ) : if key in commands : programs . extend ( commands [ key ] ) if not programs : raise util . PatoolError ( "%s archive format `%s' is not supported" % ( command , format ) ) for program in programs : if program . startswith ( 'py_' ) : return program exe = util . find_program ( program ) if exe : if program == '7z' and format == 'rar' and not util . p7zip_supports_rar ( ) : continue return exe raise util . PatoolError ( "could not find an executable program to %s format %s; candidates are (%s)," % ( command , format , "," . join ( programs ) ) ) | Find suitable archive program for given format and mode . |
24,033 | def list_formats ( ) : print ( "Archive programs of" , App ) print ( "Archive programs are searched in the following directories:" ) print ( util . system_search_path ( ) ) print ( ) for format in ArchiveFormats : print ( format , "files:" ) for command in ArchiveCommands : programs = ArchivePrograms [ format ] if command not in programs and None not in programs : print ( " %8s: - (not supported)" % command ) continue try : program = find_archive_program ( format , command ) print ( " %8s: %s" % ( command , program ) , end = ' ' ) if format == 'tar' : encs = [ x for x in ArchiveCompressions if util . find_program ( x ) ] if encs : print ( "(supported compressions: %s)" % ", " . join ( encs ) , end = ' ' ) elif format == '7z' : if util . p7zip_supports_rar ( ) : print ( "(rar archives supported)" , end = ' ' ) else : print ( "(rar archives not supported)" , end = ' ' ) print ( ) except util . PatoolError : handlers = programs . get ( None , programs . get ( command ) ) print ( " %8s: - (no program found; install %s)" % ( command , util . strlist_with_or ( handlers ) ) ) | Print information about available archive formats to stdout . |
24,034 | def check_program_compression ( archive , command , program , compression ) : program = os . path . basename ( program ) if compression : if not program_supports_compression ( program , compression ) : if command == 'create' : comp_command = command else : comp_command = 'extract' comp_prog = find_archive_program ( compression , comp_command ) if not comp_prog : msg = "cannot %s archive `%s': compression `%s' not supported" raise util . PatoolError ( msg % ( command , archive , compression ) ) | Check if a program supports the given compression . |
24,035 | def run_archive_cmdlist ( archive_cmdlist , verbosity = 0 ) : if isinstance ( archive_cmdlist , tuple ) : cmdlist , runkwargs = archive_cmdlist else : cmdlist , runkwargs = archive_cmdlist , { } return util . run_checked ( cmdlist , verbosity = verbosity , ** runkwargs ) | Run archive command . |
24,036 | def make_file_readable ( filename ) : if not os . path . islink ( filename ) : util . set_mode ( filename , stat . S_IRUSR ) | Make file user readable if it is not a link . |
24,037 | def make_user_readable ( directory ) : for root , dirs , files in os . walk ( directory , onerror = util . log_error ) : for filename in files : make_file_readable ( os . path . join ( root , filename ) ) for dirname in dirs : make_dir_readable ( os . path . join ( root , dirname ) ) | Make all files in given directory user readable . Also recurse into subdirectories . |
24,038 | def cleanup_outdir ( outdir , archive ) : make_user_readable ( outdir ) ( success , msg ) = move_outdir_orphan ( outdir ) if success : return msg , "`%s'" % msg outdir2 = util . get_single_outfile ( "" , archive ) os . rename ( outdir , outdir2 ) return outdir2 , "`%s' (%s)" % ( outdir2 , msg ) | Cleanup outdir after extraction and return target file name and result string . |
24,039 | def _extract_archive ( archive , verbosity = 0 , interactive = True , outdir = None , program = None , format = None , compression = None ) : if format is None : format , compression = get_archive_format ( archive ) check_archive_format ( format , compression ) program = find_archive_program ( format , 'extract' , program = program ) check_program_compression ( archive , 'extract' , program , compression ) get_archive_cmdlist = get_archive_cmdlist_func ( program , 'extract' , format ) if outdir is None : outdir = util . tmpdir ( dir = "." ) do_cleanup_outdir = True else : do_cleanup_outdir = False try : cmdlist = get_archive_cmdlist ( archive , compression , program , verbosity , interactive , outdir ) if cmdlist : run_archive_cmdlist ( cmdlist , verbosity = verbosity ) if do_cleanup_outdir : target , msg = cleanup_outdir ( outdir , archive ) else : target , msg = outdir , "`%s'" % outdir if verbosity >= 0 : util . log_info ( "... %s extracted to %s." % ( archive , msg ) ) return target finally : if do_cleanup_outdir : try : os . rmdir ( outdir ) except OSError : pass | Extract an archive . |
24,040 | def _create_archive ( archive , filenames , verbosity = 0 , interactive = True , program = None , format = None , compression = None ) : if format is None : format , compression = get_archive_format ( archive ) check_archive_format ( format , compression ) program = find_archive_program ( format , 'create' , program = program ) check_program_compression ( archive , 'create' , program , compression ) get_archive_cmdlist = get_archive_cmdlist_func ( program , 'create' , format ) origarchive = None if os . path . basename ( program ) == 'arc' and ".arc" in archive and not archive . endswith ( ".arc" ) : origarchive = archive archive = util . tmpfile ( dir = os . path . dirname ( archive ) , suffix = ".arc" ) cmdlist = get_archive_cmdlist ( archive , compression , program , verbosity , interactive , filenames ) if cmdlist : run_archive_cmdlist ( cmdlist , verbosity = verbosity ) if origarchive : shutil . move ( archive , origarchive ) | Create an archive . |
24,041 | def _handle_archive ( archive , command , verbosity = 0 , interactive = True , program = None , format = None , compression = None ) : if format is None : format , compression = get_archive_format ( archive ) check_archive_format ( format , compression ) if command not in ( 'list' , 'test' ) : raise util . PatoolError ( "invalid archive command `%s'" % command ) program = find_archive_program ( format , command , program = program ) check_program_compression ( archive , command , program , compression ) get_archive_cmdlist = get_archive_cmdlist_func ( program , command , format ) cmdlist = get_archive_cmdlist ( archive , compression , program , verbosity , interactive ) if cmdlist : run_archive_cmdlist ( cmdlist , verbosity = verbosity ) | Test and list archives . |
24,042 | def get_archive_cmdlist_func ( program , command , format ) : key = util . stripext ( os . path . basename ( program ) . lower ( ) ) modulename = ".programs." + ProgramModules . get ( key , key ) try : module = importlib . import_module ( modulename , __name__ ) except ImportError as msg : raise util . PatoolError ( msg ) try : return getattr ( module , '%s_%s' % ( command , format ) ) except AttributeError as msg : raise util . PatoolError ( msg ) | Get the Python function that executes the given program . |
24,043 | def _diff_archives ( archive1 , archive2 , verbosity = 0 , interactive = True ) : if util . is_same_file ( archive1 , archive2 ) : return 0 diff = util . find_program ( "diff" ) if not diff : msg = "The diff(1) program is required for showing archive differences, please install it." raise util . PatoolError ( msg ) tmpdir1 = util . tmpdir ( ) try : path1 = _extract_archive ( archive1 , outdir = tmpdir1 , verbosity = - 1 ) tmpdir2 = util . tmpdir ( ) try : path2 = _extract_archive ( archive2 , outdir = tmpdir2 , verbosity = - 1 ) return util . run_checked ( [ diff , "-urN" , path1 , path2 ] , verbosity = 1 , ret_ok = ( 0 , 1 ) ) finally : shutil . rmtree ( tmpdir2 , onerror = rmtree_log_error ) finally : shutil . rmtree ( tmpdir1 , onerror = rmtree_log_error ) | Show differences between two archives . |
24,044 | def _search_archive ( pattern , archive , verbosity = 0 , interactive = True ) : grep = util . find_program ( "grep" ) if not grep : msg = "The grep(1) program is required for searching archive contents, please install it." raise util . PatoolError ( msg ) tmpdir = util . tmpdir ( ) try : path = _extract_archive ( archive , outdir = tmpdir , verbosity = - 1 ) return util . run_checked ( [ grep , "-r" , "-e" , pattern , "." ] , ret_ok = ( 0 , 1 ) , verbosity = 1 , cwd = path ) finally : shutil . rmtree ( tmpdir , onerror = rmtree_log_error ) | Search for given pattern in an archive . |
24,045 | def _repack_archive ( archive1 , archive2 , verbosity = 0 , interactive = True ) : format1 , compression1 = get_archive_format ( archive1 ) format2 , compression2 = get_archive_format ( archive2 ) if format1 == format2 and compression1 == compression2 : util . link_or_copy ( archive1 , archive2 , verbosity = verbosity ) return tmpdir = util . tmpdir ( ) try : kwargs = dict ( verbosity = verbosity , outdir = tmpdir ) same_format = ( format1 == format2 and compression1 and compression2 ) if same_format : kwargs [ 'format' ] = compression1 path = _extract_archive ( archive1 , ** kwargs ) archive = os . path . abspath ( archive2 ) files = tuple ( os . listdir ( path ) ) olddir = os . getcwd ( ) os . chdir ( path ) try : kwargs = dict ( verbosity = verbosity , interactive = interactive ) if same_format : kwargs [ 'format' ] = compression2 _create_archive ( archive , files , ** kwargs ) finally : os . chdir ( olddir ) finally : shutil . rmtree ( tmpdir , onerror = rmtree_log_error ) | Repackage an archive to a different format . |
24,046 | def _recompress_archive ( archive , verbosity = 0 , interactive = True ) : format , compression = get_archive_format ( archive ) if compression : format = compression tmpdir = util . tmpdir ( ) tmpdir2 = util . tmpdir ( ) base , ext = os . path . splitext ( os . path . basename ( archive ) ) archive2 = util . get_single_outfile ( tmpdir2 , base , extension = ext ) try : kwargs = dict ( verbosity = verbosity , format = format , outdir = tmpdir ) path = _extract_archive ( archive , ** kwargs ) olddir = os . getcwd ( ) os . chdir ( path ) try : kwargs = dict ( verbosity = verbosity , interactive = interactive , format = format ) files = tuple ( os . listdir ( path ) ) _create_archive ( archive2 , files , ** kwargs ) finally : os . chdir ( olddir ) filesize = util . get_filesize ( archive ) filesize2 = util . get_filesize ( archive2 ) if filesize2 < filesize : os . remove ( archive ) shutil . move ( archive2 , archive ) diffsize = filesize - filesize2 return "... recompressed file is now %s smaller." % util . strsize ( diffsize ) finally : shutil . rmtree ( tmpdir , onerror = rmtree_log_error ) shutil . rmtree ( tmpdir2 , onerror = rmtree_log_error ) return "... recompressed file is not smaller, leaving archive as is." | Try to recompress an archive to smaller size . |
24,047 | def extract_archive ( archive , verbosity = 0 , outdir = None , program = None , interactive = True ) : util . check_existing_filename ( archive ) if verbosity >= 0 : util . log_info ( "Extracting %s ..." % archive ) return _extract_archive ( archive , verbosity = verbosity , interactive = interactive , outdir = outdir , program = program ) | Extract given archive . |
24,048 | def list_archive ( archive , verbosity = 1 , program = None , interactive = True ) : util . check_existing_filename ( archive ) if verbosity >= 0 : util . log_info ( "Listing %s ..." % archive ) return _handle_archive ( archive , 'list' , verbosity = verbosity , interactive = interactive , program = program ) | List given archive . |
24,049 | def create_archive ( archive , filenames , verbosity = 0 , program = None , interactive = True ) : util . check_new_filename ( archive ) util . check_archive_filelist ( filenames ) if verbosity >= 0 : util . log_info ( "Creating %s ..." % archive ) res = _create_archive ( archive , filenames , verbosity = verbosity , interactive = interactive , program = program ) if verbosity >= 0 : util . log_info ( "... %s created." % archive ) return res | Create given archive with given files . |
24,050 | def diff_archives ( archive1 , archive2 , verbosity = 0 , interactive = True ) : util . check_existing_filename ( archive1 ) util . check_existing_filename ( archive2 ) if verbosity >= 0 : util . log_info ( "Comparing %s with %s ..." % ( archive1 , archive2 ) ) res = _diff_archives ( archive1 , archive2 , verbosity = verbosity , interactive = interactive ) if res == 0 and verbosity >= 0 : util . log_info ( "... no differences found." ) | Print differences between two archives . |
24,051 | def search_archive ( pattern , archive , verbosity = 0 , interactive = True ) : if not pattern : raise util . PatoolError ( "empty search pattern" ) util . check_existing_filename ( archive ) if verbosity >= 0 : util . log_info ( "Searching %r in %s ..." % ( pattern , archive ) ) res = _search_archive ( pattern , archive , verbosity = verbosity , interactive = interactive ) if res == 1 and verbosity >= 0 : util . log_info ( "... %r not found" % pattern ) return res | Search pattern in archive members . |
24,052 | def recompress_archive ( archive , verbosity = 0 , interactive = True ) : util . check_existing_filename ( archive ) util . check_writable_filename ( archive ) if verbosity >= 0 : util . log_info ( "Recompressing %s ..." % ( archive , ) ) res = _recompress_archive ( archive , verbosity = verbosity , interactive = interactive ) if res and verbosity >= 0 : util . log_info ( res ) return 0 | Recompress an archive to hopefully smaller size . |
24,053 | def init_mimedb ( ) : global mimedb try : mimedb = mimetypes . MimeTypes ( strict = False ) except Exception as msg : log_error ( "could not initialize MIME database: %s" % msg ) return add_mimedb_data ( mimedb ) | Initialize the internal MIME database . |
24,054 | def add_mimedb_data ( mimedb ) : mimedb . encodings_map [ '.bz2' ] = 'bzip2' mimedb . encodings_map [ '.lzma' ] = 'lzma' mimedb . encodings_map [ '.xz' ] = 'xz' mimedb . encodings_map [ '.lz' ] = 'lzip' mimedb . suffix_map [ '.tbz2' ] = '.tar.bz2' add_mimetype ( mimedb , 'application/x-lzop' , '.lzo' ) add_mimetype ( mimedb , 'application/x-adf' , '.adf' ) add_mimetype ( mimedb , 'application/x-arj' , '.arj' ) add_mimetype ( mimedb , 'application/x-lzma' , '.lzma' ) add_mimetype ( mimedb , 'application/x-xz' , '.xz' ) add_mimetype ( mimedb , 'application/java-archive' , '.jar' ) add_mimetype ( mimedb , 'application/x-rar' , '.rar' ) add_mimetype ( mimedb , 'application/x-rar' , '.cbr' ) add_mimetype ( mimedb , 'application/x-7z-compressed' , '.7z' ) add_mimetype ( mimedb , 'application/x-7z-compressed' , '.cb7' ) add_mimetype ( mimedb , 'application/x-cab' , '.cab' ) add_mimetype ( mimedb , 'application/x-rpm' , '.rpm' ) add_mimetype ( mimedb , 'application/x-debian-package' , '.deb' ) add_mimetype ( mimedb , 'application/x-ace' , '.ace' ) add_mimetype ( mimedb , 'application/x-ace' , '.cba' ) add_mimetype ( mimedb , 'application/x-archive' , '.a' ) add_mimetype ( mimedb , 'application/x-alzip' , '.alz' ) add_mimetype ( mimedb , 'application/x-arc' , '.arc' ) add_mimetype ( mimedb , 'application/x-lrzip' , '.lrz' ) add_mimetype ( mimedb , 'application/x-lha' , '.lha' ) add_mimetype ( mimedb , 'application/x-lzh' , '.lzh' ) add_mimetype ( mimedb , 'application/x-rzip' , '.rz' ) add_mimetype ( mimedb , 'application/x-zoo' , '.zoo' ) add_mimetype ( mimedb , 'application/x-dms' , '.dms' ) add_mimetype ( mimedb , 'application/x-zip-compressed' , '.crx' ) add_mimetype ( mimedb , 'application/x-shar' , '.shar' ) add_mimetype ( mimedb , 'application/x-tar' , '.cbt' ) add_mimetype ( mimedb , 'application/x-vhd' , '.vhd' ) add_mimetype ( mimedb , 'audio/x-ape' , '.ape' ) add_mimetype ( mimedb , 'audio/x-shn' , '.shn' ) add_mimetype ( mimedb , 'audio/flac' , '.flac' ) add_mimetype ( mimedb , 'application/x-chm' , '.chm' ) add_mimetype ( mimedb , 'application/x-iso9660-image' , '.iso' ) add_mimetype ( mimedb , 'application/zip' , '.cbz' ) add_mimetype ( mimedb , 'application/zip' , '.epub' ) add_mimetype ( mimedb , 'application/zip' , '.apk' ) add_mimetype ( mimedb , 'application/zpaq' , '.zpaq' ) | Add missing encodings and mimetypes to MIME database . |
24,055 | def backtick ( cmd , encoding = 'utf-8' ) : data = subprocess . Popen ( cmd , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] return data . decode ( encoding ) | Return decoded output from command . |
24,056 | def run ( cmd , verbosity = 0 , ** kwargs ) : if verbosity >= 0 : log_info ( "running %s" % " " . join ( map ( shell_quote_nt , cmd ) ) ) if kwargs : if verbosity >= 0 : log_info ( " with %s" % ", " . join ( "%s=%s" % ( k , shell_quote ( str ( v ) ) ) for k , v in kwargs . items ( ) ) ) if kwargs . get ( "shell" ) : cmd = " " . join ( cmd ) if verbosity < 1 : with open ( os . devnull , 'wb' ) as devnull : kwargs [ 'stdout' ] = devnull res = subprocess . call ( cmd , ** kwargs ) else : res = subprocess . call ( cmd , ** kwargs ) return res | Run command without error checking . |
24,057 | def run_checked ( cmd , ret_ok = ( 0 , ) , ** kwargs ) : retcode = run ( cmd , ** kwargs ) if retcode not in ret_ok : msg = "Command `%s' returned non-zero exit status %d" % ( cmd , retcode ) raise PatoolError ( msg ) return retcode | Run command and raise PatoolError on error . |
24,058 | def guess_mime_mimedb ( filename ) : mime , encoding = None , None if mimedb is not None : mime , encoding = mimedb . guess_type ( filename , strict = False ) if mime not in ArchiveMimetypes and encoding in ArchiveCompressions : mime = Encoding2Mime [ encoding ] encoding = None return mime , encoding | Guess MIME type from given filename . |
24,059 | def check_existing_filename ( filename , onlyfiles = True ) : if not os . path . exists ( filename ) : raise PatoolError ( "file `%s' was not found" % filename ) if not os . access ( filename , os . R_OK ) : raise PatoolError ( "file `%s' is not readable" % filename ) if onlyfiles and not os . path . isfile ( filename ) : raise PatoolError ( "`%s' is not a file" % filename ) | Ensure that given filename is a valid existing file . |
24,060 | def check_archive_filelist ( filenames ) : if not filenames : raise PatoolError ( "cannot create archive with empty filelist" ) for filename in filenames : check_existing_filename ( filename , onlyfiles = False ) | Check that file list is not empty and contains only existing files . |
24,061 | def set_mode ( filename , flags ) : try : mode = os . lstat ( filename ) . st_mode except OSError : return if not ( mode & flags ) : try : os . chmod ( filename , flags | mode ) except OSError as msg : log_error ( "could not set mode flags for `%s': %s" % ( filename , msg ) ) | Set mode flags for given filename if not already set . |
24,062 | def tmpfile ( dir = None , prefix = "temp" , suffix = None ) : return tempfile . mkstemp ( suffix = suffix , prefix = prefix , dir = dir ) [ 1 ] | Return a temporary file . |
24,063 | def get_single_outfile ( directory , archive , extension = "" ) : outfile = os . path . join ( directory , stripext ( archive ) ) if os . path . exists ( outfile + extension ) : i = 1 newfile = "%s%d" % ( outfile , i ) while os . path . exists ( newfile + extension ) : newfile = "%s%d" % ( outfile , i ) i += 1 outfile = newfile return outfile + extension | Get output filename if archive is in a single file format like gzip . |
24,064 | def print_env_info ( key , out = sys . stderr ) : value = os . getenv ( key ) if value is not None : print ( key , "=" , repr ( value ) , file = out ) | If given environment key is defined print it out . |
24,065 | def p7zip_supports_rar ( ) : if os . name == 'nt' : return True codecname = 'p7zip/Codecs/Rar29.so' for libdir in ( '/usr/lib' , '/usr/local/lib' , '/usr/lib64' , '/usr/local/lib64' , '/usr/lib/i386-linux-gnu' , '/usr/lib/x86_64-linux-gnu' ) : fname = os . path . join ( libdir , codecname ) if os . path . exists ( fname ) : return True return False | Determine if the RAR codec is installed for 7z program . |
24,066 | def find_program ( program ) : if os . name == 'nt' : path = os . environ [ 'PATH' ] path = append_to_path ( path , get_nt_7z_dir ( ) ) path = append_to_path ( path , get_nt_mac_dir ( ) ) path = append_to_path ( path , get_nt_winrar_dir ( ) ) else : path = None return which ( program , path = path ) | Look for program in environment PATH variable . |
24,067 | def append_to_path ( path , directory ) : if not os . path . isdir ( directory ) or directory in path : return path if not path . endswith ( os . pathsep ) : path += os . pathsep return path + directory | Add a directory to the PATH environment variable if it is a valid directory . |
24,068 | def get_nt_7z_dir ( ) : try : import _winreg as winreg except ImportError : import winreg try : key = winreg . OpenKey ( winreg . HKEY_LOCAL_MACHINE , r"SOFTWARE\7-Zip" ) try : return winreg . QueryValueEx ( key , "Path" ) [ 0 ] finally : winreg . CloseKey ( key ) except WindowsError : return "" | Return 7 - Zip directory from registry or an empty string . |
24,069 | def is_same_file ( filename1 , filename2 ) : if filename1 == filename2 : return True if os . name == 'posix' : return os . path . samefile ( filename1 , filename2 ) return is_same_filename ( filename1 , filename2 ) | Check if filename1 and filename2 point to the same file object . There can be false negatives ie . the result is False but it is the same file anyway . Reason is that network filesystems can create different paths to the same physical file . |
24,070 | def is_same_filename ( filename1 , filename2 ) : return os . path . realpath ( filename1 ) == os . path . realpath ( filename2 ) | Check if filename1 and filename2 are the same filename . |
24,071 | def link_or_copy ( src , dst , verbosity = 0 ) : if verbosity > 0 : log_info ( "Copying %s -> %s" % ( src , dst ) ) try : os . link ( src , dst ) except ( AttributeError , OSError ) : try : shutil . copy ( src , dst ) except OSError as msg : raise PatoolError ( msg ) | Try to make a hard link from src to dst and if that fails copy the file . Hard links save some disk space and linking should fail fast since no copying is involved . |
24,072 | def extract_flac ( archive , compression , cmd , verbosity , interactive , outdir ) : outfile = util . get_single_outfile ( outdir , archive , extension = ".wav" ) cmdlist = [ cmd , '--decode' , archive , '--output-name' , outfile ] return cmdlist | Decompress a FLAC archive to a WAV file . |
24,073 | def create_flac ( archive , compression , cmd , verbosity , interactive , filenames ) : cmdlist = [ cmd , filenames [ 0 ] , '--best' , '--output-name' , archive ] return cmdlist | Compress a WAV file to a FLAC archive . |
24,074 | def extract_rar ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , 'x' ] if not interactive : cmdlist . extend ( [ '-p-' , '-y' ] ) cmdlist . extend ( [ '--' , os . path . abspath ( archive ) ] ) return ( cmdlist , { 'cwd' : outdir } ) | Extract a RAR archive . |
24,075 | def extract_cpio ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ util . shell_quote ( cmd ) , '--extract' , '--make-directories' , '--preserve-modification-time' ] if sys . platform . startswith ( 'linux' ) and not cmd . endswith ( 'bsdcpio' ) : cmdlist . extend ( [ '--no-absolute-filenames' , '--force-local' , '--nonmatching' , r'"*\.\.*"' ] ) if verbosity > 1 : cmdlist . append ( '-v' ) cmdlist . extend ( [ '<' , util . shell_quote ( os . path . abspath ( archive ) ) ] ) return ( cmdlist , { 'cwd' : outdir , 'shell' : True } ) | Extract a CPIO archive . |
24,076 | def create_cpio ( archive , compression , cmd , verbosity , interactive , filenames ) : cmdlist = [ util . shell_quote ( cmd ) , '--create' ] if verbosity > 1 : cmdlist . append ( '-v' ) if len ( filenames ) != 0 : findcmd = [ 'find' ] findcmd . extend ( [ util . shell_quote ( x ) for x in filenames ] ) findcmd . extend ( [ '-print0' , '|' ] ) cmdlist [ 0 : 0 ] = findcmd cmdlist . append ( '-0' ) cmdlist . extend ( [ ">" , util . shell_quote ( archive ) ] ) return ( cmdlist , { 'shell' : True } ) | Create a CPIO archive . |
24,077 | def extract_arc ( archive , compression , cmd , verbosity , interactive , outdir ) : cmdlist = [ cmd , 'x' , os . path . abspath ( archive ) ] return ( cmdlist , { 'cwd' : outdir } ) | Extract a ARC archive . |
24,078 | def list_arc ( archive , compression , cmd , verbosity , interactive ) : cmdlist = [ cmd ] if verbosity > 1 : cmdlist . append ( 'v' ) else : cmdlist . append ( 'l' ) cmdlist . append ( archive ) return cmdlist | List a ARC archive . |
24,079 | def extract_gzip ( archive , compression , cmd , verbosity , interactive , outdir ) : targetname = util . get_single_outfile ( outdir , archive ) try : with gzip . GzipFile ( archive ) as gzipfile : with open ( targetname , 'wb' ) as targetfile : data = gzipfile . read ( READ_SIZE_BYTES ) while data : targetfile . write ( data ) data = gzipfile . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error extracting %s to %s: %s" % ( archive , targetname , err ) raise util . PatoolError ( msg ) return None | Extract a GZIP archive with the gzip Python module . |
24,080 | def create_gzip ( archive , compression , cmd , verbosity , interactive , filenames ) : if len ( filenames ) > 1 : raise util . PatoolError ( 'multi-file compression not supported in Python gzip' ) try : with gzip . GzipFile ( archive , 'wb' ) as gzipfile : filename = filenames [ 0 ] with open ( filename , 'rb' ) as srcfile : data = srcfile . read ( READ_SIZE_BYTES ) while data : gzipfile . write ( data ) data = srcfile . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error creating %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | Create a GZIP archive with the gzip Python module . |
24,081 | def _extract ( archive , compression , cmd , format , verbosity , outdir ) : targetname = util . get_single_outfile ( outdir , archive ) try : with lzma . LZMAFile ( archive , ** _get_lzma_options ( format ) ) as lzmafile : with open ( targetname , 'wb' ) as targetfile : data = lzmafile . read ( READ_SIZE_BYTES ) while data : targetfile . write ( data ) data = lzmafile . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error extracting %s to %s: %s" % ( archive , targetname , err ) raise util . PatoolError ( msg ) return None | Extract an LZMA or XZ archive with the lzma Python module . |
24,082 | def extract_lzma ( archive , compression , cmd , verbosity , interactive , outdir ) : return _extract ( archive , compression , cmd , 'alone' , verbosity , outdir ) | Extract an LZMA archive with the lzma Python module . |
24,083 | def extract_xz ( archive , compression , cmd , verbosity , interactive , outdir ) : return _extract ( archive , compression , cmd , 'xz' , verbosity , outdir ) | Extract an XZ archive with the lzma Python module . |
24,084 | def _create ( archive , compression , cmd , format , verbosity , filenames ) : if len ( filenames ) > 1 : raise util . PatoolError ( 'multi-file compression not supported in Python lzma' ) try : with lzma . LZMAFile ( archive , mode = 'wb' , ** _get_lzma_options ( format , preset = 9 ) ) as lzmafile : filename = filenames [ 0 ] with open ( filename , 'rb' ) as srcfile : data = srcfile . read ( READ_SIZE_BYTES ) while data : lzmafile . write ( data ) data = srcfile . read ( READ_SIZE_BYTES ) except Exception as err : msg = "error creating %s: %s" % ( archive , err ) raise util . PatoolError ( msg ) return None | Create an LZMA or XZ archive with the lzma Python module . |
24,085 | def create_lzma ( archive , compression , cmd , verbosity , interactive , filenames ) : return _create ( archive , compression , cmd , 'alone' , verbosity , filenames ) | Create an LZMA archive with the lzma Python module . |
24,086 | def create_xz ( archive , compression , cmd , verbosity , interactive , filenames ) : return _create ( archive , compression , cmd , 'xz' , verbosity , filenames ) | Create an XZ archive with the lzma Python module . |
24,087 | def ssl_required ( allow_non_ssl = False ) : def wrapper ( view_func ) : def _checkssl ( request , * args , ** kwargs ) : if hasattr ( settings , 'SSL_ENABLED' ) and settings . SSL_ENABLED and not request . is_secure ( ) and not allow_non_ssl : return HttpResponseRedirect ( request . build_absolute_uri ( ) . replace ( 'http://' , 'https://' ) ) return view_func ( request , * args , ** kwargs ) return _checkssl return wrapper | Views decorated with this will always get redirected to https except when allow_non_ssl is set to true . |
24,088 | def anonymous_required ( view , redirect_to = None ) : if redirect_to is None : redirect_to = settings . LOGIN_REDIRECT_URL @ wraps ( view ) def wrapper ( request , * a , ** k ) : if request . user and request . user . is_authenticated ( ) : return HttpResponseRedirect ( redirect_to ) return view ( request , * a , ** k ) return wrapper | Only allow if user is NOT authenticated . |
24,089 | def generic_var ( self , key , value = None ) : return self . _get_or_set ( '{0}{1}' . format ( self . _GENERIC_VAR_KEY_PREFIX , key ) , value ) | Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX . |
24,090 | def authenticate ( self , username = None , password = None , ** kwargs ) : try : user = User . objects . get ( email = username ) if user . check_password ( password ) : return user except ( User . DoesNotExist , User . MultipleObjectsReturned ) : logging . warning ( 'Unsuccessful login attempt using username/email: {0}' . format ( username ) ) return None | username being passed is really email address and being compared to as such . |
24,091 | def add_arguments ( self , parser ) : parser . add_argument ( '--length' , default = self . length , type = int , help = _ ( 'SECRET_KEY length default=%d' % self . length ) ) parser . add_argument ( '--alphabet' , default = self . allowed_chars , type = str , help = _ ( 'alphabet to use default=%s' % self . allowed_chars ) ) | Define optional arguments with default values |
24,092 | def send_mail ( subject , message , from_email , recipient_emails , files = None , html = False , reply_to = None , bcc = None , cc = None , files_manually = None ) : import django . core . mail try : logging . debug ( 'Sending mail to: {0}' . format ( ', ' . join ( r for r in recipient_emails ) ) ) logging . debug ( 'Message: {0}' . format ( message ) ) email = django . core . mail . EmailMessage ( subject , message , from_email , recipient_emails , bcc , cc = cc ) if html : email . content_subtype = "html" if files : for file in files : email . attach_file ( file ) if files_manually : for filename , content , mimetype in files_manually : email . attach ( filename , content , mimetype ) if reply_to : email . extra_headers = { 'Reply-To' : reply_to } email . send ( ) except Exception as e : logging . error ( 'Error sending message [{0}] from {1} to {2} {3}' . format ( subject , from_email , recipient_emails , e ) ) | Sends email with advanced optional parameters |
24,093 | def skip_redundant ( iterable , skipset = None ) : if skipset is None : skipset = set ( ) for item in iterable : if item not in skipset : skipset . add ( item ) yield item | Redundant items are repeated items or items in the original skipset . |
24,094 | def get_noconflict_metaclass ( bases , left_metas , right_metas ) : metas = left_metas + tuple ( map ( type , bases ) ) + right_metas needed_metas = remove_redundant ( metas ) if needed_metas in memoized_metaclasses_map : return memoized_metaclasses_map [ needed_metas ] elif not needed_metas : meta = type elif len ( needed_metas ) == 1 : meta = needed_metas [ 0 ] elif needed_metas == bases : raise TypeError ( "Incompatible root metatypes" , needed_metas ) else : metaname = '_' + '' . join ( [ m . __name__ for m in needed_metas ] ) meta = classmaker ( ) ( metaname , needed_metas , { } ) memoized_metaclasses_map [ needed_metas ] = meta return meta | Not intended to be used outside of this module unless you know what you are doing . |
24,095 | def on_api_error_14 ( self , request ) : request . method_params [ 'captcha_key' ] = self . get_captcha_key ( request ) request . method_params [ 'captcha_sid' ] = request . api_error . captcha_sid return self . send ( request ) | 14 . Captcha needed |
24,096 | def on_api_error_15 ( self , request ) : logger . error ( 'Authorization failed. Access token will be dropped' ) self . access_token = self . get_access_token ( ) return self . send ( request ) | 15 . Access denied - due to scope |
24,097 | def get_message ( self ) : try : m = self . get_from_backend ( ) if m and m [ "type" ] not in SKIP_TYPES : return self . decrypt ( m [ "data" ] ) except AttributeError : raise Exception ( "Tried to call get message without having subscribed first!" ) except ( KeyboardInterrupt , SystemExit ) : pass except : logging . critical ( "Error in watching pubsub get message: \n%s" % traceback . format_exc ( ) ) return None | Gets the latest object from the backend and handles unpickling and validation . |
24,098 | def from_edgerc ( rcinput , section = 'default' ) : from . edgerc import EdgeRc if isinstance ( rcinput , EdgeRc ) : rc = rcinput else : rc = EdgeRc ( rcinput ) return EdgeGridAuth ( client_token = rc . get ( section , 'client_token' ) , client_secret = rc . get ( section , 'client_secret' ) , access_token = rc . get ( section , 'access_token' ) , headers_to_sign = rc . getlist ( section , 'headers_to_sign' ) , max_body = rc . getint ( section , 'max_body' ) ) | Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file . |
24,099 | def getlist ( self , section , option ) : value = self . get ( section , option ) if value : return value . split ( ',' ) else : return None | returns the named option as a list splitting the original value by |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.