text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_create_ticket(self, token, id, scopes, **kwargs): """ Create a ticket form permission to resource. https://www.keycloak.org/docs/latest/authorizatio...
data = dict(resource_id=id, resource_scopes=scopes, **kwargs) return self._realm.client.post( self.well_known['permission_endpoint'], data=self._dumps([data]), headers=self.get_headers(token) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_associate_permission(self, token, id, name, scopes, **kwargs): """ Associates a permission with a Resource. https://www.keycloak.org/docs/latest/aut...
return self._realm.client.post( '{}/{}'.format(self.well_known['policy_endpoint'], id), data=self._get_data(name=name, scopes=scopes, **kwargs), headers=self.get_headers(token) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_update(self, token, id, **kwargs): """ To update an existing permission. https://www.keycloak.org/docs/latest/authorization_services/index.html#_s...
return self._realm.client.put( '{}/{}'.format(self.well_known['policy_endpoint'], id), data=self._dumps(kwargs), headers=self.get_headers(token) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_delete(self, token, id): """ Removing a Permission. https://www.keycloak.org/docs/latest/authorization_services/index.html#removing-a-permission :...
return self._realm.client.delete( '{}/{}'.format(self.well_known['policy_endpoint'], id), headers=self.get_headers(token) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_token(cls, token): """ Permission information is encoded in an authorization token. """
missing_padding = len(token) % 4 if missing_padding != 0: token += '=' * (4 - missing_padding) return json.loads(base64.b64decode(token).decode('utf-8'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_permissions(self, token, resource_scopes_tuples=None, submit_request=False, ticket=None): """ Request permissions for user from keycloak server. https://...
headers = { "Authorization": "Bearer %s" % token, 'Content-type': 'application/x-www-form-urlencoded', } data = [ ('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket'), ('audience', self._client_id), ('response_include_resourc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_permission(self, token, resource, scope, submit_request=False): """ Evalutes if user has permission for scope on resource. :param str token: client acce...
return self.eval_permissions( token=token, resource_scopes_tuples=[(resource, scope)], submit_request=submit_request )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_permissions(self, token, resource_scopes_tuples=None, submit_request=False): """ Evaluates if user has permission for all the resource scope combination...
permissions = self.get_permissions( token=token, resource_scopes_tuples=resource_scopes_tuples, submit_request=submit_request ) res = [] for permission in permissions.get('permissions', []): for scope in permission.get('scopes', []): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(self, refresh_token): """ The logout endpoint logs out the authenticated user. :param str refresh_token: """
return self._realm.client.post(self.get_url('end_session_endpoint'), data={ 'refresh_token': refresh_token, 'client_id': self._client_id, 'clie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def userinfo(self, token): """ The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns Claims about the authenticated End-User. To obtain the reque...
url = self.well_known['userinfo_endpoint'] return self._realm.client.get(url, headers={ "Authorization": "Bearer {}".format( token ) }...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorization_url(self, **kwargs): """ Get authorization URL to redirect the resource owner to. https://tools.ietf.org/html/rfc6749#section-4.1.1 :param str ...
payload = {'response_type': 'code', 'client_id': self._client_id} for key in kwargs.keys(): # Add items in a sorted way for unittest purposes. payload[key] = kwargs[key] payload = sorted(payload.items(), key=lambda val: val[0]) params = urlencode(payload) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorization_code(self, code, redirect_uri): """ Retrieve access token by `authorization_code` grant. https://tools.ietf.org/html/rfc6749#section-4.1.3 :par...
return self._token_request(grant_type='authorization_code', code=code, redirect_uri=redirect_uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password_credentials(self, username, password, **kwargs): """ Retrieve access token by 'password credentials' grant. https://tools.ietf.org/html/rfc6749#sect...
return self._token_request(grant_type='password', username=username, password=password, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_token(self, refresh_token, **kwargs): """ Refresh an access token https://tools.ietf.org/html/rfc6749#section-6 :param str refresh_token: :param str ...
return self._token_request(grant_type='refresh_token', refresh_token=refresh_token, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _token_request(self, grant_type, **kwargs): """ Do the actual call to the token end-point. :param grant_type: :param kwargs: See invoking methods. :return: "...
payload = { 'grant_type': grant_type, 'client_id': self._client_id, 'client_secret': self._client_secret } payload.update(**kwargs) return self._realm.client.post(self.get_url('token_endpoint'), data=payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, name, **kwargs): """ Create new role http://www.keycloak.org/docs-api/3.4/rest-api/index.html #_roles_resource :param str name: Name for the rol...
payload = OrderedDict(name=name) for key in ROLE_KWARGS: if key in kwargs: payload[to_camel_case(key)] = kwargs[key] return self._client.post( url=self._client.get_full_url( self.get_path('collection', realm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, name, **kwargs): """ Update existing role. http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_roles_resource :param str name: Name for th...
payload = OrderedDict(name=name) for key in ROLE_KWARGS: if key in kwargs: payload[to_camel_case(key)] = kwargs[key] return self._client.put( url=self._client.get_full_url( self.get_path('single', realm=self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_rpm (archive, compression, cmd, verbosity, interactive, outdir): """Extract a RPM archive."""
# also check cpio cpio = util.find_program("cpio") if not cpio: raise util.PatoolError("cpio(1) is required for rpm2cpio extraction; please install it") path = util.shell_quote(os.path.abspath(archive)) cmdlist = [util.shell_quote(cmd), path, "|", util.shell_quote(cpio), '--extract'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_tar (archive, compression, cmd, verbosity, interactive): """List a TAR archive with the tarfile Python module."""
try: with tarfile.open(archive) as tfile: tfile.list(verbose=verbosity>1) except Exception as err: msg = "error listing %s: %s" % (archive, err) raise util.PatoolError(msg) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_tar (archive, compression, cmd, verbosity, interactive, outdir): """Extract a TAR archive with the tarfile Python module."""
try: with tarfile.open(archive) as tfile: tfile.extractall(path=outdir) except Exception as err: msg = "error extracting %s: %s" % (archive, err) raise util.PatoolError(msg) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_tar (archive, compression, cmd, verbosity, interactive, filenames): """Create a TAR archive with the tarfile Python module."""
mode = get_tar_mode(compression) try: with tarfile.open(archive, mode) as tfile: for filename in filenames: tfile.add(filename) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tar_mode (compression): """Determine tarfile open mode according to the given compression."""
if compression == 'gzip': return 'w:gz' if compression == 'bzip2': return 'w:bz2' if compression == 'lzma' and py_lzma: return 'w:xz' if compression: msg = 'pytarfile does not support %s for tar compression' raise util.PatoolError(msg % compression) # no comp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_arj (archive, compression, cmd, verbosity, interactive, outdir): """Extract an ARJ archive."""
cmdlist = [cmd, 'x', '-r'] if not interactive: cmdlist.append('-y') cmdlist.extend([archive, outdir]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_arj (archive, compression, cmd, verbosity, interactive): """List an ARJ archive."""
cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') if not interactive: cmdlist.append('-y') cmdlist.extend(['-r', archive]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_arj (archive, compression, cmd, verbosity, interactive, filenames): """Create an ARJ archive."""
cmdlist = [cmd, 'a', '-r'] if not interactive: cmdlist.append('-y') cmdlist.append(archive) cmdlist.extend(filenames) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_zpaq(archive, compression, cmd, verbosity, interactive, filenames): """Create a ZPAQ archive."""
cmdlist = [cmd, 'a', archive] cmdlist.extend(filenames) cmdlist.extend(['-method', '4']) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a ALZIP archive."""
return [cmd, '-d', outdir, archive]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_tar (archive, compression, cmd, verbosity, interactive, outdir): """Extract a TAR archive."""
cmdlist = [cmd, '--extract'] add_tar_opts(cmdlist, compression, verbosity) cmdlist.extend(["--file", archive, '--directory', outdir]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_tar_opts (cmdlist, compression, verbosity): """Add tar options to cmdlist."""
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('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_zip(archive, compression, cmd, verbosity, interactive): """List member of a ZIP archive with the zipfile Python module."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_zip(archive, compression, cmd, verbosity, interactive, outdir): """Extract a ZIP archive with the zipfile Python module."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_zip(archive, compression, cmd, verbosity, interactive, filenames): """Create a ZIP archive with the zipfile Python module."""
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 creatin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_directory (zfile, directory): """Write recursively all directories and filenames to zipfile instance."""
for dirpath, dirnames, filenames in os.walk(directory): zfile.write(dirpath) for filename in filenames: zfile.write(os.path.join(dirpath, filename))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_shn (archive, compression, cmd, verbosity, interactive, outdir): """Decompress a SHN archive to a WAV file."""
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})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_shn (archive, compression, cmd, verbosity, interactive, filenames): """Compress a WAV file to a SHN archive."""
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})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_dms (archive, compression, cmd, verbosity, interactive, outdir): """Extract a DMS archive."""
check_archive_ext(archive) cmdlist = [cmd, '-d', outdir] if verbosity > 1: cmdlist.append('-v') cmdlist.extend(['u', archive]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_dms (archive, compression, cmd, verbosity, interactive): """List a DMS archive."""
check_archive_ext(archive) return [cmd, 'v', archive]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_xz (archive, compression, cmd, verbosity, interactive): """List a XZ archive."""
cmdlist = [cmd] cmdlist.append('-l') if verbosity > 1: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir): """Extract an LZMA archive."""
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})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_ace (archive, compression, cmd, verbosity, interactive, outdir): """Extract an ACE archive."""
cmdlist = [cmd, 'x'] if not outdir.endswith('/'): outdir += '/' cmdlist.extend([archive, outdir]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_ace (archive, compression, cmd, verbosity, interactive): """List an ACE archive."""
cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_bzip2 (archive, compression, cmd, verbosity, interactive, outdir): """Extract a BZIP2 archive with the bz2 Python module."""
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 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames): """Create a BZIP2 archive with the bz2 Python module."""
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir): """Extract a LZH archive."""
opts = 'x' if verbosity > 1: opts += 'v' opts += "w=%s" % outdir return [cmd, opts, archive]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_lzh (archive, compression, cmd, verbosity, interactive): """List a LZH archive."""
cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_ape (archive, compression, cmd, verbosity, interactive, outdir): """Decompress an APE archive to a WAV file."""
outfile = util.get_single_outfile(outdir, archive, extension=".wav") return [cmd, archive, outfile, '-d']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_adf (archive, compression, cmd, verbosity, interactive, outdir): """Extract an ADF archive."""
return [cmd, archive, '-d', outdir]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_lrzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a LRZIP archive."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_bzip2 (archive, compression, cmd, verbosity, interactive): """List a BZIP2 archive."""
return stripext(cmd, archive, verbosity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_ape (archive, compression, cmd, verbosity, interactive): """List an APE archive."""
return stripext(cmd, archive, verbosity, extension=".wav")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stripext (cmd, archive, verbosity, extension=""): """Print the name without suffix."""
if verbosity >= 0: print(util.stripext(archive)+extension) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_ar (archive, compression, cmd, verbosity, interactive, outdir): """Extract a AR archive."""
opts = 'x' if verbosity > 1: opts += 'v' cmdlist = [cmd, opts, os.path.abspath(archive)] return (cmdlist, {'cwd': outdir})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_ar (archive, compression, cmd, verbosity, interactive): """List a AR archive."""
opts = 't' if verbosity > 1: opts += 'v' return [cmd, opts, archive]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_ar (archive, compression, cmd, verbosity, interactive, filenames): """Create a AR archive."""
opts = 'rc' if verbosity > 1: opts += 'v' cmdlist = [cmd, opts, archive] cmdlist.extend(filenames) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_cab (archive, compression, cmd, verbosity, interactive, outdir): """Extract a CAB archive."""
cmdlist = [cmd, '-d', outdir] if verbosity > 0: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_cab (archive, compression, cmd, verbosity, interactive): """List a CAB archive."""
cmdlist = [cmd, '-l'] if verbosity > 0: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k'] if verbosity > 1: cmdlist.append('-v') outfile = util.get_single_outfile(outdir, archive) cmdlist.extend(["-o", outfile, archive]) return cmdlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def program_supports_compression (program, compression): """Decide if the given program supports the compression natively. @return: True iff the program supports...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_archive_format (filename): """Detect filename archive format and optional compression."""
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' (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_archive_format (format, compression): """Make sure format and compression is known."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_archive_program (format, command, program=None): """Find suitable archive program for given format and mode."""
commands = ArchivePrograms[format] programs = [] if program is not None: # try a specific program first programs.append(program) # first try the universal programs with key None for key in (None, command): if key in commands: programs.extend(commands[key]) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_formats (): """Print information about available archive formats to stdout."""
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] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_program_compression(archive, command, program, compression): """Check if a program supports the given compression."""
program = os.path.basename(program) if compression: # check if compression is supported if not program_supports_compression(program, compression): if command == 'create': comp_command = command else: comp_command = 'extract' co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_archive_cmdlist (archive_cmdlist, verbosity=0): """Run archive command."""
# archive_cmdlist is a command list with optional keyword arguments if isinstance(archive_cmdlist, tuple): cmdlist, runkwargs = archive_cmdlist else: cmdlist, runkwargs = archive_cmdlist, {} return util.run_checked(cmdlist, verbosity=verbosity, **runkwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_file_readable (filename): """Make file user readable if it is not a link."""
if not os.path.islink(filename): util.set_mode(filename, stat.S_IRUSR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_user_readable (directory): """Make all files in given directory user readable. Also recurse into subdirectories."""
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_outdir (outdir, archive): """Cleanup outdir after extraction and return target file name and result string."""
make_user_readable(outdir) # move single directory or file in outdir (success, msg) = move_outdir_orphan(outdir) if success: # msg is a single directory or filename return msg, "`%s'" % msg # outdir remains unchanged # rename it to something more user-friendly (basically the arc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_archive(archive, verbosity=0, interactive=True, outdir=None, program=None, format=None, compression=None): """Extract an archive. @return: output di...
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_fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_archive(archive, filenames, verbosity=0, interactive=True, program=None, format=None, compression=None): """Create an archive."""
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_archive(archive, command, verbosity=0, interactive=True, program=None, format=None, compression=None): """Test and list archives."""
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_archive_cmdlist_func (program, command, format): """Get the Python function that executes the given program."""
# get python module for given archive program key = util.stripext(os.path.basename(program).lower()) modulename = ".programs." + ProgramModules.get(key, key) # import the module try: module = importlib.import_module(modulename, __name__) except ImportError as msg: raise util.Pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _diff_archives (archive1, archive2, verbosity=0, interactive=True): """Show differences between two archives. @return 0 if archives are the same, else 1 @rai...
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_arch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _search_archive(pattern, archive, verbosity=0, interactive=True): """Search for given pattern in an archive."""
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repack_archive (archive1, archive2, verbosity=0, interactive=True): """Repackage an archive to a different format."""
format1, compression1 = get_archive_format(archive1) format2, compression2 = get_archive_format(archive2) if format1 == format2 and compression1 == compression2: # same format and compression allows to copy the file util.link_or_copy(archive1, archive2, verbosity=verbosity) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recompress_archive(archive, verbosity=0, interactive=True): """Try to recompress an archive to smaller size."""
format, compression = get_archive_format(archive) if compression: # only recompress the compression itself (eg. for .tar.xz) format = compression tmpdir = util.tmpdir() tmpdir2 = util.tmpdir() base, ext = os.path.splitext(os.path.basename(archive)) archive2 = util.get_single_out...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True): """Extract given archive."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_archive(archive, verbosity=1, program=None, interactive=True): """List given archive."""
# Set default verbosity to 1 since the listing output should be visible. 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_archive(archive, filenames, verbosity=0, program=None, interactive=True): """Create given archive with given files."""
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_archives(archive1, archive2, verbosity=0, interactive=True): """Print differences between two archives."""
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: ut...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_archive(pattern, archive, verbosity=0, interactive=True): """Search pattern in archive members."""
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recompress_archive(archive, verbosity=0, interactive=True): """Recompress an archive to hopefully smaller size."""
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_mimedb(): """Initialize the internal MIME database."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_mimedb_data(mimedb): """Add missing encodings and mimetypes to MIME database."""
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') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backtick (cmd, encoding='utf-8'): """Return decoded output from command."""
data = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] return data.decode(encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run (cmd, verbosity=0, **kwargs): """Run command without error checking. @return: command return code"""
# Note that shell_quote_nt() result is not suitable for copy-paste # (especially on Unix systems), but it looks nicer than shell_quote(). if verbosity >= 0: log_info("running %s" % " ".join(map(shell_quote_nt, cmd))) if kwargs: if verbosity >= 0: log_info(" with %s" % ", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise PatoolError on error."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_mime_mimedb (filename): """Guess MIME type from given filename. @return: tuple (mime, encoding) """
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: # Files like 't.txt.gz' are recognized with encoding as format, and # an unsupported mime-type like 'tex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_existing_filename (filename, onlyfiles=True): """Ensure that given filename is a valid, existing file."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_archive_filelist (filenames): """Check that file list is not empty and contains only existing files."""
if not filenames: raise PatoolError("cannot create archive with empty filelist") for filename in filenames: check_existing_filename(filename, onlyfiles=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_mode (filename, flags): """Set mode flags for given filename if not already set."""
try: mode = os.lstat(filename).st_mode except OSError: # ignore 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmpfile (dir=None, prefix="temp", suffix=None): """Return a temporary file."""
return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_single_outfile (directory, archive, extension=""): """Get output filename if archive is in a single file format like gzip."""
outfile = os.path.join(directory, stripext(archive)) if os.path.exists(outfile + extension): # prevent overwriting existing files i = 1 newfile = "%s%d" % (outfile, i) while os.path.exists(newfile + extension): newfile = "%s%d" % (outfile, i) i += 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_env_info(key, out=sys.stderr): """If given environment key is defined, print it out."""
value = os.getenv(key) if value is not None: print(key, "=", repr(value), file=out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def p7zip_supports_rar(): """Determine if the RAR codec is installed for 7z program."""
if os.name == 'nt': # Assume RAR support is compiled into the binary. return True # the subdirectory and codec name codecname = 'p7zip/Codecs/Rar29.so' # search canonical user library dirs for libdir in ('/usr/lib', '/usr/local/lib', '/usr/lib64', '/usr/local/lib64', '/usr/lib/i386-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_program (program): """Look for program in environment PATH variable."""
if os.name == 'nt': # Add some well-known archiver programs to the search path 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: # use defaul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_to_path (path, directory): """Add a directory to the PATH environment variable, if it is a valid 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_nt_7z_dir (): """Return 7-Zip directory from registry, or an empty string."""
# Python 3.x renamed the _winreg module to winreg 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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_same_file (filename1, filename2): """Check if filename1 and filename2 point to the same file object. There can be false negatives, ie. the result is False...
if filename1 == filename2: return True if os.name == 'posix': return os.path.samefile(filename1, filename2) return is_same_filename(filename1, filename2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_same_filename (filename1, filename2): """Check if filename1 and filename2 are the same filename."""
return os.path.realpath(filename1) == os.path.realpath(filename2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_or_copy(src, dst, verbosity=0): """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 ...
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)