repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader.upload
def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None): """Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace """ # Get file handle content length in the most reliable way fd.seek(0, os.SEEK_END) size = fd.tell() fd.seek(0, os.SEEK_SET) if size > UPLOAD_SIMPLE_LIMIT_BYTES: resumable = True else: resumable = False logger.debug("Calculating checksum") hash_info = compute_hash_info(fd) if hash_info.size != size: # Has the file changed beween computing the hash # and calling upload()? raise ValueError("hash_info.size mismatch") upload_info = _UploadInfo(fd=fd, name=name, folder_key=folder_key, hash_info=hash_info, size=size, path=path, filedrop_key=filedrop_key, action_on_duplicate=action_on_duplicate) # Check whether file is present check_result = self._upload_check(upload_info, resumable) upload_result = None upload_func = None folder_key = check_result.get('folder_key', None) if folder_key is not None: # We know precisely what folder_key to use, drop path upload_info.folder_key = folder_key upload_info.path = None if check_result['hash_exists'] == 'yes': # file exists somewhere in MediaFire if check_result['in_folder'] == 'yes' and \ check_result['file_exists'] == 'yes': # file exists in this directory different_hash = check_result.get('different_hash', 'no') if different_hash == 'no': # file is already there upload_func = self._upload_none if not upload_func: # different hash or in other folder upload_func = self._upload_instant if not upload_func: if resumable: resumable_upload_info = check_result['resumable_upload'] upload_info.hash_info = compute_hash_info( fd, int(resumable_upload_info['unit_size'])) upload_func = self._upload_resumable else: upload_func = self._upload_simple # Retry retriable exceptions retries = UPLOAD_RETRY_COUNT while retries > 0: try: # Provide check_result to avoid calling API twice upload_result = upload_func(upload_info, check_result) except (RetriableUploadError, MediaFireConnectionError): retries -= 1 logger.exception("%s failed (%d retries left)", upload_func.__name__, retries) # Refresh check_result for next iteration check_result = self._upload_check(upload_info, resumable) except Exception: logger.exception("%s failed", upload_func) break else: break if upload_result is None: raise UploadError("Upload failed") return upload_result
python
def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None): """Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace """ # Get file handle content length in the most reliable way fd.seek(0, os.SEEK_END) size = fd.tell() fd.seek(0, os.SEEK_SET) if size > UPLOAD_SIMPLE_LIMIT_BYTES: resumable = True else: resumable = False logger.debug("Calculating checksum") hash_info = compute_hash_info(fd) if hash_info.size != size: # Has the file changed beween computing the hash # and calling upload()? raise ValueError("hash_info.size mismatch") upload_info = _UploadInfo(fd=fd, name=name, folder_key=folder_key, hash_info=hash_info, size=size, path=path, filedrop_key=filedrop_key, action_on_duplicate=action_on_duplicate) # Check whether file is present check_result = self._upload_check(upload_info, resumable) upload_result = None upload_func = None folder_key = check_result.get('folder_key', None) if folder_key is not None: # We know precisely what folder_key to use, drop path upload_info.folder_key = folder_key upload_info.path = None if check_result['hash_exists'] == 'yes': # file exists somewhere in MediaFire if check_result['in_folder'] == 'yes' and \ check_result['file_exists'] == 'yes': # file exists in this directory different_hash = check_result.get('different_hash', 'no') if different_hash == 'no': # file is already there upload_func = self._upload_none if not upload_func: # different hash or in other folder upload_func = self._upload_instant if not upload_func: if resumable: resumable_upload_info = check_result['resumable_upload'] upload_info.hash_info = compute_hash_info( fd, int(resumable_upload_info['unit_size'])) upload_func = self._upload_resumable else: upload_func = self._upload_simple # Retry retriable exceptions retries = UPLOAD_RETRY_COUNT while retries > 0: try: # Provide check_result to avoid calling API twice upload_result = upload_func(upload_info, check_result) except (RetriableUploadError, MediaFireConnectionError): retries -= 1 logger.exception("%s failed (%d retries left)", upload_func.__name__, retries) # Refresh check_result for next iteration check_result = self._upload_check(upload_info, resumable) except Exception: logger.exception("%s failed", upload_func) break else: break if upload_result is None: raise UploadError("Upload failed") return upload_result
[ "def", "upload", "(", "self", ",", "fd", ",", "name", "=", "None", ",", "folder_key", "=", "None", ",", "filedrop_key", "=", "None", ",", "path", "=", "None", ",", "action_on_duplicate", "=", "None", ")", ":", "# Get file handle content length in the most reliable way", "fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "size", "=", "fd", ".", "tell", "(", ")", "fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "if", "size", ">", "UPLOAD_SIMPLE_LIMIT_BYTES", ":", "resumable", "=", "True", "else", ":", "resumable", "=", "False", "logger", ".", "debug", "(", "\"Calculating checksum\"", ")", "hash_info", "=", "compute_hash_info", "(", "fd", ")", "if", "hash_info", ".", "size", "!=", "size", ":", "# Has the file changed beween computing the hash", "# and calling upload()?", "raise", "ValueError", "(", "\"hash_info.size mismatch\"", ")", "upload_info", "=", "_UploadInfo", "(", "fd", "=", "fd", ",", "name", "=", "name", ",", "folder_key", "=", "folder_key", ",", "hash_info", "=", "hash_info", ",", "size", "=", "size", ",", "path", "=", "path", ",", "filedrop_key", "=", "filedrop_key", ",", "action_on_duplicate", "=", "action_on_duplicate", ")", "# Check whether file is present", "check_result", "=", "self", ".", "_upload_check", "(", "upload_info", ",", "resumable", ")", "upload_result", "=", "None", "upload_func", "=", "None", "folder_key", "=", "check_result", ".", "get", "(", "'folder_key'", ",", "None", ")", "if", "folder_key", "is", "not", "None", ":", "# We know precisely what folder_key to use, drop path", "upload_info", ".", "folder_key", "=", "folder_key", "upload_info", ".", "path", "=", "None", "if", "check_result", "[", "'hash_exists'", "]", "==", "'yes'", ":", "# file exists somewhere in MediaFire", "if", "check_result", "[", "'in_folder'", "]", "==", "'yes'", "and", "check_result", "[", "'file_exists'", "]", "==", "'yes'", ":", "# file exists in this directory", "different_hash", "=", "check_result", ".", "get", "(", "'different_hash'", ",", "'no'", ")", "if", "different_hash", "==", "'no'", ":", "# file is already there", "upload_func", "=", "self", ".", "_upload_none", "if", "not", "upload_func", ":", "# different hash or in other folder", "upload_func", "=", "self", ".", "_upload_instant", "if", "not", "upload_func", ":", "if", "resumable", ":", "resumable_upload_info", "=", "check_result", "[", "'resumable_upload'", "]", "upload_info", ".", "hash_info", "=", "compute_hash_info", "(", "fd", ",", "int", "(", "resumable_upload_info", "[", "'unit_size'", "]", ")", ")", "upload_func", "=", "self", ".", "_upload_resumable", "else", ":", "upload_func", "=", "self", ".", "_upload_simple", "# Retry retriable exceptions", "retries", "=", "UPLOAD_RETRY_COUNT", "while", "retries", ">", "0", ":", "try", ":", "# Provide check_result to avoid calling API twice", "upload_result", "=", "upload_func", "(", "upload_info", ",", "check_result", ")", "except", "(", "RetriableUploadError", ",", "MediaFireConnectionError", ")", ":", "retries", "-=", "1", "logger", ".", "exception", "(", "\"%s failed (%d retries left)\"", ",", "upload_func", ".", "__name__", ",", "retries", ")", "# Refresh check_result for next iteration", "check_result", "=", "self", ".", "_upload_check", "(", "upload_info", ",", "resumable", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "\"%s failed\"", ",", "upload_func", ")", "break", "else", ":", "break", "if", "upload_result", "is", "None", ":", "raise", "UploadError", "(", "\"Upload failed\"", ")", "return", "upload_result" ]
Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace
[ "Upload", "file", "returns", "UploadResult", "object" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L198-L289
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._poll_upload
def _poll_upload(self, upload_key, action): """Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions """ if len(upload_key) != UPLOAD_KEY_LENGTH: # not a regular 11-char-long upload key # There is no API to poll filedrop uploads return UploadResult( action=action, quickkey=None, hash_=None, filename=None, size=None, created=None, revision=None ) quick_key = None while quick_key is None: poll_result = self._api.upload_poll(upload_key) doupload = poll_result['doupload'] logger.debug("poll(%s): status=%d, description=%s, filename=%s," " result=%d", upload_key, int(doupload['status']), doupload['description'], doupload['filename'], int(doupload['result'])) if int(doupload['result']) != 0: break if doupload['fileerror'] != '': # TODO: we may have to handle this a bit more dramatically logger.warning("poll(%s): fileerror=%d", upload_key, int(doupload['fileerror'])) break if int(doupload['status']) == STATUS_NO_MORE_REQUESTS: quick_key = doupload['quickkey'] elif int(doupload['status']) == STATUS_UPLOAD_IN_PROGRESS: # BUG: http://forum.mediafiredev.com/showthread.php?588 raise RetriableUploadError( "Invalid state transition ({})".format( doupload['description'] ) ) else: time.sleep(UPLOAD_POLL_INTERVAL) return UploadResult( action=action, quickkey=doupload['quickkey'], hash_=doupload['hash'], filename=doupload['filename'], size=doupload['size'], created=doupload['created'], revision=doupload['revision'] )
python
def _poll_upload(self, upload_key, action): """Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions """ if len(upload_key) != UPLOAD_KEY_LENGTH: # not a regular 11-char-long upload key # There is no API to poll filedrop uploads return UploadResult( action=action, quickkey=None, hash_=None, filename=None, size=None, created=None, revision=None ) quick_key = None while quick_key is None: poll_result = self._api.upload_poll(upload_key) doupload = poll_result['doupload'] logger.debug("poll(%s): status=%d, description=%s, filename=%s," " result=%d", upload_key, int(doupload['status']), doupload['description'], doupload['filename'], int(doupload['result'])) if int(doupload['result']) != 0: break if doupload['fileerror'] != '': # TODO: we may have to handle this a bit more dramatically logger.warning("poll(%s): fileerror=%d", upload_key, int(doupload['fileerror'])) break if int(doupload['status']) == STATUS_NO_MORE_REQUESTS: quick_key = doupload['quickkey'] elif int(doupload['status']) == STATUS_UPLOAD_IN_PROGRESS: # BUG: http://forum.mediafiredev.com/showthread.php?588 raise RetriableUploadError( "Invalid state transition ({})".format( doupload['description'] ) ) else: time.sleep(UPLOAD_POLL_INTERVAL) return UploadResult( action=action, quickkey=doupload['quickkey'], hash_=doupload['hash'], filename=doupload['filename'], size=doupload['size'], created=doupload['created'], revision=doupload['revision'] )
[ "def", "_poll_upload", "(", "self", ",", "upload_key", ",", "action", ")", ":", "if", "len", "(", "upload_key", ")", "!=", "UPLOAD_KEY_LENGTH", ":", "# not a regular 11-char-long upload key", "# There is no API to poll filedrop uploads", "return", "UploadResult", "(", "action", "=", "action", ",", "quickkey", "=", "None", ",", "hash_", "=", "None", ",", "filename", "=", "None", ",", "size", "=", "None", ",", "created", "=", "None", ",", "revision", "=", "None", ")", "quick_key", "=", "None", "while", "quick_key", "is", "None", ":", "poll_result", "=", "self", ".", "_api", ".", "upload_poll", "(", "upload_key", ")", "doupload", "=", "poll_result", "[", "'doupload'", "]", "logger", ".", "debug", "(", "\"poll(%s): status=%d, description=%s, filename=%s,\"", "\" result=%d\"", ",", "upload_key", ",", "int", "(", "doupload", "[", "'status'", "]", ")", ",", "doupload", "[", "'description'", "]", ",", "doupload", "[", "'filename'", "]", ",", "int", "(", "doupload", "[", "'result'", "]", ")", ")", "if", "int", "(", "doupload", "[", "'result'", "]", ")", "!=", "0", ":", "break", "if", "doupload", "[", "'fileerror'", "]", "!=", "''", ":", "# TODO: we may have to handle this a bit more dramatically", "logger", ".", "warning", "(", "\"poll(%s): fileerror=%d\"", ",", "upload_key", ",", "int", "(", "doupload", "[", "'fileerror'", "]", ")", ")", "break", "if", "int", "(", "doupload", "[", "'status'", "]", ")", "==", "STATUS_NO_MORE_REQUESTS", ":", "quick_key", "=", "doupload", "[", "'quickkey'", "]", "elif", "int", "(", "doupload", "[", "'status'", "]", ")", "==", "STATUS_UPLOAD_IN_PROGRESS", ":", "# BUG: http://forum.mediafiredev.com/showthread.php?588", "raise", "RetriableUploadError", "(", "\"Invalid state transition ({})\"", ".", "format", "(", "doupload", "[", "'description'", "]", ")", ")", "else", ":", "time", ".", "sleep", "(", "UPLOAD_POLL_INTERVAL", ")", "return", "UploadResult", "(", "action", "=", "action", ",", "quickkey", "=", "doupload", "[", "'quickkey'", "]", ",", "hash_", "=", "doupload", "[", "'hash'", "]", ",", "filename", "=", "doupload", "[", "'filename'", "]", ",", "size", "=", "doupload", "[", "'size'", "]", ",", "created", "=", "doupload", "[", "'created'", "]", ",", "revision", "=", "doupload", "[", "'revision'", "]", ")" ]
Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions
[ "Poll", "upload", "until", "quickkey", "is", "found" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L292-L351
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_check
def _upload_check(self, upload_info, resumable=False): """Wrapper around upload/check""" return self._api.upload_check( filename=upload_info.name, size=upload_info.size, hash_=upload_info.hash_info.file, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, resumable=resumable )
python
def _upload_check(self, upload_info, resumable=False): """Wrapper around upload/check""" return self._api.upload_check( filename=upload_info.name, size=upload_info.size, hash_=upload_info.hash_info.file, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, resumable=resumable )
[ "def", "_upload_check", "(", "self", ",", "upload_info", ",", "resumable", "=", "False", ")", ":", "return", "self", ".", "_api", ".", "upload_check", "(", "filename", "=", "upload_info", ".", "name", ",", "size", "=", "upload_info", ".", "size", ",", "hash_", "=", "upload_info", ".", "hash_info", ".", "file", ",", "folder_key", "=", "upload_info", ".", "folder_key", ",", "filedrop_key", "=", "upload_info", ".", "filedrop_key", ",", "path", "=", "upload_info", ".", "path", ",", "resumable", "=", "resumable", ")" ]
Wrapper around upload/check
[ "Wrapper", "around", "upload", "/", "check" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L353-L363
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_none
def _upload_none(self, upload_info, check_result): """Dummy upload function for when we don't actually upload""" return UploadResult( action=None, quickkey=check_result['duplicate_quickkey'], hash_=upload_info.hash_info.file, filename=upload_info.name, size=upload_info.size, created=None, revision=None )
python
def _upload_none(self, upload_info, check_result): """Dummy upload function for when we don't actually upload""" return UploadResult( action=None, quickkey=check_result['duplicate_quickkey'], hash_=upload_info.hash_info.file, filename=upload_info.name, size=upload_info.size, created=None, revision=None )
[ "def", "_upload_none", "(", "self", ",", "upload_info", ",", "check_result", ")", ":", "return", "UploadResult", "(", "action", "=", "None", ",", "quickkey", "=", "check_result", "[", "'duplicate_quickkey'", "]", ",", "hash_", "=", "upload_info", ".", "hash_info", ".", "file", ",", "filename", "=", "upload_info", ".", "name", ",", "size", "=", "upload_info", ".", "size", ",", "created", "=", "None", ",", "revision", "=", "None", ")" ]
Dummy upload function for when we don't actually upload
[ "Dummy", "upload", "function", "for", "when", "we", "don", "t", "actually", "upload" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L367-L377
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_instant
def _upload_instant(self, upload_info, _=None): """Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_info -- UploadInfo object check_result -- ignored """ result = self._api.upload_instant( upload_info.name, upload_info.size, upload_info.hash_info.file, path=upload_info.path, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, action_on_duplicate=upload_info.action_on_duplicate ) return UploadResult( action='upload/instant', quickkey=result['quickkey'], filename=result['filename'], revision=result['new_device_revision'], hash_=upload_info.hash_info.file, size=upload_info.size, created=None )
python
def _upload_instant(self, upload_info, _=None): """Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_info -- UploadInfo object check_result -- ignored """ result = self._api.upload_instant( upload_info.name, upload_info.size, upload_info.hash_info.file, path=upload_info.path, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, action_on_duplicate=upload_info.action_on_duplicate ) return UploadResult( action='upload/instant', quickkey=result['quickkey'], filename=result['filename'], revision=result['new_device_revision'], hash_=upload_info.hash_info.file, size=upload_info.size, created=None )
[ "def", "_upload_instant", "(", "self", ",", "upload_info", ",", "_", "=", "None", ")", ":", "result", "=", "self", ".", "_api", ".", "upload_instant", "(", "upload_info", ".", "name", ",", "upload_info", ".", "size", ",", "upload_info", ".", "hash_info", ".", "file", ",", "path", "=", "upload_info", ".", "path", ",", "folder_key", "=", "upload_info", ".", "folder_key", ",", "filedrop_key", "=", "upload_info", ".", "filedrop_key", ",", "action_on_duplicate", "=", "upload_info", ".", "action_on_duplicate", ")", "return", "UploadResult", "(", "action", "=", "'upload/instant'", ",", "quickkey", "=", "result", "[", "'quickkey'", "]", ",", "filename", "=", "result", "[", "'filename'", "]", ",", "revision", "=", "result", "[", "'new_device_revision'", "]", ",", "hash_", "=", "upload_info", ".", "hash_info", ".", "file", ",", "size", "=", "upload_info", ".", "size", ",", "created", "=", "None", ")" ]
Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_info -- UploadInfo object check_result -- ignored
[ "Instant", "upload", "and", "return", "quickkey" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L380-L407
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_simple
def _upload_simple(self, upload_info, _=None): """Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_info -- UploadInfo object check_result -- ignored """ upload_result = self._api.upload_simple( upload_info.fd, upload_info.name, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, file_size=upload_info.size, file_hash=upload_info.hash_info.file, action_on_duplicate=upload_info.action_on_duplicate) logger.debug("upload_result: %s", upload_result) upload_key = upload_result['doupload']['key'] return self._poll_upload(upload_key, 'upload/simple')
python
def _upload_simple(self, upload_info, _=None): """Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_info -- UploadInfo object check_result -- ignored """ upload_result = self._api.upload_simple( upload_info.fd, upload_info.name, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, file_size=upload_info.size, file_hash=upload_info.hash_info.file, action_on_duplicate=upload_info.action_on_duplicate) logger.debug("upload_result: %s", upload_result) upload_key = upload_result['doupload']['key'] return self._poll_upload(upload_key, 'upload/simple')
[ "def", "_upload_simple", "(", "self", ",", "upload_info", ",", "_", "=", "None", ")", ":", "upload_result", "=", "self", ".", "_api", ".", "upload_simple", "(", "upload_info", ".", "fd", ",", "upload_info", ".", "name", ",", "folder_key", "=", "upload_info", ".", "folder_key", ",", "filedrop_key", "=", "upload_info", ".", "filedrop_key", ",", "path", "=", "upload_info", ".", "path", ",", "file_size", "=", "upload_info", ".", "size", ",", "file_hash", "=", "upload_info", ".", "hash_info", ".", "file", ",", "action_on_duplicate", "=", "upload_info", ".", "action_on_duplicate", ")", "logger", ".", "debug", "(", "\"upload_result: %s\"", ",", "upload_result", ")", "upload_key", "=", "upload_result", "[", "'doupload'", "]", "[", "'key'", "]", "return", "self", ".", "_poll_upload", "(", "upload_key", ",", "'upload/simple'", ")" ]
Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_info -- UploadInfo object check_result -- ignored
[ "Simple", "upload", "and", "return", "quickkey" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L409-L432
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_resumable_unit
def _upload_resumable_unit(self, uu_info): """Upload a single unit and return raw upload/resumable result uu_info -- UploadUnitInfo instance """ # Get actual unit size unit_size = uu_info.fd.len if uu_info.hash_ is None: raise ValueError('UploadUnitInfo.hash_ is now required') return self._api.upload_resumable( uu_info.fd, uu_info.upload_info.size, uu_info.upload_info.hash_info.file, uu_info.hash_, uu_info.uid, unit_size, filedrop_key=uu_info.upload_info.filedrop_key, folder_key=uu_info.upload_info.folder_key, path=uu_info.upload_info.path, action_on_duplicate=uu_info.upload_info.action_on_duplicate)
python
def _upload_resumable_unit(self, uu_info): """Upload a single unit and return raw upload/resumable result uu_info -- UploadUnitInfo instance """ # Get actual unit size unit_size = uu_info.fd.len if uu_info.hash_ is None: raise ValueError('UploadUnitInfo.hash_ is now required') return self._api.upload_resumable( uu_info.fd, uu_info.upload_info.size, uu_info.upload_info.hash_info.file, uu_info.hash_, uu_info.uid, unit_size, filedrop_key=uu_info.upload_info.filedrop_key, folder_key=uu_info.upload_info.folder_key, path=uu_info.upload_info.path, action_on_duplicate=uu_info.upload_info.action_on_duplicate)
[ "def", "_upload_resumable_unit", "(", "self", ",", "uu_info", ")", ":", "# Get actual unit size", "unit_size", "=", "uu_info", ".", "fd", ".", "len", "if", "uu_info", ".", "hash_", "is", "None", ":", "raise", "ValueError", "(", "'UploadUnitInfo.hash_ is now required'", ")", "return", "self", ".", "_api", ".", "upload_resumable", "(", "uu_info", ".", "fd", ",", "uu_info", ".", "upload_info", ".", "size", ",", "uu_info", ".", "upload_info", ".", "hash_info", ".", "file", ",", "uu_info", ".", "hash_", ",", "uu_info", ".", "uid", ",", "unit_size", ",", "filedrop_key", "=", "uu_info", ".", "upload_info", ".", "filedrop_key", ",", "folder_key", "=", "uu_info", ".", "upload_info", ".", "folder_key", ",", "path", "=", "uu_info", ".", "upload_info", ".", "path", ",", "action_on_duplicate", "=", "uu_info", ".", "upload_info", ".", "action_on_duplicate", ")" ]
Upload a single unit and return raw upload/resumable result uu_info -- UploadUnitInfo instance
[ "Upload", "a", "single", "unit", "and", "return", "raw", "upload", "/", "resumable", "result" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L434-L456
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_resumable_all
def _upload_resumable_all(self, upload_info, bitmap, number_of_units, unit_size): """Prepare and upload all resumable units and return upload_key upload_info -- UploadInfo object bitmap -- bitmap node of upload/check number_of_units -- number of units requested unit_size -- size of a single upload unit in bytes """ fd = upload_info.fd upload_key = None for unit_id in range(number_of_units): upload_status = decode_resumable_upload_bitmap( bitmap, number_of_units) if upload_status[unit_id]: logger.debug("Skipping unit %d/%d - already uploaded", unit_id + 1, number_of_units) continue logger.debug("Uploading unit %d/%d", unit_id + 1, number_of_units) offset = unit_id * unit_size with SubsetIO(fd, offset, unit_size) as unit_fd: unit_info = _UploadUnitInfo( upload_info=upload_info, hash_=upload_info.hash_info.units[unit_id], fd=unit_fd, uid=unit_id) upload_result = self._upload_resumable_unit(unit_info) # upload_key is needed for polling if upload_key is None: upload_key = upload_result['doupload']['key'] return upload_key
python
def _upload_resumable_all(self, upload_info, bitmap, number_of_units, unit_size): """Prepare and upload all resumable units and return upload_key upload_info -- UploadInfo object bitmap -- bitmap node of upload/check number_of_units -- number of units requested unit_size -- size of a single upload unit in bytes """ fd = upload_info.fd upload_key = None for unit_id in range(number_of_units): upload_status = decode_resumable_upload_bitmap( bitmap, number_of_units) if upload_status[unit_id]: logger.debug("Skipping unit %d/%d - already uploaded", unit_id + 1, number_of_units) continue logger.debug("Uploading unit %d/%d", unit_id + 1, number_of_units) offset = unit_id * unit_size with SubsetIO(fd, offset, unit_size) as unit_fd: unit_info = _UploadUnitInfo( upload_info=upload_info, hash_=upload_info.hash_info.units[unit_id], fd=unit_fd, uid=unit_id) upload_result = self._upload_resumable_unit(unit_info) # upload_key is needed for polling if upload_key is None: upload_key = upload_result['doupload']['key'] return upload_key
[ "def", "_upload_resumable_all", "(", "self", ",", "upload_info", ",", "bitmap", ",", "number_of_units", ",", "unit_size", ")", ":", "fd", "=", "upload_info", ".", "fd", "upload_key", "=", "None", "for", "unit_id", "in", "range", "(", "number_of_units", ")", ":", "upload_status", "=", "decode_resumable_upload_bitmap", "(", "bitmap", ",", "number_of_units", ")", "if", "upload_status", "[", "unit_id", "]", ":", "logger", ".", "debug", "(", "\"Skipping unit %d/%d - already uploaded\"", ",", "unit_id", "+", "1", ",", "number_of_units", ")", "continue", "logger", ".", "debug", "(", "\"Uploading unit %d/%d\"", ",", "unit_id", "+", "1", ",", "number_of_units", ")", "offset", "=", "unit_id", "*", "unit_size", "with", "SubsetIO", "(", "fd", ",", "offset", ",", "unit_size", ")", "as", "unit_fd", ":", "unit_info", "=", "_UploadUnitInfo", "(", "upload_info", "=", "upload_info", ",", "hash_", "=", "upload_info", ".", "hash_info", ".", "units", "[", "unit_id", "]", ",", "fd", "=", "unit_fd", ",", "uid", "=", "unit_id", ")", "upload_result", "=", "self", ".", "_upload_resumable_unit", "(", "unit_info", ")", "# upload_key is needed for polling", "if", "upload_key", "is", "None", ":", "upload_key", "=", "upload_result", "[", "'doupload'", "]", "[", "'key'", "]", "return", "upload_key" ]
Prepare and upload all resumable units and return upload_key upload_info -- UploadInfo object bitmap -- bitmap node of upload/check number_of_units -- number of units requested unit_size -- size of a single upload unit in bytes
[ "Prepare", "and", "upload", "all", "resumable", "units", "and", "return", "upload_key" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L458-L500
train
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
MediaFireUploader._upload_resumable
def _upload_resumable(self, upload_info, check_result): """Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/check call result """ resumable_upload = check_result['resumable_upload'] unit_size = int(resumable_upload['unit_size']) number_of_units = int(resumable_upload['number_of_units']) # make sure we have calculated the right thing logger.debug("number_of_units=%s (expected %s)", number_of_units, len(upload_info.hash_info.units)) assert len(upload_info.hash_info.units) == number_of_units logger.debug("Preparing %d units * %d bytes", number_of_units, unit_size) upload_key = None retries = UPLOAD_RETRY_COUNT all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] while not all_units_ready and retries > 0: upload_key = self._upload_resumable_all(upload_info, bitmap, number_of_units, unit_size) check_result = self._upload_check(upload_info, resumable=True) resumable_upload = check_result['resumable_upload'] all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] if not all_units_ready: retries -= 1 logger.debug("Some units failed to upload (%d retries left)", retries) if not all_units_ready: # Most likely non-retriable raise UploadError("Could not upload all units") logger.debug("Upload complete, polling for status") return self._poll_upload(upload_key, 'upload/resumable')
python
def _upload_resumable(self, upload_info, check_result): """Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/check call result """ resumable_upload = check_result['resumable_upload'] unit_size = int(resumable_upload['unit_size']) number_of_units = int(resumable_upload['number_of_units']) # make sure we have calculated the right thing logger.debug("number_of_units=%s (expected %s)", number_of_units, len(upload_info.hash_info.units)) assert len(upload_info.hash_info.units) == number_of_units logger.debug("Preparing %d units * %d bytes", number_of_units, unit_size) upload_key = None retries = UPLOAD_RETRY_COUNT all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] while not all_units_ready and retries > 0: upload_key = self._upload_resumable_all(upload_info, bitmap, number_of_units, unit_size) check_result = self._upload_check(upload_info, resumable=True) resumable_upload = check_result['resumable_upload'] all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] if not all_units_ready: retries -= 1 logger.debug("Some units failed to upload (%d retries left)", retries) if not all_units_ready: # Most likely non-retriable raise UploadError("Could not upload all units") logger.debug("Upload complete, polling for status") return self._poll_upload(upload_key, 'upload/resumable')
[ "def", "_upload_resumable", "(", "self", ",", "upload_info", ",", "check_result", ")", ":", "resumable_upload", "=", "check_result", "[", "'resumable_upload'", "]", "unit_size", "=", "int", "(", "resumable_upload", "[", "'unit_size'", "]", ")", "number_of_units", "=", "int", "(", "resumable_upload", "[", "'number_of_units'", "]", ")", "# make sure we have calculated the right thing", "logger", ".", "debug", "(", "\"number_of_units=%s (expected %s)\"", ",", "number_of_units", ",", "len", "(", "upload_info", ".", "hash_info", ".", "units", ")", ")", "assert", "len", "(", "upload_info", ".", "hash_info", ".", "units", ")", "==", "number_of_units", "logger", ".", "debug", "(", "\"Preparing %d units * %d bytes\"", ",", "number_of_units", ",", "unit_size", ")", "upload_key", "=", "None", "retries", "=", "UPLOAD_RETRY_COUNT", "all_units_ready", "=", "resumable_upload", "[", "'all_units_ready'", "]", "==", "'yes'", "bitmap", "=", "resumable_upload", "[", "'bitmap'", "]", "while", "not", "all_units_ready", "and", "retries", ">", "0", ":", "upload_key", "=", "self", ".", "_upload_resumable_all", "(", "upload_info", ",", "bitmap", ",", "number_of_units", ",", "unit_size", ")", "check_result", "=", "self", ".", "_upload_check", "(", "upload_info", ",", "resumable", "=", "True", ")", "resumable_upload", "=", "check_result", "[", "'resumable_upload'", "]", "all_units_ready", "=", "resumable_upload", "[", "'all_units_ready'", "]", "==", "'yes'", "bitmap", "=", "resumable_upload", "[", "'bitmap'", "]", "if", "not", "all_units_ready", ":", "retries", "-=", "1", "logger", ".", "debug", "(", "\"Some units failed to upload (%d retries left)\"", ",", "retries", ")", "if", "not", "all_units_ready", ":", "# Most likely non-retriable", "raise", "UploadError", "(", "\"Could not upload all units\"", ")", "logger", ".", "debug", "(", "\"Upload complete, polling for status\"", ")", "return", "self", ".", "_poll_upload", "(", "upload_key", ",", "'upload/resumable'", ")" ]
Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/check call result
[ "Resumable", "upload", "and", "return", "quickkey" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L502-L549
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
ModuleFinder.reset
def reset(self): """Remove from sys.modules the modules imported by the debuggee.""" if not self.hooked: self.hooked = True sys.path_hooks.append(self) sys.path.insert(0, self.PATH_ENTRY) return for modname in self: if modname in sys.modules: del sys.modules[modname] submods = [] for subm in sys.modules: if subm.startswith(modname + '.'): submods.append(subm) # All submodules of modname may not have been imported by the # debuggee, but they are still removed from sys.modules as # there is no way to distinguish them. for subm in submods: del sys.modules[subm] self[:] = []
python
def reset(self): """Remove from sys.modules the modules imported by the debuggee.""" if not self.hooked: self.hooked = True sys.path_hooks.append(self) sys.path.insert(0, self.PATH_ENTRY) return for modname in self: if modname in sys.modules: del sys.modules[modname] submods = [] for subm in sys.modules: if subm.startswith(modname + '.'): submods.append(subm) # All submodules of modname may not have been imported by the # debuggee, but they are still removed from sys.modules as # there is no way to distinguish them. for subm in submods: del sys.modules[subm] self[:] = []
[ "def", "reset", "(", "self", ")", ":", "if", "not", "self", ".", "hooked", ":", "self", ".", "hooked", "=", "True", "sys", ".", "path_hooks", ".", "append", "(", "self", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "self", ".", "PATH_ENTRY", ")", "return", "for", "modname", "in", "self", ":", "if", "modname", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "modname", "]", "submods", "=", "[", "]", "for", "subm", "in", "sys", ".", "modules", ":", "if", "subm", ".", "startswith", "(", "modname", "+", "'.'", ")", ":", "submods", ".", "append", "(", "subm", ")", "# All submodules of modname may not have been imported by the", "# debuggee, but they are still removed from sys.modules as", "# there is no way to distinguish them.", "for", "subm", "in", "submods", ":", "del", "sys", ".", "modules", "[", "subm", "]", "self", "[", ":", "]", "=", "[", "]" ]
Remove from sys.modules the modules imported by the debuggee.
[ "Remove", "from", "sys", ".", "modules", "the", "modules", "imported", "by", "the", "debuggee", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L56-L76
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
BdbModule.get_func_lno
def get_func_lno(self, funcname): """The first line number of the last defined 'funcname' function.""" class FuncLineno(ast.NodeVisitor): def __init__(self): self.clss = [] def generic_visit(self, node): for child in ast.iter_child_nodes(node): for item in self.visit(child): yield item def visit_ClassDef(self, node): self.clss.append(node.name) for item in self.generic_visit(node): yield item self.clss.pop() def visit_FunctionDef(self, node): # Only allow non nested function definitions. name = '.'.join(itertools.chain(self.clss, [node.name])) yield name, node.lineno if self.functions_firstlno is None: self.functions_firstlno = {} for name, lineno in FuncLineno().visit(self.node): if (name not in self.functions_firstlno or self.functions_firstlno[name] < lineno): self.functions_firstlno[name] = lineno try: return self.functions_firstlno[funcname] except KeyError: raise BdbSourceError('{}: function "{}" not found.'.format( self.filename, funcname))
python
def get_func_lno(self, funcname): """The first line number of the last defined 'funcname' function.""" class FuncLineno(ast.NodeVisitor): def __init__(self): self.clss = [] def generic_visit(self, node): for child in ast.iter_child_nodes(node): for item in self.visit(child): yield item def visit_ClassDef(self, node): self.clss.append(node.name) for item in self.generic_visit(node): yield item self.clss.pop() def visit_FunctionDef(self, node): # Only allow non nested function definitions. name = '.'.join(itertools.chain(self.clss, [node.name])) yield name, node.lineno if self.functions_firstlno is None: self.functions_firstlno = {} for name, lineno in FuncLineno().visit(self.node): if (name not in self.functions_firstlno or self.functions_firstlno[name] < lineno): self.functions_firstlno[name] = lineno try: return self.functions_firstlno[funcname] except KeyError: raise BdbSourceError('{}: function "{}" not found.'.format( self.filename, funcname))
[ "def", "get_func_lno", "(", "self", ",", "funcname", ")", ":", "class", "FuncLineno", "(", "ast", ".", "NodeVisitor", ")", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "clss", "=", "[", "]", "def", "generic_visit", "(", "self", ",", "node", ")", ":", "for", "child", "in", "ast", ".", "iter_child_nodes", "(", "node", ")", ":", "for", "item", "in", "self", ".", "visit", "(", "child", ")", ":", "yield", "item", "def", "visit_ClassDef", "(", "self", ",", "node", ")", ":", "self", ".", "clss", ".", "append", "(", "node", ".", "name", ")", "for", "item", "in", "self", ".", "generic_visit", "(", "node", ")", ":", "yield", "item", "self", ".", "clss", ".", "pop", "(", ")", "def", "visit_FunctionDef", "(", "self", ",", "node", ")", ":", "# Only allow non nested function definitions.", "name", "=", "'.'", ".", "join", "(", "itertools", ".", "chain", "(", "self", ".", "clss", ",", "[", "node", ".", "name", "]", ")", ")", "yield", "name", ",", "node", ".", "lineno", "if", "self", ".", "functions_firstlno", "is", "None", ":", "self", ".", "functions_firstlno", "=", "{", "}", "for", "name", ",", "lineno", "in", "FuncLineno", "(", ")", ".", "visit", "(", "self", ".", "node", ")", ":", "if", "(", "name", "not", "in", "self", ".", "functions_firstlno", "or", "self", ".", "functions_firstlno", "[", "name", "]", "<", "lineno", ")", ":", "self", ".", "functions_firstlno", "[", "name", "]", "=", "lineno", "try", ":", "return", "self", ".", "functions_firstlno", "[", "funcname", "]", "except", "KeyError", ":", "raise", "BdbSourceError", "(", "'{}: function \"{}\" not found.'", ".", "format", "(", "self", ".", "filename", ",", "funcname", ")", ")" ]
The first line number of the last defined 'funcname' function.
[ "The", "first", "line", "number", "of", "the", "last", "defined", "funcname", "function", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L255-L288
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
BdbModule.get_actual_bp
def get_actual_bp(self, lineno): """Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object or one of its subcodes, pick up the next valid statement line number. Return the statement line defined by the tuple (code firstlineno, statement line number) which is at the shortest distance to line 'lineno' and greater or equal to 'lineno'. When 'lineno' is the first line number of a subcode, use its first statement line instead. """ def _distance(code, module_level=False): """The shortest distance to the next valid statement.""" subcodes = dict((c.co_firstlineno, c) for c in code.co_consts if isinstance(c, types.CodeType) and not c.co_name.startswith('<')) # Get the shortest distance to the subcode whose first line number # is the last to be less or equal to lineno. That is, find the # index of the first subcode whose first_lno is the first to be # strictly greater than lineno. subcode_dist = None subcodes_flnos = sorted(subcodes) idx = bisect(subcodes_flnos, lineno) if idx != 0: flno = subcodes_flnos[idx-1] subcode_dist = _distance(subcodes[flno]) # Check if lineno is a valid statement line number in the current # code, excluding function or method definition lines. code_lnos = sorted(code_line_numbers(code)) # Do not stop at execution of function definitions. if not module_level and len(code_lnos) > 1: code_lnos = code_lnos[1:] if lineno in code_lnos and lineno not in subcodes_flnos: return 0, (code.co_firstlineno, lineno) # Compute the distance to the next valid statement in this code. idx = bisect(code_lnos, lineno) if idx == len(code_lnos): # lineno is greater that all 'code' line numbers. return subcode_dist actual_lno = code_lnos[idx] dist = actual_lno - lineno if subcode_dist and subcode_dist[0] < dist: return subcode_dist if actual_lno not in subcodes_flnos: return dist, (code.co_firstlineno, actual_lno) else: # The actual line number is the line number of the first # statement of the subcode following lineno (recursively). return _distance(subcodes[actual_lno]) if self.code: code_dist = _distance(self.code, module_level=True) if not self.code or not code_dist: raise BdbSourceError('{}: line {} is after the last ' 'valid statement.'.format(self.filename, lineno)) return code_dist[1]
python
def get_actual_bp(self, lineno): """Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object or one of its subcodes, pick up the next valid statement line number. Return the statement line defined by the tuple (code firstlineno, statement line number) which is at the shortest distance to line 'lineno' and greater or equal to 'lineno'. When 'lineno' is the first line number of a subcode, use its first statement line instead. """ def _distance(code, module_level=False): """The shortest distance to the next valid statement.""" subcodes = dict((c.co_firstlineno, c) for c in code.co_consts if isinstance(c, types.CodeType) and not c.co_name.startswith('<')) # Get the shortest distance to the subcode whose first line number # is the last to be less or equal to lineno. That is, find the # index of the first subcode whose first_lno is the first to be # strictly greater than lineno. subcode_dist = None subcodes_flnos = sorted(subcodes) idx = bisect(subcodes_flnos, lineno) if idx != 0: flno = subcodes_flnos[idx-1] subcode_dist = _distance(subcodes[flno]) # Check if lineno is a valid statement line number in the current # code, excluding function or method definition lines. code_lnos = sorted(code_line_numbers(code)) # Do not stop at execution of function definitions. if not module_level and len(code_lnos) > 1: code_lnos = code_lnos[1:] if lineno in code_lnos and lineno not in subcodes_flnos: return 0, (code.co_firstlineno, lineno) # Compute the distance to the next valid statement in this code. idx = bisect(code_lnos, lineno) if idx == len(code_lnos): # lineno is greater that all 'code' line numbers. return subcode_dist actual_lno = code_lnos[idx] dist = actual_lno - lineno if subcode_dist and subcode_dist[0] < dist: return subcode_dist if actual_lno not in subcodes_flnos: return dist, (code.co_firstlineno, actual_lno) else: # The actual line number is the line number of the first # statement of the subcode following lineno (recursively). return _distance(subcodes[actual_lno]) if self.code: code_dist = _distance(self.code, module_level=True) if not self.code or not code_dist: raise BdbSourceError('{}: line {} is after the last ' 'valid statement.'.format(self.filename, lineno)) return code_dist[1]
[ "def", "get_actual_bp", "(", "self", ",", "lineno", ")", ":", "def", "_distance", "(", "code", ",", "module_level", "=", "False", ")", ":", "\"\"\"The shortest distance to the next valid statement.\"\"\"", "subcodes", "=", "dict", "(", "(", "c", ".", "co_firstlineno", ",", "c", ")", "for", "c", "in", "code", ".", "co_consts", "if", "isinstance", "(", "c", ",", "types", ".", "CodeType", ")", "and", "not", "c", ".", "co_name", ".", "startswith", "(", "'<'", ")", ")", "# Get the shortest distance to the subcode whose first line number", "# is the last to be less or equal to lineno. That is, find the", "# index of the first subcode whose first_lno is the first to be", "# strictly greater than lineno.", "subcode_dist", "=", "None", "subcodes_flnos", "=", "sorted", "(", "subcodes", ")", "idx", "=", "bisect", "(", "subcodes_flnos", ",", "lineno", ")", "if", "idx", "!=", "0", ":", "flno", "=", "subcodes_flnos", "[", "idx", "-", "1", "]", "subcode_dist", "=", "_distance", "(", "subcodes", "[", "flno", "]", ")", "# Check if lineno is a valid statement line number in the current", "# code, excluding function or method definition lines.", "code_lnos", "=", "sorted", "(", "code_line_numbers", "(", "code", ")", ")", "# Do not stop at execution of function definitions.", "if", "not", "module_level", "and", "len", "(", "code_lnos", ")", ">", "1", ":", "code_lnos", "=", "code_lnos", "[", "1", ":", "]", "if", "lineno", "in", "code_lnos", "and", "lineno", "not", "in", "subcodes_flnos", ":", "return", "0", ",", "(", "code", ".", "co_firstlineno", ",", "lineno", ")", "# Compute the distance to the next valid statement in this code.", "idx", "=", "bisect", "(", "code_lnos", ",", "lineno", ")", "if", "idx", "==", "len", "(", "code_lnos", ")", ":", "# lineno is greater that all 'code' line numbers.", "return", "subcode_dist", "actual_lno", "=", "code_lnos", "[", "idx", "]", "dist", "=", "actual_lno", "-", "lineno", "if", "subcode_dist", "and", "subcode_dist", "[", "0", "]", "<", "dist", ":", "return", "subcode_dist", "if", "actual_lno", "not", "in", "subcodes_flnos", ":", "return", "dist", ",", "(", "code", ".", "co_firstlineno", ",", "actual_lno", ")", "else", ":", "# The actual line number is the line number of the first", "# statement of the subcode following lineno (recursively).", "return", "_distance", "(", "subcodes", "[", "actual_lno", "]", ")", "if", "self", ".", "code", ":", "code_dist", "=", "_distance", "(", "self", ".", "code", ",", "module_level", "=", "True", ")", "if", "not", "self", ".", "code", "or", "not", "code_dist", ":", "raise", "BdbSourceError", "(", "'{}: line {} is after the last '", "'valid statement.'", ".", "format", "(", "self", ".", "filename", ",", "lineno", ")", ")", "return", "code_dist", "[", "1", "]" ]
Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object or one of its subcodes, pick up the next valid statement line number. Return the statement line defined by the tuple (code firstlineno, statement line number) which is at the shortest distance to line 'lineno' and greater or equal to 'lineno'. When 'lineno' is the first line number of a subcode, use its first statement line instead.
[ "Get", "the", "actual", "breakpoint", "line", "number", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L290-L349
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
ModuleBreakpoints.get_breakpoints
def get_breakpoints(self, lineno): """Return the list of breakpoints set at lineno.""" try: firstlineno, actual_lno = self.bdb_module.get_actual_bp(lineno) except BdbSourceError: return [] if firstlineno not in self: return [] code_bps = self[firstlineno] if actual_lno not in code_bps: return [] return [bp for bp in sorted(code_bps[actual_lno], key=attrgetter('number')) if bp.line == lineno]
python
def get_breakpoints(self, lineno): """Return the list of breakpoints set at lineno.""" try: firstlineno, actual_lno = self.bdb_module.get_actual_bp(lineno) except BdbSourceError: return [] if firstlineno not in self: return [] code_bps = self[firstlineno] if actual_lno not in code_bps: return [] return [bp for bp in sorted(code_bps[actual_lno], key=attrgetter('number')) if bp.line == lineno]
[ "def", "get_breakpoints", "(", "self", ",", "lineno", ")", ":", "try", ":", "firstlineno", ",", "actual_lno", "=", "self", ".", "bdb_module", ".", "get_actual_bp", "(", "lineno", ")", "except", "BdbSourceError", ":", "return", "[", "]", "if", "firstlineno", "not", "in", "self", ":", "return", "[", "]", "code_bps", "=", "self", "[", "firstlineno", "]", "if", "actual_lno", "not", "in", "code_bps", ":", "return", "[", "]", "return", "[", "bp", "for", "bp", "in", "sorted", "(", "code_bps", "[", "actual_lno", "]", ",", "key", "=", "attrgetter", "(", "'number'", ")", ")", "if", "bp", ".", "line", "==", "lineno", "]" ]
Return the list of breakpoints set at lineno.
[ "Return", "the", "list", "of", "breakpoints", "set", "at", "lineno", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L417-L429
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
Tracer.settrace
def settrace(self, do_set): """Set or remove the trace function.""" if do_set: sys.settrace(self.trace_dispatch) else: sys.settrace(None)
python
def settrace(self, do_set): """Set or remove the trace function.""" if do_set: sys.settrace(self.trace_dispatch) else: sys.settrace(None)
[ "def", "settrace", "(", "self", ",", "do_set", ")", ":", "if", "do_set", ":", "sys", ".", "settrace", "(", "self", ".", "trace_dispatch", ")", "else", ":", "sys", ".", "settrace", "(", "None", ")" ]
Set or remove the trace function.
[ "Set", "or", "remove", "the", "trace", "function", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L587-L592
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
Bdb.restart
def restart(self): """Restart the debugger after source code changes.""" _module_finder.reset() linecache.checkcache() for module_bpts in self.breakpoints.values(): module_bpts.reset()
python
def restart(self): """Restart the debugger after source code changes.""" _module_finder.reset() linecache.checkcache() for module_bpts in self.breakpoints.values(): module_bpts.reset()
[ "def", "restart", "(", "self", ")", ":", "_module_finder", ".", "reset", "(", ")", "linecache", ".", "checkcache", "(", ")", "for", "module_bpts", "in", "self", ".", "breakpoints", ".", "values", "(", ")", ":", "module_bpts", ".", "reset", "(", ")" ]
Restart the debugger after source code changes.
[ "Restart", "the", "debugger", "after", "source", "code", "changes", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L631-L636
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
Bdb.set_until
def set_until(self, frame, lineno=None): """Stop when the current line number in frame is greater than lineno or when returning from frame.""" if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, lineno)
python
def set_until(self, frame, lineno=None): """Stop when the current line number in frame is greater than lineno or when returning from frame.""" if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, lineno)
[ "def", "set_until", "(", "self", ",", "frame", ",", "lineno", "=", "None", ")", ":", "if", "lineno", "is", "None", ":", "lineno", "=", "frame", ".", "f_lineno", "+", "1", "self", ".", "_set_stopinfo", "(", "frame", ",", "lineno", ")" ]
Stop when the current line number in frame is greater than lineno or when returning from frame.
[ "Stop", "when", "the", "current", "line", "number", "in", "frame", "is", "greater", "than", "lineno", "or", "when", "returning", "from", "frame", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L713-L718
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
Bdb.set_trace
def set_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ # First disable tracing temporarily as set_trace() may be called while # tracing is in use. For example when called from a signal handler and # within a debugging session started with runcall(). self.settrace(False) if not frame: frame = sys._getframe().f_back frame.f_trace = self.trace_dispatch # Do not change botframe when the debuggee has been started from an # instance of Pdb with one of the family of run methods. self.reset(ignore_first_call_event=False, botframe=self.botframe) self.topframe = frame while frame: if frame is self.botframe: break botframe = frame frame = frame.f_back else: self.botframe = botframe # Must trace the bottom frame to disable tracing on termination, # see issue 13044. if not self.botframe.f_trace: self.botframe.f_trace = self.trace_dispatch self.settrace(True)
python
def set_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ # First disable tracing temporarily as set_trace() may be called while # tracing is in use. For example when called from a signal handler and # within a debugging session started with runcall(). self.settrace(False) if not frame: frame = sys._getframe().f_back frame.f_trace = self.trace_dispatch # Do not change botframe when the debuggee has been started from an # instance of Pdb with one of the family of run methods. self.reset(ignore_first_call_event=False, botframe=self.botframe) self.topframe = frame while frame: if frame is self.botframe: break botframe = frame frame = frame.f_back else: self.botframe = botframe # Must trace the bottom frame to disable tracing on termination, # see issue 13044. if not self.botframe.f_trace: self.botframe.f_trace = self.trace_dispatch self.settrace(True)
[ "def", "set_trace", "(", "self", ",", "frame", "=", "None", ")", ":", "# First disable tracing temporarily as set_trace() may be called while", "# tracing is in use. For example when called from a signal handler and", "# within a debugging session started with runcall().", "self", ".", "settrace", "(", "False", ")", "if", "not", "frame", ":", "frame", "=", "sys", ".", "_getframe", "(", ")", ".", "f_back", "frame", ".", "f_trace", "=", "self", ".", "trace_dispatch", "# Do not change botframe when the debuggee has been started from an", "# instance of Pdb with one of the family of run methods.", "self", ".", "reset", "(", "ignore_first_call_event", "=", "False", ",", "botframe", "=", "self", ".", "botframe", ")", "self", ".", "topframe", "=", "frame", "while", "frame", ":", "if", "frame", "is", "self", ".", "botframe", ":", "break", "botframe", "=", "frame", "frame", "=", "frame", ".", "f_back", "else", ":", "self", ".", "botframe", "=", "botframe", "# Must trace the bottom frame to disable tracing on termination,", "# see issue 13044.", "if", "not", "self", ".", "botframe", ".", "f_trace", ":", "self", ".", "botframe", ".", "f_trace", "=", "self", ".", "trace_dispatch", "self", ".", "settrace", "(", "True", ")" ]
Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame.
[ "Start", "debugging", "from", "frame", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L732-L763
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
Breakpoint.process_hit_event
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return False, False # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return False, False except Exception: # If the breakpoint condition evaluation fails, the most # conservative thing is to stop on the breakpoint. Don't # delete temporary, as another hint to the user. return True, False if self.ignore > 0: self.ignore -= 1 return False, False return True, True
python
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return False, False # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return False, False except Exception: # If the breakpoint condition evaluation fails, the most # conservative thing is to stop on the breakpoint. Don't # delete temporary, as another hint to the user. return True, False if self.ignore > 0: self.ignore -= 1 return False, False return True, True
[ "def", "process_hit_event", "(", "self", ",", "frame", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "False", ",", "False", "# Count every hit when breakpoint is enabled.", "self", ".", "hits", "+=", "1", "# A conditional breakpoint.", "if", "self", ".", "cond", ":", "try", ":", "if", "not", "eval_", "(", "self", ".", "cond", ",", "frame", ".", "f_globals", ",", "frame", ".", "f_locals", ")", ":", "return", "False", ",", "False", "except", "Exception", ":", "# If the breakpoint condition evaluation fails, the most", "# conservative thing is to stop on the breakpoint. Don't", "# delete temporary, as another hint to the user.", "return", "True", ",", "False", "if", "self", ".", "ignore", ">", "0", ":", "self", ".", "ignore", "-=", "1", "return", "False", ",", "False", "return", "True", ",", "True" ]
Return (stop_state, delete_temporary) at a breakpoint hit event.
[ "Return", "(", "stop_state", "delete_temporary", ")", "at", "a", "breakpoint", "hit", "event", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L1061-L1080
train
kamikaze/webdav
src/webdav/client.py
listdir
def listdir(directory): """Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names """ file_names = list() for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isdir(file_path): filename = f'{filename}{os.path.sep}' file_names.append(filename) return file_names
python
def listdir(directory): """Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names """ file_names = list() for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isdir(file_path): filename = f'{filename}{os.path.sep}' file_names.append(filename) return file_names
[ "def", "listdir", "(", "directory", ")", ":", "file_names", "=", "list", "(", ")", "for", "filename", "in", "os", ".", "listdir", "(", "directory", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "filename", "=", "f'{filename}{os.path.sep}'", "file_names", ".", "append", "(", "filename", ")", "return", "file_names" ]
Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names
[ "Returns", "list", "of", "nested", "files", "and", "directories", "for", "local", "directory", "by", "path" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L28-L40
train
kamikaze/webdav
src/webdav/client.py
get_options
def get_options(option_type, from_options): """Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary """ _options = dict() for key in option_type.keys: key_with_prefix = f'{option_type.prefix}{key}' if key not in from_options and key_with_prefix not in from_options: _options[key] = '' elif key in from_options: _options[key] = from_options.get(key) else: _options[key] = from_options.get(key_with_prefix) return _options
python
def get_options(option_type, from_options): """Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary """ _options = dict() for key in option_type.keys: key_with_prefix = f'{option_type.prefix}{key}' if key not in from_options and key_with_prefix not in from_options: _options[key] = '' elif key in from_options: _options[key] = from_options.get(key) else: _options[key] = from_options.get(key_with_prefix) return _options
[ "def", "get_options", "(", "option_type", ",", "from_options", ")", ":", "_options", "=", "dict", "(", ")", "for", "key", "in", "option_type", ".", "keys", ":", "key_with_prefix", "=", "f'{option_type.prefix}{key}'", "if", "key", "not", "in", "from_options", "and", "key_with_prefix", "not", "in", "from_options", ":", "_options", "[", "key", "]", "=", "''", "elif", "key", "in", "from_options", ":", "_options", "[", "key", "]", "=", "from_options", ".", "get", "(", "key", ")", "else", ":", "_options", "[", "key", "]", "=", "from_options", ".", "get", "(", "key_with_prefix", ")", "return", "_options" ]
Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary
[ "Extract", "options", "for", "specified", "option", "type", "from", "all", "options" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L43-L62
train
kamikaze/webdav
src/webdav/client.py
Client.get_headers
def get_headers(self, action, headers_ext=None): """Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action. """ if action in Client.http_header: try: headers = Client.http_header[action].copy() except AttributeError: headers = Client.http_header[action][:] else: headers = list() if headers_ext: headers.extend(headers_ext) if self.webdav.token: webdav_token = f'Authorization: OAuth {self.webdav.token}' headers.append(webdav_token) return dict([map(lambda s: s.strip(), i.split(':')) for i in headers])
python
def get_headers(self, action, headers_ext=None): """Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action. """ if action in Client.http_header: try: headers = Client.http_header[action].copy() except AttributeError: headers = Client.http_header[action][:] else: headers = list() if headers_ext: headers.extend(headers_ext) if self.webdav.token: webdav_token = f'Authorization: OAuth {self.webdav.token}' headers.append(webdav_token) return dict([map(lambda s: s.strip(), i.split(':')) for i in headers])
[ "def", "get_headers", "(", "self", ",", "action", ",", "headers_ext", "=", "None", ")", ":", "if", "action", "in", "Client", ".", "http_header", ":", "try", ":", "headers", "=", "Client", ".", "http_header", "[", "action", "]", ".", "copy", "(", ")", "except", "AttributeError", ":", "headers", "=", "Client", ".", "http_header", "[", "action", "]", "[", ":", "]", "else", ":", "headers", "=", "list", "(", ")", "if", "headers_ext", ":", "headers", ".", "extend", "(", "headers_ext", ")", "if", "self", ".", "webdav", ".", "token", ":", "webdav_token", "=", "f'Authorization: OAuth {self.webdav.token}'", "headers", ".", "append", "(", "webdav_token", ")", "return", "dict", "(", "[", "map", "(", "lambda", "s", ":", "s", ".", "strip", "(", ")", ",", "i", ".", "split", "(", "':'", ")", ")", "for", "i", "in", "headers", "]", ")" ]
Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action.
[ "Returns", "HTTP", "headers", "of", "specified", "WebDAV", "actions", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L107-L129
train
kamikaze/webdav
src/webdav/client.py
Client.execute_request
def execute_request(self, action, path, data=None, headers_ext=None): """Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request. """ response = self.session.request( method=Client.requests[action], url=self.get_url(path), auth=self.webdav.auth, headers=self.get_headers(action, headers_ext), timeout=self.timeout, data=data ) if response.status_code == 507: raise NotEnoughSpace() if 499 < response.status_code < 600: raise ServerException(url=self.get_url(path), code=response.status_code, message=response.content) if response.status_code >= 400: raise ResponseErrorCode(url=self.get_url(path), code=response.status_code, message=response.content) return response
python
def execute_request(self, action, path, data=None, headers_ext=None): """Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request. """ response = self.session.request( method=Client.requests[action], url=self.get_url(path), auth=self.webdav.auth, headers=self.get_headers(action, headers_ext), timeout=self.timeout, data=data ) if response.status_code == 507: raise NotEnoughSpace() if 499 < response.status_code < 600: raise ServerException(url=self.get_url(path), code=response.status_code, message=response.content) if response.status_code >= 400: raise ResponseErrorCode(url=self.get_url(path), code=response.status_code, message=response.content) return response
[ "def", "execute_request", "(", "self", ",", "action", ",", "path", ",", "data", "=", "None", ",", "headers_ext", "=", "None", ")", ":", "response", "=", "self", ".", "session", ".", "request", "(", "method", "=", "Client", ".", "requests", "[", "action", "]", ",", "url", "=", "self", ".", "get_url", "(", "path", ")", ",", "auth", "=", "self", ".", "webdav", ".", "auth", ",", "headers", "=", "self", ".", "get_headers", "(", "action", ",", "headers_ext", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "data", "=", "data", ")", "if", "response", ".", "status_code", "==", "507", ":", "raise", "NotEnoughSpace", "(", ")", "if", "499", "<", "response", ".", "status_code", "<", "600", ":", "raise", "ServerException", "(", "url", "=", "self", ".", "get_url", "(", "path", ")", ",", "code", "=", "response", ".", "status_code", ",", "message", "=", "response", ".", "content", ")", "if", "response", ".", "status_code", ">=", "400", ":", "raise", "ResponseErrorCode", "(", "url", "=", "self", ".", "get_url", "(", "path", ")", ",", "code", "=", "response", ".", "status_code", ",", "message", "=", "response", ".", "content", ")", "return", "response" ]
Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request.
[ "Generate", "request", "to", "WebDAV", "server", "for", "specified", "action", "and", "path", "and", "execute", "it", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L147-L172
train
kamikaze/webdav
src/webdav/client.py
Client.valid
def valid(self): """Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise. """ return True if self.webdav.valid() and self.proxy.valid() else False
python
def valid(self): """Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise. """ return True if self.webdav.valid() and self.proxy.valid() else False
[ "def", "valid", "(", "self", ")", ":", "return", "True", "if", "self", ".", "webdav", ".", "valid", "(", ")", "and", "self", ".", "proxy", ".", "valid", "(", ")", "else", "False" ]
Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise.
[ "Validates", "of", "WebDAV", "and", "proxy", "settings", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L227-L232
train
kamikaze/webdav
src/webdav/client.py
Client.list
def list(self, remote_path=root): """Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: path to remote directory. :return: list of nested file or directory names. """ directory_urn = Urn(remote_path, directory=True) if directory_urn.path() != Client.root: if not self.check(directory_urn.path()): raise RemoteResourceNotFound(directory_urn.path()) response = self.execute_request(action='list', path=directory_urn.quote()) urns = WebDavXmlUtils.parse_get_list_response(response.content) path = Urn.normalize_path(self.get_full_path(directory_urn)) return [urn.filename() for urn in urns if Urn.compare_path(path, urn.path()) is False]
python
def list(self, remote_path=root): """Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: path to remote directory. :return: list of nested file or directory names. """ directory_urn = Urn(remote_path, directory=True) if directory_urn.path() != Client.root: if not self.check(directory_urn.path()): raise RemoteResourceNotFound(directory_urn.path()) response = self.execute_request(action='list', path=directory_urn.quote()) urns = WebDavXmlUtils.parse_get_list_response(response.content) path = Urn.normalize_path(self.get_full_path(directory_urn)) return [urn.filename() for urn in urns if Urn.compare_path(path, urn.path()) is False]
[ "def", "list", "(", "self", ",", "remote_path", "=", "root", ")", ":", "directory_urn", "=", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", "if", "directory_urn", ".", "path", "(", ")", "!=", "Client", ".", "root", ":", "if", "not", "self", ".", "check", "(", "directory_urn", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "directory_urn", ".", "path", "(", ")", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'list'", ",", "path", "=", "directory_urn", ".", "quote", "(", ")", ")", "urns", "=", "WebDavXmlUtils", ".", "parse_get_list_response", "(", "response", ".", "content", ")", "path", "=", "Urn", ".", "normalize_path", "(", "self", ".", "get_full_path", "(", "directory_urn", ")", ")", "return", "[", "urn", ".", "filename", "(", ")", "for", "urn", "in", "urns", "if", "Urn", ".", "compare_path", "(", "path", ",", "urn", ".", "path", "(", ")", ")", "is", "False", "]" ]
Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: path to remote directory. :return: list of nested file or directory names.
[ "Returns", "list", "of", "nested", "files", "and", "directories", "for", "remote", "WebDAV", "directory", "by", "path", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPFIND" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L235-L251
train
kamikaze/webdav
src/webdav/client.py
Client.free
def free(self): """Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes. """ data = WebDavXmlUtils.create_free_space_request_content() response = self.execute_request(action='free', path='', data=data) return WebDavXmlUtils.parse_free_space_response(response.content, self.webdav.hostname)
python
def free(self): """Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes. """ data = WebDavXmlUtils.create_free_space_request_content() response = self.execute_request(action='free', path='', data=data) return WebDavXmlUtils.parse_free_space_response(response.content, self.webdav.hostname)
[ "def", "free", "(", "self", ")", ":", "data", "=", "WebDavXmlUtils", ".", "create_free_space_request_content", "(", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'free'", ",", "path", "=", "''", ",", "data", "=", "data", ")", "return", "WebDavXmlUtils", ".", "parse_free_space_response", "(", "response", ".", "content", ",", "self", ".", "webdav", ".", "hostname", ")" ]
Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes.
[ "Returns", "an", "amount", "of", "free", "space", "on", "remote", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPFIND" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L254-L262
train
kamikaze/webdav
src/webdav/client.py
Client.check
def check(self, remote_path=root): """Checks an existence of remote resource on WebDAV server by remote path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: (optional) path to resource on WebDAV server. Defaults is root directory of WebDAV. :return: True if resource is exist or False otherwise """ urn = Urn(remote_path) try: response = self.execute_request(action='check', path=urn.quote()) except ResponseErrorCode: return False if int(response.status_code) == 200: return True return False
python
def check(self, remote_path=root): """Checks an existence of remote resource on WebDAV server by remote path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: (optional) path to resource on WebDAV server. Defaults is root directory of WebDAV. :return: True if resource is exist or False otherwise """ urn = Urn(remote_path) try: response = self.execute_request(action='check', path=urn.quote()) except ResponseErrorCode: return False if int(response.status_code) == 200: return True return False
[ "def", "check", "(", "self", ",", "remote_path", "=", "root", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "try", ":", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'check'", ",", "path", "=", "urn", ".", "quote", "(", ")", ")", "except", "ResponseErrorCode", ":", "return", "False", "if", "int", "(", "response", ".", "status_code", ")", "==", "200", ":", "return", "True", "return", "False" ]
Checks an existence of remote resource on WebDAV server by remote path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: (optional) path to resource on WebDAV server. Defaults is root directory of WebDAV. :return: True if resource is exist or False otherwise
[ "Checks", "an", "existence", "of", "remote", "resource", "on", "WebDAV", "server", "by", "remote", "path", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#rfc", ".", "section", ".", "9", ".", "4" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L265-L281
train
kamikaze/webdav
src/webdav/client.py
Client.mkdir
def mkdir(self, remote_path): """Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise. """ directory_urn = Urn(remote_path, directory=True) try: response = self.execute_request(action='mkdir', path=directory_urn.quote()) return response.status_code in (200, 201) except ResponseErrorCode as e: if e.code == 405: return True raise
python
def mkdir(self, remote_path): """Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise. """ directory_urn = Urn(remote_path, directory=True) try: response = self.execute_request(action='mkdir', path=directory_urn.quote()) return response.status_code in (200, 201) except ResponseErrorCode as e: if e.code == 405: return True raise
[ "def", "mkdir", "(", "self", ",", "remote_path", ")", ":", "directory_urn", "=", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", "try", ":", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'mkdir'", ",", "path", "=", "directory_urn", ".", "quote", "(", ")", ")", "return", "response", ".", "status_code", "in", "(", "200", ",", "201", ")", "except", "ResponseErrorCode", "as", "e", ":", "if", "e", ".", "code", "==", "405", ":", "return", "True", "raise" ]
Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise.
[ "Makes", "new", "directory", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_MKCOL" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L284-L302
train
kamikaze/webdav
src/webdav/client.py
Client.download_from
def download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) response = self.execute_request(action='download', path=urn.quote()) buff.write(response.content)
python
def download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) response = self.execute_request(action='download', path=urn.quote()) buff.write(response.content)
[ "def", "download_from", "(", "self", ",", "buff", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn", ".", "path", "(", ")", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'download'", ",", "path", "=", "urn", ".", "quote", "(", ")", ")", "buff", ".", "write", "(", "response", ".", "content", ")" ]
Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server.
[ "Downloads", "file", "from", "WebDAV", "and", "writes", "it", "in", "buffer", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L305-L319
train
kamikaze/webdav
src/webdav/client.py
Client.download
def download(self, remote_path, local_path, progress=None): """Downloads remote resource from WebDAV and save it in local path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote resource for downloading can be file and directory. :param local_path: the path to save resource locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): self.download_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.download_file(local_path=local_path, remote_path=remote_path, progress=progress)
python
def download(self, remote_path, local_path, progress=None): """Downloads remote resource from WebDAV and save it in local path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote resource for downloading can be file and directory. :param local_path: the path to save resource locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): self.download_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.download_file(local_path=local_path, remote_path=remote_path, progress=progress)
[ "def", "download", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "self", ".", "download_directory", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "progress", "=", "progress", ")", "else", ":", "self", ".", "download_file", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "progress", "=", "progress", ")" ]
Downloads remote resource from WebDAV and save it in local path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote resource for downloading can be file and directory. :param local_path: the path to save resource locally. :param progress: progress function. Not supported now.
[ "Downloads", "remote", "resource", "from", "WebDAV", "and", "save", "it", "in", "local", "path", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#rfc", ".", "section", ".", "9", ".", "4" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L321-L333
train
kamikaze/webdav
src/webdav/client.py
Client.download_directory
def download_directory(self, remote_path, local_path, progress=None): """Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.exists(local_path): shutil.rmtree(local_path) os.makedirs(local_path) for resource_name in self.list(urn.path()): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.download(local_path=_local_path, remote_path=_remote_path, progress=progress)
python
def download_directory(self, remote_path, local_path, progress=None): """Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.exists(local_path): shutil.rmtree(local_path) os.makedirs(local_path) for resource_name in self.list(urn.path()): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.download(local_path=_local_path, remote_path=_remote_path, progress=progress)
[ "def", "download_directory", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "urn", "=", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", "if", "not", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "shutil", ".", "rmtree", "(", "local_path", ")", "os", ".", "makedirs", "(", "local_path", ")", "for", "resource_name", "in", "self", ".", "list", "(", "urn", ".", "path", "(", ")", ")", ":", "_remote_path", "=", "f'{urn.path()}{resource_name}'", "_local_path", "=", "os", ".", "path", ".", "join", "(", "local_path", ",", "resource_name", ")", "self", ".", "download", "(", "local_path", "=", "_local_path", ",", "remote_path", "=", "_remote_path", ",", "progress", "=", "progress", ")" ]
Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now.
[ "Downloads", "directory", "and", "downloads", "all", "nested", "files", "and", "directories", "from", "remote", "WebDAV", "to", "local", ".", "If", "there", "is", "something", "on", "local", "path", "it", "deletes", "directories", "and", "files", "then", "creates", "new", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L335-L355
train
kamikaze/webdav
src/webdav/client.py
Client.open
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """Downloads file from WebDAV server and saves it temprorary, then opens it for further manipulations. Has the same interface as built-in open() :param file: the path to remote file for opening. """ urn = Urn(file) urn_path = urn.path() remote_file_exists = self.check(urn_path) if not remote_file_exists: if 'r' in mode: raise RemoteResourceNotFound(urn_path) elif self.is_dir(urn_path): raise OptionNotValid(name='file', value=file) with tempfile.TemporaryDirectory() as temp_dir: local_path = f'{temp_dir}{os.path.sep}{file}' if remote_file_exists: self.download_file(file, local_path) else: if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) as f: yield f if 'w' in mode or 'a' in mode or 'x' in mode: self.upload_file(file, local_path)
python
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """Downloads file from WebDAV server and saves it temprorary, then opens it for further manipulations. Has the same interface as built-in open() :param file: the path to remote file for opening. """ urn = Urn(file) urn_path = urn.path() remote_file_exists = self.check(urn_path) if not remote_file_exists: if 'r' in mode: raise RemoteResourceNotFound(urn_path) elif self.is_dir(urn_path): raise OptionNotValid(name='file', value=file) with tempfile.TemporaryDirectory() as temp_dir: local_path = f'{temp_dir}{os.path.sep}{file}' if remote_file_exists: self.download_file(file, local_path) else: if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) as f: yield f if 'w' in mode or 'a' in mode or 'x' in mode: self.upload_file(file, local_path)
[ "def", "open", "(", "self", ",", "file", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ",", "closefd", "=", "True", ",", "opener", "=", "None", ")", ":", "urn", "=", "Urn", "(", "file", ")", "urn_path", "=", "urn", ".", "path", "(", ")", "remote_file_exists", "=", "self", ".", "check", "(", "urn_path", ")", "if", "not", "remote_file_exists", ":", "if", "'r'", "in", "mode", ":", "raise", "RemoteResourceNotFound", "(", "urn_path", ")", "elif", "self", ".", "is_dir", "(", "urn_path", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'file'", ",", "value", "=", "file", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "temp_dir", ":", "local_path", "=", "f'{temp_dir}{os.path.sep}{file}'", "if", "remote_file_exists", ":", "self", ".", "download_file", "(", "file", ",", "local_path", ")", "else", ":", "if", "(", "'w'", "in", "mode", "or", "'a'", "in", "mode", "or", "'x'", "in", "mode", ")", "and", "os", ".", "path", ".", "sep", "in", "local_path", ":", "os", ".", "makedirs", "(", "local_path", ".", "rsplit", "(", "os", ".", "path", ".", "sep", ",", "1", ")", "[", "0", "]", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "file", "=", "local_path", ",", "mode", "=", "mode", ",", "buffering", "=", "buffering", ",", "encoding", "=", "encoding", ",", "errors", "=", "errors", ",", "newline", "=", "newline", ",", "closefd", "=", "closefd", ",", "opener", "=", "opener", ")", "as", "f", ":", "yield", "f", "if", "'w'", "in", "mode", "or", "'a'", "in", "mode", "or", "'x'", "in", "mode", ":", "self", ".", "upload_file", "(", "file", ",", "local_path", ")" ]
Downloads file from WebDAV server and saves it temprorary, then opens it for further manipulations. Has the same interface as built-in open() :param file: the path to remote file for opening.
[ "Downloads", "file", "from", "WebDAV", "server", "and", "saves", "it", "temprorary", "then", "opens", "it", "for", "further", "manipulations", ".", "Has", "the", "same", "interface", "as", "built", "-", "in", "open", "()" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L359-L390
train
kamikaze/webdav
src/webdav/client.py
Client.download_file
def download_file(self, remote_path, local_path, progress=None): """Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) with open(local_path, 'wb') as local_file: response = self.execute_request('download', urn.quote()) for block in response.iter_content(1024): local_file.write(block)
python
def download_file(self, remote_path, local_path, progress=None): """Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) with open(local_path, 'wb') as local_file: response = self.execute_request('download', urn.quote()) for block in response.iter_content(1024): local_file.write(block)
[ "def", "download_file", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'local_path'", ",", "value", "=", "local_path", ")", "if", "os", ".", "path", ".", "sep", "in", "local_path", ":", "os", ".", "makedirs", "(", "local_path", ".", "rsplit", "(", "os", ".", "path", ".", "sep", ",", "1", ")", "[", "0", "]", ",", "exist_ok", "=", "True", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn", ".", "path", "(", ")", ")", "with", "open", "(", "local_path", ",", "'wb'", ")", "as", "local_file", ":", "response", "=", "self", ".", "execute_request", "(", "'download'", ",", "urn", ".", "quote", "(", ")", ")", "for", "block", "in", "response", ".", "iter_content", "(", "1024", ")", ":", "local_file", ".", "write", "(", "block", ")" ]
Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress function. Not supported now.
[ "Downloads", "file", "from", "WebDAV", "server", "and", "save", "it", "locally", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#rfc", ".", "section", ".", "9", ".", "4" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L393-L417
train
kamikaze/webdav
src/webdav/client.py
Client.download_sync
def download_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ self.download(local_path=local_path, remote_path=remote_path) if callback: callback()
python
def download_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ self.download(local_path=local_path, remote_path=remote_path) if callback: callback()
[ "def", "download_sync", "(", "self", ",", "remote_path", ",", "local_path", ",", "callback", "=", "None", ")", ":", "self", ".", "download", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ")", "if", "callback", ":", "callback", "(", ")" ]
Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete.
[ "Downloads", "remote", "resources", "from", "WebDAV", "server", "synchronously", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L419-L428
train
kamikaze/webdav
src/webdav/client.py
Client.download_async
def download_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.download_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
python
def download_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.download_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
[ "def", "download_async", "(", "self", ",", "remote_path", ",", "local_path", ",", "callback", "=", "None", ")", ":", "target", "=", "(", "lambda", ":", "self", ".", "download_sync", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "callback", "=", "callback", ")", ")", "threading", ".", "Thread", "(", "target", "=", "target", ")", ".", "start", "(", ")" ]
Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete.
[ "Downloads", "remote", "resources", "from", "WebDAV", "server", "asynchronously" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L430-L438
train
kamikaze/webdav
src/webdav/client.py
Client.upload_to
def upload_to(self, buff, remote_path): """Uploads file from buffer to remote path on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param buff: the buffer with content for file. :param remote_path: the path to save file remotely on WebDAV server. """ urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) self.execute_request(action='upload', path=urn.quote(), data=buff)
python
def upload_to(self, buff, remote_path): """Uploads file from buffer to remote path on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param buff: the buffer with content for file. :param remote_path: the path to save file remotely on WebDAV server. """ urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) self.execute_request(action='upload', path=urn.quote(), data=buff)
[ "def", "upload_to", "(", "self", ",", "buff", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "urn", ".", "is_dir", "(", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "parent", "(", ")", ")", ":", "raise", "RemoteParentNotFound", "(", "urn", ".", "path", "(", ")", ")", "self", ".", "execute_request", "(", "action", "=", "'upload'", ",", "path", "=", "urn", ".", "quote", "(", ")", ",", "data", "=", "buff", ")" ]
Uploads file from buffer to remote path on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param buff: the buffer with content for file. :param remote_path: the path to save file remotely on WebDAV server.
[ "Uploads", "file", "from", "buffer", "to", "remote", "path", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PUT" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L441-L455
train
kamikaze/webdav
src/webdav/client.py
Client.upload
def upload(self, remote_path, local_path, progress=None): """Uploads resource to remote path on WebDAV server. In case resource is directory it will upload all nested files and directories. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param progress: Progress function. Not supported now. """ if os.path.isdir(local_path): self.upload_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.upload_file(local_path=local_path, remote_path=remote_path)
python
def upload(self, remote_path, local_path, progress=None): """Uploads resource to remote path on WebDAV server. In case resource is directory it will upload all nested files and directories. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param progress: Progress function. Not supported now. """ if os.path.isdir(local_path): self.upload_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.upload_file(local_path=local_path, remote_path=remote_path)
[ "def", "upload", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "self", ".", "upload_directory", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "progress", "=", "progress", ")", "else", ":", "self", ".", "upload_file", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ")" ]
Uploads resource to remote path on WebDAV server. In case resource is directory it will upload all nested files and directories. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param progress: Progress function. Not supported now.
[ "Uploads", "resource", "to", "remote", "path", "on", "WebDAV", "server", ".", "In", "case", "resource", "is", "directory", "it", "will", "upload", "all", "nested", "files", "and", "directories", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PUT" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L457-L469
train
kamikaze/webdav
src/webdav/client.py
Client.upload_directory
def upload_directory(self, remote_path, local_path, progress=None): """Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) if self.check(urn.path()): self.clean(urn.path()) self.mkdir(remote_path) for resource_name in listdir(local_path): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.upload(local_path=_local_path, remote_path=_remote_path, progress=progress)
python
def upload_directory(self, remote_path, local_path, progress=None): """Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) if self.check(urn.path()): self.clean(urn.path()) self.mkdir(remote_path) for resource_name in listdir(local_path): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.upload(local_path=_local_path, remote_path=_remote_path, progress=progress)
[ "def", "upload_directory", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "urn", "=", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", "if", "not", "urn", ".", "is_dir", "(", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'local_path'", ",", "value", "=", "local_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "raise", "LocalResourceNotFound", "(", "local_path", ")", "if", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", ":", "self", ".", "clean", "(", "urn", ".", "path", "(", ")", ")", "self", ".", "mkdir", "(", "remote_path", ")", "for", "resource_name", "in", "listdir", "(", "local_path", ")", ":", "_remote_path", "=", "f'{urn.path()}{resource_name}'", "_local_path", "=", "os", ".", "path", ".", "join", "(", "local_path", ",", "resource_name", ")", "self", ".", "upload", "(", "local_path", "=", "_local_path", ",", "remote_path", "=", "_remote_path", ",", "progress", "=", "progress", ")" ]
Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now.
[ "Uploads", "directory", "to", "remote", "path", "on", "WebDAV", "server", ".", "In", "case", "directory", "is", "exist", "on", "remote", "server", "it", "will", "delete", "it", "and", "then", "upload", "directory", "with", "nested", "files", "and", "directories", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L471-L498
train
kamikaze/webdav
src/webdav/client.py
Client.upload_file
def upload_file(self, remote_path, local_path, progress=None): """Uploads file to remote path on WebDAV server. File should be 2Gb or less. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path to uploading file on WebDAV server. :param local_path: the path to local file for uploading. :param progress: Progress function. Not supported now. """ if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) with open(local_path, 'rb') as local_file: file_size = os.path.getsize(local_path) if file_size > self.large_size: raise ResourceTooBig(path=local_path, size=file_size, max_size=self.large_size) self.execute_request(action='upload', path=urn.quote(), data=local_file)
python
def upload_file(self, remote_path, local_path, progress=None): """Uploads file to remote path on WebDAV server. File should be 2Gb or less. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path to uploading file on WebDAV server. :param local_path: the path to local file for uploading. :param progress: Progress function. Not supported now. """ if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) with open(local_path, 'rb') as local_file: file_size = os.path.getsize(local_path) if file_size > self.large_size: raise ResourceTooBig(path=local_path, size=file_size, max_size=self.large_size) self.execute_request(action='upload', path=urn.quote(), data=local_file)
[ "def", "upload_file", "(", "self", ",", "remote_path", ",", "local_path", ",", "progress", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "raise", "LocalResourceNotFound", "(", "local_path", ")", "urn", "=", "Urn", "(", "remote_path", ")", "if", "urn", ".", "is_dir", "(", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remote_path'", ",", "value", "=", "remote_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "local_path", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'local_path'", ",", "value", "=", "local_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "parent", "(", ")", ")", ":", "raise", "RemoteParentNotFound", "(", "urn", ".", "path", "(", ")", ")", "with", "open", "(", "local_path", ",", "'rb'", ")", "as", "local_file", ":", "file_size", "=", "os", ".", "path", ".", "getsize", "(", "local_path", ")", "if", "file_size", ">", "self", ".", "large_size", ":", "raise", "ResourceTooBig", "(", "path", "=", "local_path", ",", "size", "=", "file_size", ",", "max_size", "=", "self", ".", "large_size", ")", "self", ".", "execute_request", "(", "action", "=", "'upload'", ",", "path", "=", "urn", ".", "quote", "(", ")", ",", "data", "=", "local_file", ")" ]
Uploads file to remote path on WebDAV server. File should be 2Gb or less. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path to uploading file on WebDAV server. :param local_path: the path to local file for uploading. :param progress: Progress function. Not supported now.
[ "Uploads", "file", "to", "remote", "path", "on", "WebDAV", "server", ".", "File", "should", "be", "2Gb", "or", "less", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PUT" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L501-L527
train
kamikaze/webdav
src/webdav/client.py
Client.upload_sync
def upload_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ self.upload(local_path=local_path, remote_path=remote_path) if callback: callback()
python
def upload_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ self.upload(local_path=local_path, remote_path=remote_path) if callback: callback()
[ "def", "upload_sync", "(", "self", ",", "remote_path", ",", "local_path", ",", "callback", "=", "None", ")", ":", "self", ".", "upload", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ")", "if", "callback", ":", "callback", "(", ")" ]
Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete.
[ "Uploads", "resource", "to", "remote", "path", "on", "WebDAV", "server", "synchronously", ".", "In", "case", "resource", "is", "directory", "it", "will", "upload", "all", "nested", "files", "and", "directories", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L529-L540
train
kamikaze/webdav
src/webdav/client.py
Client.upload_async
def upload_async(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
python
def upload_async(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
[ "def", "upload_async", "(", "self", ",", "remote_path", ",", "local_path", ",", "callback", "=", "None", ")", ":", "target", "=", "(", "lambda", ":", "self", ".", "upload_sync", "(", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ",", "callback", "=", "callback", ")", ")", "threading", ".", "Thread", "(", "target", "=", "target", ")", ".", "start", "(", ")" ]
Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete.
[ "Uploads", "resource", "to", "remote", "path", "on", "WebDAV", "server", "asynchronously", ".", "In", "case", "resource", "is", "directory", "it", "will", "upload", "all", "nested", "files", "and", "directories", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L542-L551
train
kamikaze/webdav
src/webdav/client.py
Client.copy
def copy(self, remote_path_from, remote_path_to): """Copies resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY :param remote_path_from: the path to resource which will be copied, :param remote_path_to: the path where resource will be copied. """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' self.execute_request(action='copy', path=urn_from.quote(), headers_ext=[header_destination])
python
def copy(self, remote_path_from, remote_path_to): """Copies resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY :param remote_path_from: the path to resource which will be copied, :param remote_path_to: the path where resource will be copied. """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' self.execute_request(action='copy', path=urn_from.quote(), headers_ext=[header_destination])
[ "def", "copy", "(", "self", ",", "remote_path_from", ",", "remote_path_to", ")", ":", "urn_from", "=", "Urn", "(", "remote_path_from", ")", "if", "not", "self", ".", "check", "(", "urn_from", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn_from", ".", "path", "(", ")", ")", "urn_to", "=", "Urn", "(", "remote_path_to", ")", "if", "not", "self", ".", "check", "(", "urn_to", ".", "parent", "(", ")", ")", ":", "raise", "RemoteParentNotFound", "(", "urn_to", ".", "path", "(", ")", ")", "header_destination", "=", "f'Destination: {self.get_full_path(urn_to)}'", "self", ".", "execute_request", "(", "action", "=", "'copy'", ",", "path", "=", "urn_from", ".", "quote", "(", ")", ",", "headers_ext", "=", "[", "header_destination", "]", ")" ]
Copies resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY :param remote_path_from: the path to resource which will be copied, :param remote_path_to: the path where resource will be copied.
[ "Copies", "resource", "from", "one", "place", "to", "another", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_COPY" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L554-L570
train
kamikaze/webdav
src/webdav/client.py
Client.move
def move(self, remote_path_from, remote_path_to, overwrite=False): """Moves resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE :param remote_path_from: the path to resource which will be moved, :param remote_path_to: the path where resource will be moved. :param overwrite: (optional) the flag, overwrite file if it exists. Defaults is False """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' header_overwrite = f'Overwrite: {"T" if overwrite else "F"}' self.execute_request(action='move', path=urn_from.quote(), headers_ext=[header_destination, header_overwrite])
python
def move(self, remote_path_from, remote_path_to, overwrite=False): """Moves resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE :param remote_path_from: the path to resource which will be moved, :param remote_path_to: the path where resource will be moved. :param overwrite: (optional) the flag, overwrite file if it exists. Defaults is False """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' header_overwrite = f'Overwrite: {"T" if overwrite else "F"}' self.execute_request(action='move', path=urn_from.quote(), headers_ext=[header_destination, header_overwrite])
[ "def", "move", "(", "self", ",", "remote_path_from", ",", "remote_path_to", ",", "overwrite", "=", "False", ")", ":", "urn_from", "=", "Urn", "(", "remote_path_from", ")", "if", "not", "self", ".", "check", "(", "urn_from", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn_from", ".", "path", "(", ")", ")", "urn_to", "=", "Urn", "(", "remote_path_to", ")", "if", "not", "self", ".", "check", "(", "urn_to", ".", "parent", "(", ")", ")", ":", "raise", "RemoteParentNotFound", "(", "urn_to", ".", "path", "(", ")", ")", "header_destination", "=", "f'Destination: {self.get_full_path(urn_to)}'", "header_overwrite", "=", "f'Overwrite: {\"T\" if overwrite else \"F\"}'", "self", ".", "execute_request", "(", "action", "=", "'move'", ",", "path", "=", "urn_from", ".", "quote", "(", ")", ",", "headers_ext", "=", "[", "header_destination", ",", "header_overwrite", "]", ")" ]
Moves resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE :param remote_path_from: the path to resource which will be moved, :param remote_path_to: the path where resource will be moved. :param overwrite: (optional) the flag, overwrite file if it exists. Defaults is False
[ "Moves", "resource", "from", "one", "place", "to", "another", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_MOVE" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L573-L591
train
kamikaze/webdav
src/webdav/client.py
Client.clean
def clean(self, remote_path): """Cleans (Deletes) a remote resource on WebDAV server. The name of method is not changed for back compatibility with original library. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_DELETE :param remote_path: the remote resource whisch will be deleted. """ urn = Urn(remote_path) self.execute_request(action='clean', path=urn.quote())
python
def clean(self, remote_path): """Cleans (Deletes) a remote resource on WebDAV server. The name of method is not changed for back compatibility with original library. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_DELETE :param remote_path: the remote resource whisch will be deleted. """ urn = Urn(remote_path) self.execute_request(action='clean', path=urn.quote())
[ "def", "clean", "(", "self", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "self", ".", "execute_request", "(", "action", "=", "'clean'", ",", "path", "=", "urn", ".", "quote", "(", ")", ")" ]
Cleans (Deletes) a remote resource on WebDAV server. The name of method is not changed for back compatibility with original library. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_DELETE :param remote_path: the remote resource whisch will be deleted.
[ "Cleans", "(", "Deletes", ")", "a", "remote", "resource", "on", "WebDAV", "server", ".", "The", "name", "of", "method", "is", "not", "changed", "for", "back", "compatibility", "with", "original", "library", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_DELETE" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L594-L602
train
kamikaze/webdav
src/webdav/client.py
Client.info
def info(self, remote_path): """Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ urn = Urn(remote_path) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_info_response(content=response.content, path=path, hostname=self.webdav.hostname)
python
def info(self, remote_path): """Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ urn = Urn(remote_path) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_info_response(content=response.content, path=path, hostname=self.webdav.hostname)
[ "def", "info", "(", "self", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", "and", "not", "self", ".", "check", "(", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "remote_path", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'info'", ",", "path", "=", "urn", ".", "quote", "(", ")", ")", "path", "=", "self", ".", "get_full_path", "(", "urn", ")", "return", "WebDavXmlUtils", ".", "parse_info_response", "(", "content", "=", "response", ".", "content", ",", "path", "=", "path", ",", "hostname", "=", "self", ".", "webdav", ".", "hostname", ")" ]
Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification.
[ "Gets", "information", "about", "resource", "on", "WebDAV", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPFIND" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L605-L622
train
kamikaze/webdav
src/webdav/client.py
Client.is_dir
def is_dir(self, remote_path): """Checks is the remote resource directory. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: True in case the remote resource is directory and False otherwise. """ urn = Urn(remote_path) parent_urn = Urn(urn.parent()) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=parent_urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_is_dir_response(content=response.content, path=path, hostname=self.webdav.hostname)
python
def is_dir(self, remote_path): """Checks is the remote resource directory. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: True in case the remote resource is directory and False otherwise. """ urn = Urn(remote_path) parent_urn = Urn(urn.parent()) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=parent_urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_is_dir_response(content=response.content, path=path, hostname=self.webdav.hostname)
[ "def", "is_dir", "(", "self", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "parent_urn", "=", "Urn", "(", "urn", ".", "parent", "(", ")", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", "and", "not", "self", ".", "check", "(", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "remote_path", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'info'", ",", "path", "=", "parent_urn", ".", "quote", "(", ")", ")", "path", "=", "self", ".", "get_full_path", "(", "urn", ")", "return", "WebDavXmlUtils", ".", "parse_is_dir_response", "(", "content", "=", "response", ".", "content", ",", "path", "=", "path", ",", "hostname", "=", "self", ".", "webdav", ".", "hostname", ")" ]
Checks is the remote resource directory. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: True in case the remote resource is directory and False otherwise.
[ "Checks", "is", "the", "remote", "resource", "directory", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPFIND" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L625-L639
train
kamikaze/webdav
src/webdav/client.py
Client.get_property
def get_property(self, remote_path, option): """Gets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set. :return: the value of property or None if property is not found. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_get_property_request_content(option) response = self.execute_request(action='get_property', path=urn.quote(), data=data) return WebDavXmlUtils.parse_get_property_response(response.content, option['name'])
python
def get_property(self, remote_path, option): """Gets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set. :return: the value of property or None if property is not found. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_get_property_request_content(option) response = self.execute_request(action='get_property', path=urn.quote(), data=data) return WebDavXmlUtils.parse_get_property_response(response.content, option['name'])
[ "def", "get_property", "(", "self", ",", "remote_path", ",", "option", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn", ".", "path", "(", ")", ")", "data", "=", "WebDavXmlUtils", ".", "create_get_property_request_content", "(", "option", ")", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'get_property'", ",", "path", "=", "urn", ".", "quote", "(", ")", ",", "data", "=", "data", ")", "return", "WebDavXmlUtils", ".", "parse_get_property_response", "(", "response", ".", "content", ",", "option", "[", "'name'", "]", ")" ]
Gets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set. :return: the value of property or None if property is not found.
[ "Gets", "metadata", "property", "of", "remote", "resource", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPFIND" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L642-L658
train
kamikaze/webdav
src/webdav/client.py
Client.set_property
def set_property(self, remote_path, option): """Sets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ self.set_property_batch(remote_path=remote_path, option=[option])
python
def set_property(self, remote_path, option): """Sets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ self.set_property_batch(remote_path=remote_path, option=[option])
[ "def", "set_property", "(", "self", ",", "remote_path", ",", "option", ")", ":", "self", ".", "set_property_batch", "(", "remote_path", "=", "remote_path", ",", "option", "=", "[", "option", "]", ")" ]
Sets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string.
[ "Sets", "metadata", "property", "of", "remote", "resource", "on", "WebDAV", "server", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPPATCH" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L661-L671
train
kamikaze/webdav
src/webdav/client.py
Client.set_property_batch
def set_property_batch(self, remote_path, option): """Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_set_property_batch_request_content(option) self.execute_request(action='set_property', path=urn.quote(), data=data)
python
def set_property_batch(self, remote_path, option): """Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_set_property_batch_request_content(option) self.execute_request(action='set_property', path=urn.quote(), data=data)
[ "def", "set_property_batch", "(", "self", ",", "remote_path", ",", "option", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "not", "self", ".", "check", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "RemoteResourceNotFound", "(", "urn", ".", "path", "(", ")", ")", "data", "=", "WebDavXmlUtils", ".", "create_set_property_batch_request_content", "(", "option", ")", "self", ".", "execute_request", "(", "action", "=", "'set_property'", ",", "path", "=", "urn", ".", "quote", "(", ")", ",", "data", "=", "data", ")" ]
Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string.
[ "Sets", "batch", "metadata", "properties", "of", "remote", "resource", "on", "WebDAV", "server", "in", "batch", ".", "More", "information", "you", "can", "find", "by", "link", "http", ":", "//", "webdav", ".", "org", "/", "specs", "/", "rfc4918", ".", "html#METHOD_PROPPATCH" ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L674-L689
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.parse_get_list_response
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. """ try: tree = etree.fromstring(content) hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall('.//{DAV:}href')] return [Urn(hree) for hree in hrees] except etree.XMLSyntaxError: return list()
python
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. """ try: tree = etree.fromstring(content) hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall('.//{DAV:}href')] return [Urn(hree) for hree in hrees] except etree.XMLSyntaxError: return list()
[ "def", "parse_get_list_response", "(", "content", ")", ":", "try", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "hrees", "=", "[", "Urn", ".", "separate", "+", "unquote", "(", "urlsplit", "(", "hree", ".", "text", ")", ".", "path", ")", "for", "hree", "in", "tree", ".", "findall", "(", "'.//{DAV:}href'", ")", "]", "return", "[", "Urn", "(", "hree", ")", "for", "hree", "in", "hrees", "]", "except", "etree", ".", "XMLSyntaxError", ":", "return", "list", "(", ")" ]
Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names.
[ "Parses", "of", "response", "content", "XML", "from", "WebDAV", "server", "and", "extract", "file", "and", "directory", "names", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L852-L863
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.create_free_space_request_content
def create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'quota-available-bytes') etree.SubElement(prop, 'quota-used-bytes') tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
python
def create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'quota-available-bytes') etree.SubElement(prop, 'quota-used-bytes') tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
[ "def", "create_free_space_request_content", "(", ")", ":", "root", "=", "etree", ".", "Element", "(", "'propfind'", ",", "xmlns", "=", "'DAV:'", ")", "prop", "=", "etree", ".", "SubElement", "(", "root", ",", "'prop'", ")", "etree", ".", "SubElement", "(", "prop", ",", "'quota-available-bytes'", ")", "etree", ".", "SubElement", "(", "prop", ",", "'quota-used-bytes'", ")", "tree", "=", "etree", ".", "ElementTree", "(", "root", ")", "return", "WebDavXmlUtils", ".", "etree_to_string", "(", "tree", ")" ]
Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content.
[ "Creates", "an", "XML", "for", "requesting", "of", "free", "space", "on", "remote", "WebDAV", "server", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L866-L876
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.parse_free_space_response
def parse_free_space_response(content, hostname): """Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes. """ try: tree = etree.fromstring(content) node = tree.find('.//{DAV:}quota-available-bytes') if node is not None: return int(node.text) else: raise MethodNotSupported(name='free', server=hostname) except TypeError: raise MethodNotSupported(name='free', server=hostname) except etree.XMLSyntaxError: return str()
python
def parse_free_space_response(content, hostname): """Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes. """ try: tree = etree.fromstring(content) node = tree.find('.//{DAV:}quota-available-bytes') if node is not None: return int(node.text) else: raise MethodNotSupported(name='free', server=hostname) except TypeError: raise MethodNotSupported(name='free', server=hostname) except etree.XMLSyntaxError: return str()
[ "def", "parse_free_space_response", "(", "content", ",", "hostname", ")", ":", "try", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "node", "=", "tree", ".", "find", "(", "'.//{DAV:}quota-available-bytes'", ")", "if", "node", "is", "not", "None", ":", "return", "int", "(", "node", ".", "text", ")", "else", ":", "raise", "MethodNotSupported", "(", "name", "=", "'free'", ",", "server", "=", "hostname", ")", "except", "TypeError", ":", "raise", "MethodNotSupported", "(", "name", "=", "'free'", ",", "server", "=", "hostname", ")", "except", "etree", ".", "XMLSyntaxError", ":", "return", "str", "(", ")" ]
Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes.
[ "Parses", "of", "response", "content", "XML", "from", "WebDAV", "server", "and", "extract", "an", "amount", "of", "free", "space", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L879-L896
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.parse_info_response
def parse_info_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) find_attributes = { 'created': './/{DAV:}creationdate', 'name': './/{DAV:}displayname', 'size': './/{DAV:}getcontentlength', 'modified': './/{DAV:}getlastmodified' } info = dict() for (name, value) in find_attributes.items(): info[name] = response.findtext(value) return info
python
def parse_info_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) find_attributes = { 'created': './/{DAV:}creationdate', 'name': './/{DAV:}displayname', 'size': './/{DAV:}getcontentlength', 'modified': './/{DAV:}getlastmodified' } info = dict() for (name, value) in find_attributes.items(): info[name] = response.findtext(value) return info
[ "def", "parse_info_response", "(", "content", ",", "path", ",", "hostname", ")", ":", "response", "=", "WebDavXmlUtils", ".", "extract_response_for_path", "(", "content", "=", "content", ",", "path", "=", "path", ",", "hostname", "=", "hostname", ")", "find_attributes", "=", "{", "'created'", ":", "'.//{DAV:}creationdate'", ",", "'name'", ":", "'.//{DAV:}displayname'", ",", "'size'", ":", "'.//{DAV:}getcontentlength'", ",", "'modified'", ":", "'.//{DAV:}getlastmodified'", "}", "info", "=", "dict", "(", ")", "for", "(", "name", ",", "value", ")", "in", "find_attributes", ".", "items", "(", ")", ":", "info", "[", "name", "]", "=", "response", ".", "findtext", "(", "value", ")", "return", "info" ]
Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification.
[ "Parses", "of", "response", "content", "XML", "from", "WebDAV", "server", "and", "extract", "an", "information", "about", "resource", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L899-L921
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.parse_is_dir_response
def parse_is_dir_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: True in case the remote resource is directory and False otherwise. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) resource_type = response.find('.//{DAV:}resourcetype') if resource_type is None: raise MethodNotSupported(name='is_dir', server=hostname) dir_type = resource_type.find('{DAV:}collection') return dir_type is not None
python
def parse_is_dir_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: True in case the remote resource is directory and False otherwise. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) resource_type = response.find('.//{DAV:}resourcetype') if resource_type is None: raise MethodNotSupported(name='is_dir', server=hostname) dir_type = resource_type.find('{DAV:}collection') return dir_type is not None
[ "def", "parse_is_dir_response", "(", "content", ",", "path", ",", "hostname", ")", ":", "response", "=", "WebDavXmlUtils", ".", "extract_response_for_path", "(", "content", "=", "content", ",", "path", "=", "path", ",", "hostname", "=", "hostname", ")", "resource_type", "=", "response", ".", "find", "(", "'.//{DAV:}resourcetype'", ")", "if", "resource_type", "is", "None", ":", "raise", "MethodNotSupported", "(", "name", "=", "'is_dir'", ",", "server", "=", "hostname", ")", "dir_type", "=", "resource_type", ".", "find", "(", "'{DAV:}collection'", ")", "return", "dir_type", "is", "not", "None" ]
Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: True in case the remote resource is directory and False otherwise.
[ "Parses", "of", "response", "content", "XML", "from", "WebDAV", "server", "and", "extract", "an", "information", "about", "resource", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L924-L940
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.create_get_property_request_content
def create_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, option.get('name', ''), xmlns=option.get('namespace', '')) tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
python
def create_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, option.get('name', ''), xmlns=option.get('namespace', '')) tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
[ "def", "create_get_property_request_content", "(", "option", ")", ":", "root", "=", "etree", ".", "Element", "(", "'propfind'", ",", "xmlns", "=", "'DAV:'", ")", "prop", "=", "etree", ".", "SubElement", "(", "root", ",", "'prop'", ")", "etree", ".", "SubElement", "(", "prop", ",", "option", ".", "get", "(", "'name'", ",", "''", ")", ",", "xmlns", "=", "option", ".", "get", "(", "'namespace'", ",", "''", ")", ")", "tree", "=", "etree", ".", "ElementTree", "(", "root", ")", "return", "WebDavXmlUtils", ".", "etree_to_string", "(", "tree", ")" ]
Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content.
[ "Creates", "an", "XML", "for", "requesting", "of", "getting", "a", "property", "value", "of", "remote", "WebDAV", "resource", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L943-L955
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.parse_get_property_response
def parse_get_property_response(content, name): """Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise. """ tree = etree.fromstring(content) return tree.xpath('//*[local-name() = $name]', name=name)[0].text
python
def parse_get_property_response(content, name): """Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise. """ tree = etree.fromstring(content) return tree.xpath('//*[local-name() = $name]', name=name)[0].text
[ "def", "parse_get_property_response", "(", "content", ",", "name", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "return", "tree", ".", "xpath", "(", "'//*[local-name() = $name]'", ",", "name", "=", "name", ")", "[", "0", "]", ".", "text" ]
Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise.
[ "Parses", "of", "response", "content", "XML", "from", "WebDAV", "server", "for", "getting", "metadata", "property", "value", "for", "some", "resource", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L958-L966
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.create_set_property_batch_request_content
def create_set_property_batch_request_content(options): """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content. """ root_node = etree.Element('propertyupdate', xmlns='DAV:') set_node = etree.SubElement(root_node, 'set') prop_node = etree.SubElement(set_node, 'prop') for option in options: opt_node = etree.SubElement(prop_node, option['name'], xmlns=option.get('namespace', '')) opt_node.text = option.get('value', '') tree = etree.ElementTree(root_node) return WebDavXmlUtils.etree_to_string(tree)
python
def create_set_property_batch_request_content(options): """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content. """ root_node = etree.Element('propertyupdate', xmlns='DAV:') set_node = etree.SubElement(root_node, 'set') prop_node = etree.SubElement(set_node, 'prop') for option in options: opt_node = etree.SubElement(prop_node, option['name'], xmlns=option.get('namespace', '')) opt_node.text = option.get('value', '') tree = etree.ElementTree(root_node) return WebDavXmlUtils.etree_to_string(tree)
[ "def", "create_set_property_batch_request_content", "(", "options", ")", ":", "root_node", "=", "etree", ".", "Element", "(", "'propertyupdate'", ",", "xmlns", "=", "'DAV:'", ")", "set_node", "=", "etree", ".", "SubElement", "(", "root_node", ",", "'set'", ")", "prop_node", "=", "etree", ".", "SubElement", "(", "set_node", ",", "'prop'", ")", "for", "option", "in", "options", ":", "opt_node", "=", "etree", ".", "SubElement", "(", "prop_node", ",", "option", "[", "'name'", "]", ",", "xmlns", "=", "option", ".", "get", "(", "'namespace'", ",", "''", ")", ")", "opt_node", ".", "text", "=", "option", ".", "get", "(", "'value'", ",", "''", ")", "tree", "=", "etree", ".", "ElementTree", "(", "root_node", ")", "return", "WebDavXmlUtils", ".", "etree_to_string", "(", "tree", ")" ]
Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content.
[ "Creates", "an", "XML", "for", "requesting", "of", "setting", "a", "property", "values", "for", "remote", "WebDAV", "resource", "in", "batch", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L969-L985
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.etree_to_string
def etree_to_string(tree): """Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML. """ buff = BytesIO() tree.write(buff, xml_declaration=True, encoding='UTF-8') return buff.getvalue()
python
def etree_to_string(tree): """Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML. """ buff = BytesIO() tree.write(buff, xml_declaration=True, encoding='UTF-8') return buff.getvalue()
[ "def", "etree_to_string", "(", "tree", ")", ":", "buff", "=", "BytesIO", "(", ")", "tree", ".", "write", "(", "buff", ",", "xml_declaration", "=", "True", ",", "encoding", "=", "'UTF-8'", ")", "return", "buff", ".", "getvalue", "(", ")" ]
Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML.
[ "Creates", "string", "from", "lxml", ".", "etree", ".", "ElementTree", "with", "XML", "declaration", "and", "UTF", "-", "8", "encoding", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L988-L996
train
kamikaze/webdav
src/webdav/client.py
WebDavXmlUtils.extract_response_for_path
def extract_response_for_path(content, path, hostname): """Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path. """ try: tree = etree.fromstring(content) responses = tree.findall('{DAV:}response') n_path = Urn.normalize_path(path) for resp in responses: href = resp.findtext('{DAV:}href') if Urn.compare_path(n_path, href) is True: return resp raise RemoteResourceNotFound(path) except etree.XMLSyntaxError: raise MethodNotSupported(name='is_dir', server=hostname)
python
def extract_response_for_path(content, path, hostname): """Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path. """ try: tree = etree.fromstring(content) responses = tree.findall('{DAV:}response') n_path = Urn.normalize_path(path) for resp in responses: href = resp.findtext('{DAV:}href') if Urn.compare_path(n_path, href) is True: return resp raise RemoteResourceNotFound(path) except etree.XMLSyntaxError: raise MethodNotSupported(name='is_dir', server=hostname)
[ "def", "extract_response_for_path", "(", "content", ",", "path", ",", "hostname", ")", ":", "try", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "responses", "=", "tree", ".", "findall", "(", "'{DAV:}response'", ")", "n_path", "=", "Urn", ".", "normalize_path", "(", "path", ")", "for", "resp", "in", "responses", ":", "href", "=", "resp", ".", "findtext", "(", "'{DAV:}href'", ")", "if", "Urn", ".", "compare_path", "(", "n_path", ",", "href", ")", "is", "True", ":", "return", "resp", "raise", "RemoteResourceNotFound", "(", "path", ")", "except", "etree", ".", "XMLSyntaxError", ":", "raise", "MethodNotSupported", "(", "name", "=", "'is_dir'", ",", "server", "=", "hostname", ")" ]
Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path.
[ "Extracts", "single", "response", "for", "specified", "remote", "resource", "." ]
6facff7224023d3e28c8e1592f3c58401c91a0e6
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L999-L1020
train
Nukesor/pueue
pueue/daemon/files.py
cleanup
def cleanup(config_dir): """Remove temporary stderr and stdout files as well as the daemon socket.""" stdout_path = os.path.join(config_dir, 'pueue.stdout') stderr_path = os.path.join(config_dir, 'pueue.stderr') if os._exists(stdout_path): os.remove(stdout_path) if os._exists(stderr_path): os.remove(stderr_path) socketPath = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socketPath): os.remove(socketPath)
python
def cleanup(config_dir): """Remove temporary stderr and stdout files as well as the daemon socket.""" stdout_path = os.path.join(config_dir, 'pueue.stdout') stderr_path = os.path.join(config_dir, 'pueue.stderr') if os._exists(stdout_path): os.remove(stdout_path) if os._exists(stderr_path): os.remove(stderr_path) socketPath = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socketPath): os.remove(socketPath)
[ "def", "cleanup", "(", "config_dir", ")", ":", "stdout_path", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "'pueue.stdout'", ")", "stderr_path", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "'pueue.stderr'", ")", "if", "os", ".", "_exists", "(", "stdout_path", ")", ":", "os", ".", "remove", "(", "stdout_path", ")", "if", "os", ".", "_exists", "(", "stderr_path", ")", ":", "os", ".", "remove", "(", "stderr_path", ")", "socketPath", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "'pueue.sock'", ")", "if", "os", ".", "path", ".", "exists", "(", "socketPath", ")", ":", "os", ".", "remove", "(", "socketPath", ")" ]
Remove temporary stderr and stdout files as well as the daemon socket.
[ "Remove", "temporary", "stderr", "and", "stdout", "files", "as", "well", "as", "the", "daemon", "socket", "." ]
f1d276360454d4dd2738658a13df1e20caa4b926
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/files.py#L5-L16
train
Nukesor/pueue
pueue/daemon/files.py
get_descriptor_output
def get_descriptor_output(descriptor, key, handler=None): """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError. """ line = 'stub' lines = '' while line != '': try: line = descriptor.readline() lines += line except UnicodeDecodeError: error_msg = "Error while decoding output of process {}".format(key) if handler: handler.logger.error("{} with command {}".format( error_msg, handler.queue[key]['command'])) lines += error_msg + '\n' return lines.replace('\n', '\n ')
python
def get_descriptor_output(descriptor, key, handler=None): """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError. """ line = 'stub' lines = '' while line != '': try: line = descriptor.readline() lines += line except UnicodeDecodeError: error_msg = "Error while decoding output of process {}".format(key) if handler: handler.logger.error("{} with command {}".format( error_msg, handler.queue[key]['command'])) lines += error_msg + '\n' return lines.replace('\n', '\n ')
[ "def", "get_descriptor_output", "(", "descriptor", ",", "key", ",", "handler", "=", "None", ")", ":", "line", "=", "'stub'", "lines", "=", "''", "while", "line", "!=", "''", ":", "try", ":", "line", "=", "descriptor", ".", "readline", "(", ")", "lines", "+=", "line", "except", "UnicodeDecodeError", ":", "error_msg", "=", "\"Error while decoding output of process {}\"", ".", "format", "(", "key", ")", "if", "handler", ":", "handler", ".", "logger", ".", "error", "(", "\"{} with command {}\"", ".", "format", "(", "error_msg", ",", "handler", ".", "queue", "[", "key", "]", "[", "'command'", "]", ")", ")", "lines", "+=", "error_msg", "+", "'\\n'", "return", "lines", ".", "replace", "(", "'\\n'", ",", "'\\n '", ")" ]
Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError.
[ "Get", "the", "descriptor", "output", "and", "handle", "incorrect", "UTF", "-", "8", "encoding", "of", "subprocess", "logs", "." ]
f1d276360454d4dd2738658a13df1e20caa4b926
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/files.py#L19-L38
train
MediaFire/mediafire-python-open-sdk
mediafire/media/conversion_server_client.py
ConversionServerClient.request
def request(self, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): """Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content """ if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ 'quickkey': quickkey, 'doc_type': doc_type, 'page': page, 'output': output, 'size_id': size_id, 'metadata': metadata, 'request_conversion_only': request_conversion_only }) url = API_ENDPOINT + '?' + hash_ + '&' + urlencode(query) response = self.http.get(url, stream=True) if response.status_code == 204: raise ConversionServerError("Unable to fulfill request. " "The document will not be converted.", response.status_code) response.raise_for_status() if response.headers['content-type'] == 'application/json': return response.json() return response
python
def request(self, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): """Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content """ if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ 'quickkey': quickkey, 'doc_type': doc_type, 'page': page, 'output': output, 'size_id': size_id, 'metadata': metadata, 'request_conversion_only': request_conversion_only }) url = API_ENDPOINT + '?' + hash_ + '&' + urlencode(query) response = self.http.get(url, stream=True) if response.status_code == 204: raise ConversionServerError("Unable to fulfill request. " "The document will not be converted.", response.status_code) response.raise_for_status() if response.headers['content-type'] == 'application/json': return response.json() return response
[ "def", "request", "(", "self", ",", "hash_", ",", "quickkey", ",", "doc_type", ",", "page", "=", "None", ",", "output", "=", "None", ",", "size_id", "=", "None", ",", "metadata", "=", "None", ",", "request_conversion_only", "=", "None", ")", ":", "if", "len", "(", "hash_", ")", ">", "4", ":", "hash_", "=", "hash_", "[", ":", "4", "]", "query", "=", "QueryParams", "(", "{", "'quickkey'", ":", "quickkey", ",", "'doc_type'", ":", "doc_type", ",", "'page'", ":", "page", ",", "'output'", ":", "output", ",", "'size_id'", ":", "size_id", ",", "'metadata'", ":", "metadata", ",", "'request_conversion_only'", ":", "request_conversion_only", "}", ")", "url", "=", "API_ENDPOINT", "+", "'?'", "+", "hash_", "+", "'&'", "+", "urlencode", "(", "query", ")", "response", "=", "self", ".", "http", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "if", "response", ".", "status_code", "==", "204", ":", "raise", "ConversionServerError", "(", "\"Unable to fulfill request. \"", "\"The document will not be converted.\"", ",", "response", ".", "status_code", ")", "response", ".", "raise_for_status", "(", ")", "if", "response", ".", "headers", "[", "'content-type'", "]", "==", "'application/json'", ":", "return", "response", ".", "json", "(", ")", "return", "response" ]
Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content
[ "Query", "conversion", "server" ]
8f1f23db1b16f16e026f5c6777aec32d00baa05f
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/media/conversion_server_client.py#L36-L80
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
user_method
def user_method(user_event): """Decorator of the Pdb user_* methods that controls the RemoteSocket.""" def wrapper(self, *args): stdin = self.stdin is_sock = isinstance(stdin, RemoteSocket) try: try: if is_sock and not stdin.connect(): return return user_event(self, *args) except Exception: self.close() raise finally: if is_sock and stdin.closed(): self.do_detach(None) return wrapper
python
def user_method(user_event): """Decorator of the Pdb user_* methods that controls the RemoteSocket.""" def wrapper(self, *args): stdin = self.stdin is_sock = isinstance(stdin, RemoteSocket) try: try: if is_sock and not stdin.connect(): return return user_event(self, *args) except Exception: self.close() raise finally: if is_sock and stdin.closed(): self.do_detach(None) return wrapper
[ "def", "user_method", "(", "user_event", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ")", ":", "stdin", "=", "self", ".", "stdin", "is_sock", "=", "isinstance", "(", "stdin", ",", "RemoteSocket", ")", "try", ":", "try", ":", "if", "is_sock", "and", "not", "stdin", ".", "connect", "(", ")", ":", "return", "return", "user_event", "(", "self", ",", "*", "args", ")", "except", "Exception", ":", "self", ".", "close", "(", ")", "raise", "finally", ":", "if", "is_sock", "and", "stdin", ".", "closed", "(", ")", ":", "self", ".", "do_detach", "(", "None", ")", "return", "wrapper" ]
Decorator of the Pdb user_* methods that controls the RemoteSocket.
[ "Decorator", "of", "the", "Pdb", "user_", "*", "methods", "that", "controls", "the", "RemoteSocket", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L115-L131
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.user_line
def user_line(self, frame, breakpoint_hits=None): """This function is called when we stop or break at this line.""" if not breakpoint_hits: self.interaction(frame, None) else: commands_result = self.bp_commands(frame, breakpoint_hits) if not commands_result: self.interaction(frame, None) else: doprompt, silent = commands_result if not silent: self.print_stack_entry(self.stack[self.curindex]) if doprompt: self._cmdloop() self.forget()
python
def user_line(self, frame, breakpoint_hits=None): """This function is called when we stop or break at this line.""" if not breakpoint_hits: self.interaction(frame, None) else: commands_result = self.bp_commands(frame, breakpoint_hits) if not commands_result: self.interaction(frame, None) else: doprompt, silent = commands_result if not silent: self.print_stack_entry(self.stack[self.curindex]) if doprompt: self._cmdloop() self.forget()
[ "def", "user_line", "(", "self", ",", "frame", ",", "breakpoint_hits", "=", "None", ")", ":", "if", "not", "breakpoint_hits", ":", "self", ".", "interaction", "(", "frame", ",", "None", ")", "else", ":", "commands_result", "=", "self", ".", "bp_commands", "(", "frame", ",", "breakpoint_hits", ")", "if", "not", "commands_result", ":", "self", ".", "interaction", "(", "frame", ",", "None", ")", "else", ":", "doprompt", ",", "silent", "=", "commands_result", "if", "not", "silent", ":", "self", ".", "print_stack_entry", "(", "self", ".", "stack", "[", "self", ".", "curindex", "]", ")", "if", "doprompt", ":", "self", ".", "_cmdloop", "(", ")", "self", ".", "forget", "(", ")" ]
This function is called when we stop or break at this line.
[ "This", "function", "is", "called", "when", "we", "stop", "or", "break", "at", "this", "line", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L518-L532
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.bp_commands
def bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.""" # Handle multiple breakpoints on the same line (issue 14789) effective_bp_list, temporaries = breakpoint_hits silent = True doprompt = False atleast_one_cmd = False for bp in effective_bp_list: if bp in self.commands: if not atleast_one_cmd: atleast_one_cmd = True self.setup(frame, None) lastcmd_back = self.lastcmd for line in self.commands[bp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[bp]: silent = False if self.commands_doprompt[bp]: doprompt = True # Delete the temporary breakpoints. tmp_to_delete = ' '.join(str(bp) for bp in temporaries) if tmp_to_delete: self.do_clear(tmp_to_delete) if atleast_one_cmd: return doprompt, silent return None
python
def bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.""" # Handle multiple breakpoints on the same line (issue 14789) effective_bp_list, temporaries = breakpoint_hits silent = True doprompt = False atleast_one_cmd = False for bp in effective_bp_list: if bp in self.commands: if not atleast_one_cmd: atleast_one_cmd = True self.setup(frame, None) lastcmd_back = self.lastcmd for line in self.commands[bp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[bp]: silent = False if self.commands_doprompt[bp]: doprompt = True # Delete the temporary breakpoints. tmp_to_delete = ' '.join(str(bp) for bp in temporaries) if tmp_to_delete: self.do_clear(tmp_to_delete) if atleast_one_cmd: return doprompt, silent return None
[ "def", "bp_commands", "(", "self", ",", "frame", ",", "breakpoint_hits", ")", ":", "# Handle multiple breakpoints on the same line (issue 14789)", "effective_bp_list", ",", "temporaries", "=", "breakpoint_hits", "silent", "=", "True", "doprompt", "=", "False", "atleast_one_cmd", "=", "False", "for", "bp", "in", "effective_bp_list", ":", "if", "bp", "in", "self", ".", "commands", ":", "if", "not", "atleast_one_cmd", ":", "atleast_one_cmd", "=", "True", "self", ".", "setup", "(", "frame", ",", "None", ")", "lastcmd_back", "=", "self", ".", "lastcmd", "for", "line", "in", "self", ".", "commands", "[", "bp", "]", ":", "self", ".", "onecmd", "(", "line", ")", "self", ".", "lastcmd", "=", "lastcmd_back", "if", "not", "self", ".", "commands_silent", "[", "bp", "]", ":", "silent", "=", "False", "if", "self", ".", "commands_doprompt", "[", "bp", "]", ":", "doprompt", "=", "True", "# Delete the temporary breakpoints.", "tmp_to_delete", "=", "' '", ".", "join", "(", "str", "(", "bp", ")", "for", "bp", "in", "temporaries", ")", "if", "tmp_to_delete", ":", "self", ".", "do_clear", "(", "tmp_to_delete", ")", "if", "atleast_one_cmd", ":", "return", "doprompt", ",", "silent", "return", "None" ]
Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.
[ "Call", "every", "command", "that", "was", "set", "for", "the", "current", "active", "breakpoints", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L534-L564
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.user_return
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value self.message('--Return--') self.interaction(frame, None)
python
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value self.message('--Return--') self.interaction(frame, None)
[ "def", "user_return", "(", "self", ",", "frame", ",", "return_value", ")", ":", "frame", ".", "f_locals", "[", "'__return__'", "]", "=", "return_value", "self", ".", "message", "(", "'--Return--'", ")", "self", ".", "interaction", "(", "frame", ",", "None", ")" ]
This function is called when a return trap is set here.
[ "This", "function", "is", "called", "when", "a", "return", "trap", "is", "set", "here", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L567-L571
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.user_exception
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" exc_type, exc_value, exc_traceback = exc_info frame.f_locals['__exception__'] = exc_type, exc_value # An 'Internal StopIteration' exception is an exception debug event # issued by the interpreter when handling a subgenerator run with # 'yield from' or a generator controled by a for loop. No exception has # actually occured in this case. The debugger uses this debug event to # stop when the debuggee is returning from such generators. prefix = 'Internal ' if (PY34 and not exc_traceback and exc_type is StopIteration) else '' self.message('--Exception--\n%s%s' % (prefix, traceback.format_exception_only(exc_type, exc_value)[-1].strip())) self.interaction(frame, exc_traceback)
python
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" exc_type, exc_value, exc_traceback = exc_info frame.f_locals['__exception__'] = exc_type, exc_value # An 'Internal StopIteration' exception is an exception debug event # issued by the interpreter when handling a subgenerator run with # 'yield from' or a generator controled by a for loop. No exception has # actually occured in this case. The debugger uses this debug event to # stop when the debuggee is returning from such generators. prefix = 'Internal ' if (PY34 and not exc_traceback and exc_type is StopIteration) else '' self.message('--Exception--\n%s%s' % (prefix, traceback.format_exception_only(exc_type, exc_value)[-1].strip())) self.interaction(frame, exc_traceback)
[ "def", "user_exception", "(", "self", ",", "frame", ",", "exc_info", ")", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "exc_info", "frame", ".", "f_locals", "[", "'__exception__'", "]", "=", "exc_type", ",", "exc_value", "# An 'Internal StopIteration' exception is an exception debug event", "# issued by the interpreter when handling a subgenerator run with", "# 'yield from' or a generator controled by a for loop. No exception has", "# actually occured in this case. The debugger uses this debug event to", "# stop when the debuggee is returning from such generators.", "prefix", "=", "'Internal '", "if", "(", "PY34", "and", "not", "exc_traceback", "and", "exc_type", "is", "StopIteration", ")", "else", "''", "self", ".", "message", "(", "'--Exception--\\n%s%s'", "%", "(", "prefix", ",", "traceback", ".", "format_exception_only", "(", "exc_type", ",", "exc_value", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", ")", "self", ".", "interaction", "(", "frame", ",", "exc_traceback", ")" ]
This function is called if an exception occurs, but only if we are to stop at or just below this level.
[ "This", "function", "is", "called", "if", "an", "exception", "occurs", "but", "only", "if", "we", "are", "to", "stop", "at", "or", "just", "below", "this", "level", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L574-L589
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.precmd
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ii += 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': marker = line.find(';;') if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line
python
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ii += 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': marker = line.find(';;') if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line
[ "def", "precmd", "(", "self", ",", "line", ")", ":", "if", "not", "line", ".", "strip", "(", ")", ":", "return", "line", "args", "=", "line", ".", "split", "(", ")", "while", "args", "[", "0", "]", "in", "self", ".", "aliases", ":", "line", "=", "self", ".", "aliases", "[", "args", "[", "0", "]", "]", "ii", "=", "1", "for", "tmpArg", "in", "args", "[", "1", ":", "]", ":", "line", "=", "line", ".", "replace", "(", "\"%\"", "+", "str", "(", "ii", ")", ",", "tmpArg", ")", "ii", "+=", "1", "line", "=", "line", ".", "replace", "(", "\"%*\"", ",", "' '", ".", "join", "(", "args", "[", "1", ":", "]", ")", ")", "args", "=", "line", ".", "split", "(", ")", "# split into ';;' separated commands", "# unless it's an alias command", "if", "args", "[", "0", "]", "!=", "'alias'", ":", "marker", "=", "line", ".", "find", "(", "';;'", ")", "if", "marker", ">=", "0", ":", "# queue up everything after marker", "next", "=", "line", "[", "marker", "+", "2", ":", "]", ".", "lstrip", "(", ")", "self", ".", "cmdqueue", ".", "append", "(", "next", ")", "line", "=", "line", "[", ":", "marker", "]", ".", "rstrip", "(", ")", "return", "line" ]
Handle alias expansion and ';;' separator.
[ "Handle", "alias", "expansion", "and", ";;", "separator", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L683-L706
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.onecmd
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
python
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
[ "def", "onecmd", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "commands_defining", ":", "return", "cmd", ".", "Cmd", ".", "onecmd", "(", "self", ",", "line", ")", "else", ":", "return", "self", ".", "handle_command_def", "(", "line", ")" ]
Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.
[ "Interpret", "the", "argument", "as", "though", "it", "had", "been", "typed", "in", "response", "to", "the", "prompt", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L708-L718
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.handle_command_def
def handle_command_def(self, line): """Handles one command line during command list definition.""" cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default # one of the resuming commands if func.__name__ in self.commands_resuming: self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
python
def handle_command_def(self, line): """Handles one command line during command list definition.""" cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default # one of the resuming commands if func.__name__ in self.commands_resuming: self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
[ "def", "handle_command_def", "(", "self", ",", "line", ")", ":", "cmd", ",", "arg", ",", "line", "=", "self", ".", "parseline", "(", "line", ")", "if", "not", "cmd", ":", "return", "if", "cmd", "==", "'silent'", ":", "self", ".", "commands_silent", "[", "self", ".", "commands_bnum", "]", "=", "True", "return", "# continue to handle other cmd def in the cmd list", "elif", "cmd", "==", "'end'", ":", "self", ".", "cmdqueue", "=", "[", "]", "return", "1", "# end of cmd list", "cmdlist", "=", "self", ".", "commands", "[", "self", ".", "commands_bnum", "]", "if", "arg", ":", "cmdlist", ".", "append", "(", "cmd", "+", "' '", "+", "arg", ")", "else", ":", "cmdlist", ".", "append", "(", "cmd", ")", "# Determine if we must stop", "try", ":", "func", "=", "getattr", "(", "self", ",", "'do_'", "+", "cmd", ")", "except", "AttributeError", ":", "func", "=", "self", ".", "default", "# one of the resuming commands", "if", "func", ".", "__name__", "in", "self", ".", "commands_resuming", ":", "self", ".", "commands_doprompt", "[", "self", ".", "commands_bnum", "]", "=", "False", "self", ".", "cmdqueue", "=", "[", "]", "return", "1", "return" ]
Handles one command line during command list definition.
[ "Handles", "one", "command", "line", "during", "command", "list", "definition", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L720-L746
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_commands
def do_commands(self, arg): """commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just 'end' to terminate the commands. The commands are executed when the breakpoint is hit. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint -- which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached. """ if not arg: bnum = len(bdb.Breakpoint.bpbynumber) - 1 else: try: bnum = int(arg) except Exception: self.error("Usage: commands [bnum]\n ...\n end") return self.commands_bnum = bnum # Save old definitions for the case of a keyboard interrupt. if bnum in self.commands: old_command_defs = (self.commands[bnum], self.commands_doprompt[bnum], self.commands_silent[bnum]) else: old_command_defs = None self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True try: self.cmdloop() except KeyboardInterrupt: # Restore old definitions. if old_command_defs: self.commands[bnum] = old_command_defs[0] self.commands_doprompt[bnum] = old_command_defs[1] self.commands_silent[bnum] = old_command_defs[2] else: del self.commands[bnum] del self.commands_doprompt[bnum] del self.commands_silent[bnum] self.error('command definition aborted, old commands restored') finally: self.commands_defining = False self.prompt = prompt_back
python
def do_commands(self, arg): """commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just 'end' to terminate the commands. The commands are executed when the breakpoint is hit. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint -- which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached. """ if not arg: bnum = len(bdb.Breakpoint.bpbynumber) - 1 else: try: bnum = int(arg) except Exception: self.error("Usage: commands [bnum]\n ...\n end") return self.commands_bnum = bnum # Save old definitions for the case of a keyboard interrupt. if bnum in self.commands: old_command_defs = (self.commands[bnum], self.commands_doprompt[bnum], self.commands_silent[bnum]) else: old_command_defs = None self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True try: self.cmdloop() except KeyboardInterrupt: # Restore old definitions. if old_command_defs: self.commands[bnum] = old_command_defs[0] self.commands_doprompt[bnum] = old_command_defs[1] self.commands_silent[bnum] = old_command_defs[2] else: del self.commands[bnum] del self.commands_doprompt[bnum] del self.commands_silent[bnum] self.error('command definition aborted, old commands restored') finally: self.commands_defining = False self.prompt = prompt_back
[ "def", "do_commands", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "bnum", "=", "len", "(", "bdb", ".", "Breakpoint", ".", "bpbynumber", ")", "-", "1", "else", ":", "try", ":", "bnum", "=", "int", "(", "arg", ")", "except", "Exception", ":", "self", ".", "error", "(", "\"Usage: commands [bnum]\\n ...\\n end\"", ")", "return", "self", ".", "commands_bnum", "=", "bnum", "# Save old definitions for the case of a keyboard interrupt.", "if", "bnum", "in", "self", ".", "commands", ":", "old_command_defs", "=", "(", "self", ".", "commands", "[", "bnum", "]", ",", "self", ".", "commands_doprompt", "[", "bnum", "]", ",", "self", ".", "commands_silent", "[", "bnum", "]", ")", "else", ":", "old_command_defs", "=", "None", "self", ".", "commands", "[", "bnum", "]", "=", "[", "]", "self", ".", "commands_doprompt", "[", "bnum", "]", "=", "True", "self", ".", "commands_silent", "[", "bnum", "]", "=", "False", "prompt_back", "=", "self", ".", "prompt", "self", ".", "prompt", "=", "'(com) '", "self", ".", "commands_defining", "=", "True", "try", ":", "self", ".", "cmdloop", "(", ")", "except", "KeyboardInterrupt", ":", "# Restore old definitions.", "if", "old_command_defs", ":", "self", ".", "commands", "[", "bnum", "]", "=", "old_command_defs", "[", "0", "]", "self", ".", "commands_doprompt", "[", "bnum", "]", "=", "old_command_defs", "[", "1", "]", "self", ".", "commands_silent", "[", "bnum", "]", "=", "old_command_defs", "[", "2", "]", "else", ":", "del", "self", ".", "commands", "[", "bnum", "]", "del", "self", ".", "commands_doprompt", "[", "bnum", "]", "del", "self", ".", "commands_silent", "[", "bnum", "]", "self", ".", "error", "(", "'command definition aborted, old commands restored'", ")", "finally", ":", "self", ".", "commands_defining", "=", "False", "self", ".", "prompt", "=", "prompt_back" ]
commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just 'end' to terminate the commands. The commands are executed when the breakpoint is hit. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint -- which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached.
[ "commands", "[", "bpnumber", "]", "(", "com", ")", "...", "(", "com", ")", "end", "(", "Pdb", ")" ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L815-L890
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_break
def do_break(self, arg, temporary = 0): """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted. """ if not arg: all_breaks = '\n'.join(bp.bpformat() for bp in bdb.Breakpoint.bpbynumber if bp) if all_breaks: self.message("Num Type Disp Enb Where") self.message(all_breaks) return # Parse arguments, comma has lowest precedence and cannot occur in # filename. args = arg.rsplit(',', 1) cond = args[1].strip() if len(args) == 2 else None # Parse stuff before comma: [filename:]lineno | function. args = args[0].rsplit(':', 1) name = args[0].strip() lineno = args[1] if len(args) == 2 else args[0] try: lineno = int(lineno) except ValueError: if len(args) == 2: self.error('Bad lineno: "{}".'.format(lineno)) else: # Attempt the list of possible function or method fully # qualified names and corresponding filenames. candidates = get_fqn_fname(name, self.curframe) for fqn, fname in candidates: try: bp = self.set_break(fname, None, temporary, cond, fqn) self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line)) return except bdb.BdbError: pass if not candidates: self.error( 'Not a function or a built-in: "{}"'.format(name)) else: self.error('Bad name: "{}".'.format(name)) else: filename = self.curframe.f_code.co_filename if len(args) == 2 and name: filename = name if filename.startswith('<') and filename.endswith('>'): # allow <doctest name>: doctest installs a hook at # linecache.getlines to allow <doctest name> to be # linecached and readable. if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile else: root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if not os.path.exists(filename): self.error('Bad filename: "{}".'.format(arg)) return try: bp = self.set_break(filename, lineno, temporary, cond) except bdb.BdbError as err: self.error(err) else: self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line))
python
def do_break(self, arg, temporary = 0): """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted. """ if not arg: all_breaks = '\n'.join(bp.bpformat() for bp in bdb.Breakpoint.bpbynumber if bp) if all_breaks: self.message("Num Type Disp Enb Where") self.message(all_breaks) return # Parse arguments, comma has lowest precedence and cannot occur in # filename. args = arg.rsplit(',', 1) cond = args[1].strip() if len(args) == 2 else None # Parse stuff before comma: [filename:]lineno | function. args = args[0].rsplit(':', 1) name = args[0].strip() lineno = args[1] if len(args) == 2 else args[0] try: lineno = int(lineno) except ValueError: if len(args) == 2: self.error('Bad lineno: "{}".'.format(lineno)) else: # Attempt the list of possible function or method fully # qualified names and corresponding filenames. candidates = get_fqn_fname(name, self.curframe) for fqn, fname in candidates: try: bp = self.set_break(fname, None, temporary, cond, fqn) self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line)) return except bdb.BdbError: pass if not candidates: self.error( 'Not a function or a built-in: "{}"'.format(name)) else: self.error('Bad name: "{}".'.format(name)) else: filename = self.curframe.f_code.co_filename if len(args) == 2 and name: filename = name if filename.startswith('<') and filename.endswith('>'): # allow <doctest name>: doctest installs a hook at # linecache.getlines to allow <doctest name> to be # linecached and readable. if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile else: root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if not os.path.exists(filename): self.error('Bad filename: "{}".'.format(arg)) return try: bp = self.set_break(filename, lineno, temporary, cond) except bdb.BdbError as err: self.error(err) else: self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line))
[ "def", "do_break", "(", "self", ",", "arg", ",", "temporary", "=", "0", ")", ":", "if", "not", "arg", ":", "all_breaks", "=", "'\\n'", ".", "join", "(", "bp", ".", "bpformat", "(", ")", "for", "bp", "in", "bdb", ".", "Breakpoint", ".", "bpbynumber", "if", "bp", ")", "if", "all_breaks", ":", "self", ".", "message", "(", "\"Num Type Disp Enb Where\"", ")", "self", ".", "message", "(", "all_breaks", ")", "return", "# Parse arguments, comma has lowest precedence and cannot occur in", "# filename.", "args", "=", "arg", ".", "rsplit", "(", "','", ",", "1", ")", "cond", "=", "args", "[", "1", "]", ".", "strip", "(", ")", "if", "len", "(", "args", ")", "==", "2", "else", "None", "# Parse stuff before comma: [filename:]lineno | function.", "args", "=", "args", "[", "0", "]", ".", "rsplit", "(", "':'", ",", "1", ")", "name", "=", "args", "[", "0", "]", ".", "strip", "(", ")", "lineno", "=", "args", "[", "1", "]", "if", "len", "(", "args", ")", "==", "2", "else", "args", "[", "0", "]", "try", ":", "lineno", "=", "int", "(", "lineno", ")", "except", "ValueError", ":", "if", "len", "(", "args", ")", "==", "2", ":", "self", ".", "error", "(", "'Bad lineno: \"{}\".'", ".", "format", "(", "lineno", ")", ")", "else", ":", "# Attempt the list of possible function or method fully", "# qualified names and corresponding filenames.", "candidates", "=", "get_fqn_fname", "(", "name", ",", "self", ".", "curframe", ")", "for", "fqn", ",", "fname", "in", "candidates", ":", "try", ":", "bp", "=", "self", ".", "set_break", "(", "fname", ",", "None", ",", "temporary", ",", "cond", ",", "fqn", ")", "self", ".", "message", "(", "'Breakpoint {:d} at {}:{:d}'", ".", "format", "(", "bp", ".", "number", ",", "bp", ".", "file", ",", "bp", ".", "line", ")", ")", "return", "except", "bdb", ".", "BdbError", ":", "pass", "if", "not", "candidates", ":", "self", ".", "error", "(", "'Not a function or a built-in: \"{}\"'", ".", "format", "(", "name", ")", ")", "else", ":", "self", ".", "error", "(", "'Bad name: \"{}\".'", ".", "format", "(", "name", ")", ")", "else", ":", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "if", "len", "(", "args", ")", "==", "2", "and", "name", ":", "filename", "=", "name", "if", "filename", ".", "startswith", "(", "'<'", ")", "and", "filename", ".", "endswith", "(", "'>'", ")", ":", "# allow <doctest name>: doctest installs a hook at", "# linecache.getlines to allow <doctest name> to be", "# linecached and readable.", "if", "filename", "==", "'<string>'", "and", "self", ".", "mainpyfile", ":", "filename", "=", "self", ".", "mainpyfile", "else", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "==", "''", ":", "filename", "=", "filename", "+", "'.py'", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "self", ".", "error", "(", "'Bad filename: \"{}\".'", ".", "format", "(", "arg", ")", ")", "return", "try", ":", "bp", "=", "self", ".", "set_break", "(", "filename", ",", "lineno", ",", "temporary", ",", "cond", ")", "except", "bdb", ".", "BdbError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "self", ".", "message", "(", "'Breakpoint {:d} at {}:{:d}'", ".", "format", "(", "bp", ".", "number", ",", "bp", ".", "file", ",", "bp", ".", "line", ")", ")" ]
b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.
[ "b", "(", "reak", ")", "[", "(", "[", "filename", ":", "]", "lineno", "|", "function", ")", "[", "condition", "]", "]", "Without", "argument", "list", "all", "breaks", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L894-L970
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.defaultFile
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename
python
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename
[ "def", "defaultFile", "(", "self", ")", ":", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "if", "filename", "==", "'<string>'", "and", "self", ".", "mainpyfile", ":", "filename", "=", "self", ".", "mainpyfile", "return", "filename" ]
Produce a reasonable default.
[ "Produce", "a", "reasonable", "default", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L973-L978
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_enable
def do_enable(self, arg): """enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.enable() self.done_breakpoint_state(bp, True)
python
def do_enable(self, arg): """enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.enable() self.done_breakpoint_state(bp, True)
[ "def", "do_enable", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "for", "i", "in", "args", ":", "try", ":", "bp", "=", "self", ".", "get_bpbynumber", "(", "i", ")", "except", "ValueError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "bp", ".", "enable", "(", ")", "self", ".", "done_breakpoint_state", "(", "bp", ",", "True", ")" ]
enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers.
[ "enable", "bpnumber", "[", "bpnumber", "...", "]", "Enables", "the", "breakpoints", "given", "as", "a", "space", "separated", "list", "of", "breakpoint", "numbers", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L998-L1011
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_disable
def do_disable(self, arg): """disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.disable() self.done_breakpoint_state(bp, False)
python
def do_disable(self, arg): """disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.disable() self.done_breakpoint_state(bp, False)
[ "def", "do_disable", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "for", "i", "in", "args", ":", "try", ":", "bp", "=", "self", ".", "get_bpbynumber", "(", "i", ")", "except", "ValueError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "bp", ".", "disable", "(", ")", "self", ".", "done_breakpoint_state", "(", "bp", ",", "False", ")" ]
disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled.
[ "disable", "bpnumber", "[", "bpnumber", "...", "]", "Disables", "the", "breakpoints", "given", "as", "a", "space", "separated", "list", "of", "breakpoint", "numbers", ".", "Disabling", "a", "breakpoint", "means", "it", "cannot", "cause", "the", "program", "to", "stop", "execution", "but", "unlike", "clearing", "a", "breakpoint", "it", "remains", "in", "the", "list", "of", "breakpoints", "and", "can", "be", "(", "re", "-", ")", "enabled", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1015-L1031
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_condition
def do_condition(self, arg): """condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional. """ args = arg.split(' ', 1) try: cond = args[1] except IndexError: cond = None try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.cond = cond if not cond: self.message('Breakpoint %d is now unconditional.' % bp.number) else: self.message('New condition set for breakpoint %d.' % bp.number)
python
def do_condition(self, arg): """condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional. """ args = arg.split(' ', 1) try: cond = args[1] except IndexError: cond = None try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.cond = cond if not cond: self.message('Breakpoint %d is now unconditional.' % bp.number) else: self.message('New condition set for breakpoint %d.' % bp.number)
[ "def", "do_condition", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", "' '", ",", "1", ")", "try", ":", "cond", "=", "args", "[", "1", "]", "except", "IndexError", ":", "cond", "=", "None", "try", ":", "bp", "=", "self", ".", "get_bpbynumber", "(", "args", "[", "0", "]", ".", "strip", "(", ")", ")", "except", "IndexError", ":", "self", ".", "error", "(", "'Breakpoint number expected'", ")", "except", "ValueError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "bp", ".", "cond", "=", "cond", "if", "not", "cond", ":", "self", ".", "message", "(", "'Breakpoint %d is now unconditional.'", "%", "bp", ".", "number", ")", "else", ":", "self", ".", "message", "(", "'New condition set for breakpoint %d.'", "%", "bp", ".", "number", ")" ]
condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.
[ "condition", "bpnumber", "[", "condition", "]", "Set", "a", "new", "condition", "for", "the", "breakpoint", "an", "expression", "which", "must", "evaluate", "to", "true", "before", "the", "breakpoint", "is", "honored", ".", "If", "condition", "is", "absent", "any", "existing", "condition", "is", "removed", ";", "i", ".", "e", ".", "the", "breakpoint", "is", "made", "unconditional", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1035-L1058
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_ignore
def do_ignore(self, arg): """ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true. """ args = arg.split(' ', 1) try: count = int(args[1].strip()) except Exception: count = 0 try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.ignore = count if count > 0: if count > 1: countstr = '%d crossings' % count else: countstr = '1 crossing' self.message('Will ignore next %s of breakpoint %d.' % (countstr, bp.number)) else: self.message('Will stop next time breakpoint %d is reached.' % bp.number)
python
def do_ignore(self, arg): """ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true. """ args = arg.split(' ', 1) try: count = int(args[1].strip()) except Exception: count = 0 try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.ignore = count if count > 0: if count > 1: countstr = '%d crossings' % count else: countstr = '1 crossing' self.message('Will ignore next %s of breakpoint %d.' % (countstr, bp.number)) else: self.message('Will stop next time breakpoint %d is reached.' % bp.number)
[ "def", "do_ignore", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", "' '", ",", "1", ")", "try", ":", "count", "=", "int", "(", "args", "[", "1", "]", ".", "strip", "(", ")", ")", "except", "Exception", ":", "count", "=", "0", "try", ":", "bp", "=", "self", ".", "get_bpbynumber", "(", "args", "[", "0", "]", ".", "strip", "(", ")", ")", "except", "IndexError", ":", "self", ".", "error", "(", "'Breakpoint number expected'", ")", "except", "ValueError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "bp", ".", "ignore", "=", "count", "if", "count", ">", "0", ":", "if", "count", ">", "1", ":", "countstr", "=", "'%d crossings'", "%", "count", "else", ":", "countstr", "=", "'1 crossing'", "self", ".", "message", "(", "'Will ignore next %s of breakpoint %d.'", "%", "(", "countstr", ",", "bp", ".", "number", ")", ")", "else", ":", "self", ".", "message", "(", "'Will stop next time breakpoint %d is reached.'", "%", "bp", ".", "number", ")" ]
ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.
[ "ignore", "bpnumber", "[", "count", "]", "Set", "the", "ignore", "count", "for", "the", "given", "breakpoint", "number", ".", "If", "count", "is", "omitted", "the", "ignore", "count", "is", "set", "to", "0", ".", "A", "breakpoint", "becomes", "active", "when", "the", "ignore", "count", "is", "zero", ".", "When", "non", "-", "zero", "the", "count", "is", "decremented", "each", "time", "the", "breakpoint", "is", "reached", "and", "the", "breakpoint", "is", "not", "disabled", "and", "any", "associated", "condition", "evaluates", "to", "true", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1062-L1093
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_clear
def do_clear(self, arg): """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file. """ if not arg: try: if PY3: reply = input('Clear all breaks? ') else: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp] self.clear_all_breaks() for bp in bplist: self.done_delete_breakpoint(bp) return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: bplist = self.get_breaks(filename, lineno) err = self.clear_break(filename, lineno) if err: self.error(err) else: for bp in bplist: self.done_delete_breakpoint(bp) return numberlist = arg.split() for i in numberlist: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: self.clear_bpbynumber(i) self.done_delete_breakpoint(bp)
python
def do_clear(self, arg): """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file. """ if not arg: try: if PY3: reply = input('Clear all breaks? ') else: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp] self.clear_all_breaks() for bp in bplist: self.done_delete_breakpoint(bp) return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: bplist = self.get_breaks(filename, lineno) err = self.clear_break(filename, lineno) if err: self.error(err) else: for bp in bplist: self.done_delete_breakpoint(bp) return numberlist = arg.split() for i in numberlist: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: self.clear_bpbynumber(i) self.done_delete_breakpoint(bp)
[ "def", "do_clear", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "try", ":", "if", "PY3", ":", "reply", "=", "input", "(", "'Clear all breaks? '", ")", "else", ":", "reply", "=", "raw_input", "(", "'Clear all breaks? '", ")", "except", "EOFError", ":", "reply", "=", "'no'", "reply", "=", "reply", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "reply", "in", "(", "'y'", ",", "'yes'", ")", ":", "bplist", "=", "[", "bp", "for", "bp", "in", "bdb", ".", "Breakpoint", ".", "bpbynumber", "if", "bp", "]", "self", ".", "clear_all_breaks", "(", ")", "for", "bp", "in", "bplist", ":", "self", ".", "done_delete_breakpoint", "(", "bp", ")", "return", "if", "':'", "in", "arg", ":", "# Make sure it works for \"clear C:\\foo\\bar.py:12\"", "i", "=", "arg", ".", "rfind", "(", "':'", ")", "filename", "=", "arg", "[", ":", "i", "]", "arg", "=", "arg", "[", "i", "+", "1", ":", "]", "try", ":", "lineno", "=", "int", "(", "arg", ")", "except", "ValueError", ":", "err", "=", "\"Invalid line number (%s)\"", "%", "arg", "else", ":", "bplist", "=", "self", ".", "get_breaks", "(", "filename", ",", "lineno", ")", "err", "=", "self", ".", "clear_break", "(", "filename", ",", "lineno", ")", "if", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "for", "bp", "in", "bplist", ":", "self", ".", "done_delete_breakpoint", "(", "bp", ")", "return", "numberlist", "=", "arg", ".", "split", "(", ")", "for", "i", "in", "numberlist", ":", "try", ":", "bp", "=", "self", ".", "get_bpbynumber", "(", "i", ")", "except", "ValueError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "else", ":", "self", ".", "clear_bpbynumber", "(", "i", ")", "self", ".", "done_delete_breakpoint", "(", "bp", ")" ]
cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file.
[ "cl", "(", "ear", ")", "filename", ":", "lineno", "\\", "ncl", "(", "ear", ")", "[", "bpnumber", "[", "bpnumber", "...", "]]", "With", "a", "space", "separated", "list", "of", "breakpoint", "numbers", "clear", "those", "breakpoints", ".", "Without", "argument", "clear", "all", "breaks", "(", "but", "first", "ask", "confirmation", ")", ".", "With", "a", "filename", ":", "lineno", "argument", "clear", "all", "breaks", "at", "that", "line", "in", "that", "file", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1100-L1148
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_up
def do_up(self, arg): """u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). """ if self.curindex == 0: self.error('Oldest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = 0 else: newframe = max(0, self.curindex - count) self._select_frame(newframe)
python
def do_up(self, arg): """u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). """ if self.curindex == 0: self.error('Oldest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = 0 else: newframe = max(0, self.curindex - count) self._select_frame(newframe)
[ "def", "do_up", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "curindex", "==", "0", ":", "self", ".", "error", "(", "'Oldest frame'", ")", "return", "try", ":", "count", "=", "int", "(", "arg", "or", "1", ")", "except", "ValueError", ":", "self", ".", "error", "(", "'Invalid frame count (%s)'", "%", "arg", ")", "return", "if", "count", "<", "0", ":", "newframe", "=", "0", "else", ":", "newframe", "=", "max", "(", "0", ",", "self", ".", "curindex", "-", "count", ")", "self", ".", "_select_frame", "(", "newframe", ")" ]
u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame).
[ "u", "(", "p", ")", "[", "count", "]", "Move", "the", "current", "frame", "count", "(", "default", "one", ")", "levels", "up", "in", "the", "stack", "trace", "(", "to", "an", "older", "frame", ")", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1171-L1188
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_down
def do_down(self, arg): """d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). """ if self.curindex + 1 == len(self.stack): self.error('Newest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = len(self.stack) - 1 else: newframe = min(len(self.stack) - 1, self.curindex + count) self._select_frame(newframe)
python
def do_down(self, arg): """d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). """ if self.curindex + 1 == len(self.stack): self.error('Newest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = len(self.stack) - 1 else: newframe = min(len(self.stack) - 1, self.curindex + count) self._select_frame(newframe)
[ "def", "do_down", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "curindex", "+", "1", "==", "len", "(", "self", ".", "stack", ")", ":", "self", ".", "error", "(", "'Newest frame'", ")", "return", "try", ":", "count", "=", "int", "(", "arg", "or", "1", ")", "except", "ValueError", ":", "self", ".", "error", "(", "'Invalid frame count (%s)'", "%", "arg", ")", "return", "if", "count", "<", "0", ":", "newframe", "=", "len", "(", "self", ".", "stack", ")", "-", "1", "else", ":", "newframe", "=", "min", "(", "len", "(", "self", ".", "stack", ")", "-", "1", ",", "self", ".", "curindex", "+", "count", ")", "self", ".", "_select_frame", "(", "newframe", ")" ]
d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame).
[ "d", "(", "own", ")", "[", "count", "]", "Move", "the", "current", "frame", "count", "(", "default", "one", ")", "levels", "down", "in", "the", "stack", "trace", "(", "to", "a", "newer", "frame", ")", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1191-L1208
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_until
def do_until(self, arg): """unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns. """ if arg: try: lineno = int(arg) except ValueError: self.error('Error in argument: %r' % arg) return if lineno <= self.curframe.f_lineno: self.error('"until" line number is smaller than current ' 'line number') return else: lineno = None self.set_until(self.curframe, lineno) self.set_sigint_handler() return 1
python
def do_until(self, arg): """unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns. """ if arg: try: lineno = int(arg) except ValueError: self.error('Error in argument: %r' % arg) return if lineno <= self.curframe.f_lineno: self.error('"until" line number is smaller than current ' 'line number') return else: lineno = None self.set_until(self.curframe, lineno) self.set_sigint_handler() return 1
[ "def", "do_until", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "try", ":", "lineno", "=", "int", "(", "arg", ")", "except", "ValueError", ":", "self", ".", "error", "(", "'Error in argument: %r'", "%", "arg", ")", "return", "if", "lineno", "<=", "self", ".", "curframe", ".", "f_lineno", ":", "self", ".", "error", "(", "'\"until\" line number is smaller than current '", "'line number'", ")", "return", "else", ":", "lineno", "=", "None", "self", ".", "set_until", "(", "self", ".", "curframe", ",", "lineno", ")", "self", ".", "set_sigint_handler", "(", ")", "return", "1" ]
unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns.
[ "unt", "(", "il", ")", "[", "lineno", "]", "Without", "argument", "continue", "execution", "until", "the", "line", "with", "a", "number", "greater", "than", "the", "current", "one", "is", "reached", ".", "With", "a", "line", "number", "continue", "execution", "until", "a", "line", "with", "a", "number", "greater", "or", "equal", "to", "that", "is", "reached", ".", "In", "both", "cases", "also", "stop", "when", "the", "current", "frame", "returns", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1211-L1233
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_run
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". """ if arg: argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 # this is caught in the main debugger loop raise Restart
python
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". """ if arg: argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 # this is caught in the main debugger loop raise Restart
[ "def", "do_run", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "argv0", "=", "sys", ".", "argv", "[", "0", ":", "1", "]", "sys", ".", "argv", "=", "shlex", ".", "split", "(", "arg", ")", "sys", ".", "argv", "[", ":", "0", "]", "=", "argv0", "# this is caught in the main debugger loop", "raise", "Restart" ]
run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run".
[ "run", "[", "args", "...", "]", "Restart", "the", "debugged", "python", "program", ".", "If", "a", "string", "is", "supplied", "it", "is", "splitted", "with", "shlex", "and", "the", "result", "is", "used", "as", "the", "new", "sys", ".", "argv", ".", "History", "breakpoints", "actions", "and", "debugger", "options", "are", "preserved", ".", "restart", "is", "an", "alias", "for", "run", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1257-L1269
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_jump
def do_jump(self, arg): """j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are allowed -- for instance it is not possible to jump into the middle of a for loop or out of a finally clause. """ if self.curindex + 1 != len(self.stack): self.error('You can only jump within the bottom frame') return try: arg = int(arg) except ValueError: self.error("The 'jump' command requires a line number") else: try: # Do the jump, fix up our copy of the stack, and display the # new position self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) except ValueError as e: self.error('Jump failed: %s' % e)
python
def do_jump(self, arg): """j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are allowed -- for instance it is not possible to jump into the middle of a for loop or out of a finally clause. """ if self.curindex + 1 != len(self.stack): self.error('You can only jump within the bottom frame') return try: arg = int(arg) except ValueError: self.error("The 'jump' command requires a line number") else: try: # Do the jump, fix up our copy of the stack, and display the # new position self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) except ValueError as e: self.error('Jump failed: %s' % e)
[ "def", "do_jump", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "curindex", "+", "1", "!=", "len", "(", "self", ".", "stack", ")", ":", "self", ".", "error", "(", "'You can only jump within the bottom frame'", ")", "return", "try", ":", "arg", "=", "int", "(", "arg", ")", "except", "ValueError", ":", "self", ".", "error", "(", "\"The 'jump' command requires a line number\"", ")", "else", ":", "try", ":", "# Do the jump, fix up our copy of the stack, and display the", "# new position", "self", ".", "curframe", ".", "f_lineno", "=", "arg", "self", ".", "stack", "[", "self", ".", "curindex", "]", "=", "self", ".", "stack", "[", "self", ".", "curindex", "]", "[", "0", "]", ",", "arg", "self", ".", "print_stack_entry", "(", "self", ".", "stack", "[", "self", ".", "curindex", "]", ")", "except", "ValueError", "as", "e", ":", "self", ".", "error", "(", "'Jump failed: %s'", "%", "e", ")" ]
j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don't want to run. It should be noted that not all jumps are allowed -- for instance it is not possible to jump into the middle of a for loop or out of a finally clause.
[ "j", "(", "ump", ")", "lineno", "Set", "the", "next", "line", "that", "will", "be", "executed", ".", "Only", "available", "in", "the", "bottom", "-", "most", "frame", ".", "This", "lets", "you", "jump", "back", "and", "execute", "code", "again", "or", "jump", "forward", "to", "skip", "code", "that", "you", "don", "t", "want", "to", "run", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1291-L1317
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_debug
def do_debug(self, arg): """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment). """ self.settrace(False) globals = self.curframe.f_globals locals = self.get_locals(self.curframe) p = Pdb(self.completekey, self.stdin, self.stdout, debug=True) p.prompt = "(%s) " % self.prompt.strip() self.message("ENTERING RECURSIVE DEBUGGER") sys.call_tracing(p.run, (arg, globals, locals)) self.message("LEAVING RECURSIVE DEBUGGER") self.settrace(True) self.lastcmd = p.lastcmd
python
def do_debug(self, arg): """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment). """ self.settrace(False) globals = self.curframe.f_globals locals = self.get_locals(self.curframe) p = Pdb(self.completekey, self.stdin, self.stdout, debug=True) p.prompt = "(%s) " % self.prompt.strip() self.message("ENTERING RECURSIVE DEBUGGER") sys.call_tracing(p.run, (arg, globals, locals)) self.message("LEAVING RECURSIVE DEBUGGER") self.settrace(True) self.lastcmd = p.lastcmd
[ "def", "do_debug", "(", "self", ",", "arg", ")", ":", "self", ".", "settrace", "(", "False", ")", "globals", "=", "self", ".", "curframe", ".", "f_globals", "locals", "=", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", "p", "=", "Pdb", "(", "self", ".", "completekey", ",", "self", ".", "stdin", ",", "self", ".", "stdout", ",", "debug", "=", "True", ")", "p", ".", "prompt", "=", "\"(%s) \"", "%", "self", ".", "prompt", ".", "strip", "(", ")", "self", ".", "message", "(", "\"ENTERING RECURSIVE DEBUGGER\"", ")", "sys", ".", "call_tracing", "(", "p", ".", "run", ",", "(", "arg", ",", "globals", ",", "locals", ")", ")", "self", ".", "message", "(", "\"LEAVING RECURSIVE DEBUGGER\"", ")", "self", ".", "settrace", "(", "True", ")", "self", ".", "lastcmd", "=", "p", ".", "lastcmd" ]
debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).
[ "debug", "code", "Enter", "a", "recursive", "debugger", "that", "steps", "through", "the", "code", "argument", "(", "which", "is", "an", "arbitrary", "expression", "or", "statement", "to", "be", "executed", "in", "the", "current", "environment", ")", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1320-L1335
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_quit
def do_quit(self, arg): """q(uit)\nexit Quit from the debugger. The program being executed is aborted. """ if isinstance(self.stdin, RemoteSocket) and not self.is_debug_instance: return self.do_detach(arg) self._user_requested_quit = True self.set_quit() return 1
python
def do_quit(self, arg): """q(uit)\nexit Quit from the debugger. The program being executed is aborted. """ if isinstance(self.stdin, RemoteSocket) and not self.is_debug_instance: return self.do_detach(arg) self._user_requested_quit = True self.set_quit() return 1
[ "def", "do_quit", "(", "self", ",", "arg", ")", ":", "if", "isinstance", "(", "self", ".", "stdin", ",", "RemoteSocket", ")", "and", "not", "self", ".", "is_debug_instance", ":", "return", "self", ".", "do_detach", "(", "arg", ")", "self", ".", "_user_requested_quit", "=", "True", "self", ".", "set_quit", "(", ")", "return", "1" ]
q(uit)\nexit Quit from the debugger. The program being executed is aborted.
[ "q", "(", "uit", ")", "\\", "nexit", "Quit", "from", "the", "debugger", ".", "The", "program", "being", "executed", "is", "aborted", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1349-L1357
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_args
def do_args(self, arg): """a(rgs) Print the argument list of the current function. """ co = self.curframe.f_code dict = self.get_locals(self.curframe) n = co.co_argcount if co.co_flags & 4: n = n+1 if co.co_flags & 8: n = n+1 for i in range(n): name = co.co_varnames[i] if name in dict: self.message('%s = %s' % (name, bdb.safe_repr(dict[name]))) else: self.message('%s = *** undefined ***' % (name,))
python
def do_args(self, arg): """a(rgs) Print the argument list of the current function. """ co = self.curframe.f_code dict = self.get_locals(self.curframe) n = co.co_argcount if co.co_flags & 4: n = n+1 if co.co_flags & 8: n = n+1 for i in range(n): name = co.co_varnames[i] if name in dict: self.message('%s = %s' % (name, bdb.safe_repr(dict[name]))) else: self.message('%s = *** undefined ***' % (name,))
[ "def", "do_args", "(", "self", ",", "arg", ")", ":", "co", "=", "self", ".", "curframe", ".", "f_code", "dict", "=", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", "n", "=", "co", ".", "co_argcount", "if", "co", ".", "co_flags", "&", "4", ":", "n", "=", "n", "+", "1", "if", "co", ".", "co_flags", "&", "8", ":", "n", "=", "n", "+", "1", "for", "i", "in", "range", "(", "n", ")", ":", "name", "=", "co", ".", "co_varnames", "[", "i", "]", "if", "name", "in", "dict", ":", "self", ".", "message", "(", "'%s = %s'", "%", "(", "name", ",", "bdb", ".", "safe_repr", "(", "dict", "[", "name", "]", ")", ")", ")", "else", ":", "self", ".", "message", "(", "'%s = *** undefined ***'", "%", "(", "name", ",", ")", ")" ]
a(rgs) Print the argument list of the current function.
[ "a", "(", "rgs", ")", "Print", "the", "argument", "list", "of", "the", "current", "function", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1369-L1383
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_retval
def do_retval(self, arg): """retval Print the return value for the last return of a function. """ locals = self.get_locals(self.curframe) if '__return__' in locals: self.message(bdb.safe_repr(locals['__return__'])) else: self.error('Not yet returned!')
python
def do_retval(self, arg): """retval Print the return value for the last return of a function. """ locals = self.get_locals(self.curframe) if '__return__' in locals: self.message(bdb.safe_repr(locals['__return__'])) else: self.error('Not yet returned!')
[ "def", "do_retval", "(", "self", ",", "arg", ")", ":", "locals", "=", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", "if", "'__return__'", "in", "locals", ":", "self", ".", "message", "(", "bdb", ".", "safe_repr", "(", "locals", "[", "'__return__'", "]", ")", ")", "else", ":", "self", ".", "error", "(", "'Not yet returned!'", ")" ]
retval Print the return value for the last return of a function.
[ "retval", "Print", "the", "return", "value", "for", "the", "last", "return", "of", "a", "function", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1386-L1394
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_p
def do_p(self, arg): """p expression Print the value of the expression. """ try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
python
def do_p(self, arg): """p expression Print the value of the expression. """ try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
[ "def", "do_p", "(", "self", ",", "arg", ")", ":", "try", ":", "self", ".", "message", "(", "bdb", ".", "safe_repr", "(", "self", ".", "_getval", "(", "arg", ")", ")", ")", "except", "Exception", ":", "pass" ]
p expression Print the value of the expression.
[ "p", "expression", "Print", "the", "value", "of", "the", "expression", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1418-L1425
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_pp
def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """ obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(obj))
python
def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """ obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(obj))
[ "def", "do_pp", "(", "self", ",", "arg", ")", ":", "obj", "=", "self", ".", "_getval", "(", "arg", ")", "try", ":", "repr", "(", "obj", ")", "except", "Exception", ":", "self", ".", "message", "(", "bdb", ".", "safe_repr", "(", "obj", ")", ")", "else", ":", "self", ".", "message", "(", "pprint", ".", "pformat", "(", "obj", ")", ")" ]
pp expression Pretty-print the value of the expression.
[ "pp", "expression", "Pretty", "-", "print", "the", "value", "of", "the", "expression", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1427-L1437
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_list
def do_list(self, arg): """l(ist) [first [,last] | .] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. The current line in the current frame is indicated by "->". If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by ">>", if it differs from the current line. """ self.lastcmd = 'list' last = None if arg and arg != '.': try: if ',' in arg: first, last = arg.split(',') first = int(first.strip()) last = int(last.strip()) if last < first: # assume it's a count last = first + last else: first = int(arg.strip()) first = max(1, first - 5) except ValueError: self.error('Error in argument: %r' % arg) return elif self.lineno is None or arg == '.': first = max(1, self.curframe.f_lineno - 5) else: first = self.lineno + 1 if last is None: last = first + 10 filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines = linecache.getlines(filename, self.curframe.f_globals) self._print_lines(lines[first-1:last], first, breaklist, self.curframe) self.lineno = min(last, len(lines)) if len(lines) < last: self.message('[EOF]') except KeyboardInterrupt: pass
python
def do_list(self, arg): """l(ist) [first [,last] | .] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. The current line in the current frame is indicated by "->". If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by ">>", if it differs from the current line. """ self.lastcmd = 'list' last = None if arg and arg != '.': try: if ',' in arg: first, last = arg.split(',') first = int(first.strip()) last = int(last.strip()) if last < first: # assume it's a count last = first + last else: first = int(arg.strip()) first = max(1, first - 5) except ValueError: self.error('Error in argument: %r' % arg) return elif self.lineno is None or arg == '.': first = max(1, self.curframe.f_lineno - 5) else: first = self.lineno + 1 if last is None: last = first + 10 filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines = linecache.getlines(filename, self.curframe.f_globals) self._print_lines(lines[first-1:last], first, breaklist, self.curframe) self.lineno = min(last, len(lines)) if len(lines) < last: self.message('[EOF]') except KeyboardInterrupt: pass
[ "def", "do_list", "(", "self", ",", "arg", ")", ":", "self", ".", "lastcmd", "=", "'list'", "last", "=", "None", "if", "arg", "and", "arg", "!=", "'.'", ":", "try", ":", "if", "','", "in", "arg", ":", "first", ",", "last", "=", "arg", ".", "split", "(", "','", ")", "first", "=", "int", "(", "first", ".", "strip", "(", ")", ")", "last", "=", "int", "(", "last", ".", "strip", "(", ")", ")", "if", "last", "<", "first", ":", "# assume it's a count", "last", "=", "first", "+", "last", "else", ":", "first", "=", "int", "(", "arg", ".", "strip", "(", ")", ")", "first", "=", "max", "(", "1", ",", "first", "-", "5", ")", "except", "ValueError", ":", "self", ".", "error", "(", "'Error in argument: %r'", "%", "arg", ")", "return", "elif", "self", ".", "lineno", "is", "None", "or", "arg", "==", "'.'", ":", "first", "=", "max", "(", "1", ",", "self", ".", "curframe", ".", "f_lineno", "-", "5", ")", "else", ":", "first", "=", "self", ".", "lineno", "+", "1", "if", "last", "is", "None", ":", "last", "=", "first", "+", "10", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "breaklist", "=", "self", ".", "get_file_breaks", "(", "filename", ")", "try", ":", "lines", "=", "linecache", ".", "getlines", "(", "filename", ",", "self", ".", "curframe", ".", "f_globals", ")", "self", ".", "_print_lines", "(", "lines", "[", "first", "-", "1", ":", "last", "]", ",", "first", ",", "breaklist", ",", "self", ".", "curframe", ")", "self", ".", "lineno", "=", "min", "(", "last", ",", "len", "(", "lines", ")", ")", "if", "len", "(", "lines", ")", "<", "last", ":", "self", ".", "message", "(", "'[EOF]'", ")", "except", "KeyboardInterrupt", ":", "pass" ]
l(ist) [first [,last] | .] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. The current line in the current frame is indicated by "->". If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by ">>", if it differs from the current line.
[ "l", "(", "ist", ")", "[", "first", "[", "last", "]", "|", ".", "]" ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1443-L1491
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_longlist
def do_longlist(self, arg): """longlist | ll List the whole source code for the current function or frame. """ filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines, lineno = getsourcelines(self.curframe, self.get_locals(self.curframe)) except IOError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe)
python
def do_longlist(self, arg): """longlist | ll List the whole source code for the current function or frame. """ filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines, lineno = getsourcelines(self.curframe, self.get_locals(self.curframe)) except IOError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe)
[ "def", "do_longlist", "(", "self", ",", "arg", ")", ":", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "breaklist", "=", "self", ".", "get_file_breaks", "(", "filename", ")", "try", ":", "lines", ",", "lineno", "=", "getsourcelines", "(", "self", ".", "curframe", ",", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", ")", "except", "IOError", "as", "err", ":", "self", ".", "error", "(", "err", ")", "return", "self", ".", "_print_lines", "(", "lines", ",", "lineno", ",", "breaklist", ",", "self", ".", "curframe", ")" ]
longlist | ll List the whole source code for the current function or frame.
[ "longlist", "|", "ll", "List", "the", "whole", "source", "code", "for", "the", "current", "function", "or", "frame", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1494-L1506
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_source
def do_source(self, arg): """source expression Try to get source code for the given object and display it. """ try: obj = self._getval(arg) except Exception: return try: lines, lineno = getsourcelines(obj, self.get_locals(self.curframe)) except (IOError, TypeError) as err: self.error(err) return self._print_lines(lines, lineno)
python
def do_source(self, arg): """source expression Try to get source code for the given object and display it. """ try: obj = self._getval(arg) except Exception: return try: lines, lineno = getsourcelines(obj, self.get_locals(self.curframe)) except (IOError, TypeError) as err: self.error(err) return self._print_lines(lines, lineno)
[ "def", "do_source", "(", "self", ",", "arg", ")", ":", "try", ":", "obj", "=", "self", ".", "_getval", "(", "arg", ")", "except", "Exception", ":", "return", "try", ":", "lines", ",", "lineno", "=", "getsourcelines", "(", "obj", ",", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", ")", "except", "(", "IOError", ",", "TypeError", ")", "as", "err", ":", "self", ".", "error", "(", "err", ")", "return", "self", ".", "_print_lines", "(", "lines", ",", "lineno", ")" ]
source expression Try to get source code for the given object and display it.
[ "source", "expression", "Try", "to", "get", "source", "code", "for", "the", "given", "object", "and", "display", "it", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1509-L1522
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb._print_lines
def _print_lines(self, lines, start, breaks=(), frame=None): """Print a range of lines.""" if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, start): s = str(lineno).rjust(3) if len(s) < 4: s += ' ' if lineno in breaks: s += 'B' else: s += ' ' if lineno == current_lineno: s += '->' elif lineno == exc_lineno: s += '>>' self.message(s + '\t' + line.rstrip())
python
def _print_lines(self, lines, start, breaks=(), frame=None): """Print a range of lines.""" if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, start): s = str(lineno).rjust(3) if len(s) < 4: s += ' ' if lineno in breaks: s += 'B' else: s += ' ' if lineno == current_lineno: s += '->' elif lineno == exc_lineno: s += '>>' self.message(s + '\t' + line.rstrip())
[ "def", "_print_lines", "(", "self", ",", "lines", ",", "start", ",", "breaks", "=", "(", ")", ",", "frame", "=", "None", ")", ":", "if", "frame", ":", "current_lineno", "=", "frame", ".", "f_lineno", "exc_lineno", "=", "self", ".", "tb_lineno", ".", "get", "(", "frame", ",", "-", "1", ")", "else", ":", "current_lineno", "=", "exc_lineno", "=", "-", "1", "for", "lineno", ",", "line", "in", "enumerate", "(", "lines", ",", "start", ")", ":", "s", "=", "str", "(", "lineno", ")", ".", "rjust", "(", "3", ")", "if", "len", "(", "s", ")", "<", "4", ":", "s", "+=", "' '", "if", "lineno", "in", "breaks", ":", "s", "+=", "'B'", "else", ":", "s", "+=", "' '", "if", "lineno", "==", "current_lineno", ":", "s", "+=", "'->'", "elif", "lineno", "==", "exc_lineno", ":", "s", "+=", "'>>'", "self", ".", "message", "(", "s", "+", "'\\t'", "+", "line", ".", "rstrip", "(", ")", ")" ]
Print a range of lines.
[ "Print", "a", "range", "of", "lines", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1526-L1545
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_whatis
def do_whatis(self, arg): """whatis arg Print the type of the argument. """ try: value = self._getval(arg) except Exception: # _getval() already printed the error return code = None # Is it a function? try: code = value.__code__ except Exception: pass if code: self.message('Function %s' % code.co_name) return # Is it an instance method? try: code = value.__func__.__code__ except Exception: pass if code: self.message('Method %s' % code.co_name) return # Is it a class? if value.__class__ is type: self.message('Class %s.%s' % (value.__module__, value.__name__)) return # None of the above... self.message(type(value))
python
def do_whatis(self, arg): """whatis arg Print the type of the argument. """ try: value = self._getval(arg) except Exception: # _getval() already printed the error return code = None # Is it a function? try: code = value.__code__ except Exception: pass if code: self.message('Function %s' % code.co_name) return # Is it an instance method? try: code = value.__func__.__code__ except Exception: pass if code: self.message('Method %s' % code.co_name) return # Is it a class? if value.__class__ is type: self.message('Class %s.%s' % (value.__module__, value.__name__)) return # None of the above... self.message(type(value))
[ "def", "do_whatis", "(", "self", ",", "arg", ")", ":", "try", ":", "value", "=", "self", ".", "_getval", "(", "arg", ")", "except", "Exception", ":", "# _getval() already printed the error", "return", "code", "=", "None", "# Is it a function?", "try", ":", "code", "=", "value", ".", "__code__", "except", "Exception", ":", "pass", "if", "code", ":", "self", ".", "message", "(", "'Function %s'", "%", "code", ".", "co_name", ")", "return", "# Is it an instance method?", "try", ":", "code", "=", "value", ".", "__func__", ".", "__code__", "except", "Exception", ":", "pass", "if", "code", ":", "self", ".", "message", "(", "'Method %s'", "%", "code", ".", "co_name", ")", "return", "# Is it a class?", "if", "value", ".", "__class__", "is", "type", ":", "self", ".", "message", "(", "'Class %s.%s'", "%", "(", "value", ".", "__module__", ",", "value", ".", "__name__", ")", ")", "return", "# None of the above...", "self", ".", "message", "(", "type", "(", "value", ")", ")" ]
whatis arg Print the type of the argument.
[ "whatis", "arg", "Print", "the", "type", "of", "the", "argument", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1547-L1578
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_display
def do_display(self, arg): """display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame. """ if not arg: self.message('Currently displaying:') for item in self.displaying.get(self.curframe, {}).items(): self.message('%s: %s' % bdb.safe_repr(item)) else: val = self._getval_except(arg) self.displaying.setdefault(self.curframe, {})[arg] = val self.message('display %s: %s' % (arg, bdb.safe_repr(val)))
python
def do_display(self, arg): """display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame. """ if not arg: self.message('Currently displaying:') for item in self.displaying.get(self.curframe, {}).items(): self.message('%s: %s' % bdb.safe_repr(item)) else: val = self._getval_except(arg) self.displaying.setdefault(self.curframe, {})[arg] = val self.message('display %s: %s' % (arg, bdb.safe_repr(val)))
[ "def", "do_display", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "self", ".", "message", "(", "'Currently displaying:'", ")", "for", "item", "in", "self", ".", "displaying", ".", "get", "(", "self", ".", "curframe", ",", "{", "}", ")", ".", "items", "(", ")", ":", "self", ".", "message", "(", "'%s: %s'", "%", "bdb", ".", "safe_repr", "(", "item", ")", ")", "else", ":", "val", "=", "self", ".", "_getval_except", "(", "arg", ")", "self", ".", "displaying", ".", "setdefault", "(", "self", ".", "curframe", ",", "{", "}", ")", "[", "arg", "]", "=", "val", "self", ".", "message", "(", "'display %s: %s'", "%", "(", "arg", ",", "bdb", ".", "safe_repr", "(", "val", ")", ")", ")" ]
display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame.
[ "display", "[", "expression", "]" ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1582-L1597
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_undisplay
def do_undisplay(self, arg): """undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame. """ if arg: try: del self.displaying.get(self.curframe, {})[arg] except KeyError: self.error('not displaying %s' % arg) else: self.displaying.pop(self.curframe, None)
python
def do_undisplay(self, arg): """undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame. """ if arg: try: del self.displaying.get(self.curframe, {})[arg] except KeyError: self.error('not displaying %s' % arg) else: self.displaying.pop(self.curframe, None)
[ "def", "do_undisplay", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "try", ":", "del", "self", ".", "displaying", ".", "get", "(", "self", ".", "curframe", ",", "{", "}", ")", "[", "arg", "]", "except", "KeyError", ":", "self", ".", "error", "(", "'not displaying %s'", "%", "arg", ")", "else", ":", "self", ".", "displaying", ".", "pop", "(", "self", ".", "curframe", ",", "None", ")" ]
undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame.
[ "undisplay", "[", "expression", "]" ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1601-L1614
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_interact
def do_interact(self, arg): """interact Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope. """ def readfunc(prompt): self.stdout.write(prompt) self.stdout.flush() line = self.stdin.readline() line = line.rstrip('\r\n') if line == 'EOF': raise EOFError return line ns = self.curframe.f_globals.copy() ns.update(self.get_locals(self.curframe)) if isinstance(self.stdin, RemoteSocket): # Main interpreter redirection of the code module. if PY3: import sys as _sys else: # Parent module 'pdb_clone' not found while handling absolute # import. _sys = __import__('sys', level=0) code.sys = _sys self.redirect(code.interact, local=ns, readfunc=readfunc) else: code.interact("*interactive*", local=ns)
python
def do_interact(self, arg): """interact Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope. """ def readfunc(prompt): self.stdout.write(prompt) self.stdout.flush() line = self.stdin.readline() line = line.rstrip('\r\n') if line == 'EOF': raise EOFError return line ns = self.curframe.f_globals.copy() ns.update(self.get_locals(self.curframe)) if isinstance(self.stdin, RemoteSocket): # Main interpreter redirection of the code module. if PY3: import sys as _sys else: # Parent module 'pdb_clone' not found while handling absolute # import. _sys = __import__('sys', level=0) code.sys = _sys self.redirect(code.interact, local=ns, readfunc=readfunc) else: code.interact("*interactive*", local=ns)
[ "def", "do_interact", "(", "self", ",", "arg", ")", ":", "def", "readfunc", "(", "prompt", ")", ":", "self", ".", "stdout", ".", "write", "(", "prompt", ")", "self", ".", "stdout", ".", "flush", "(", ")", "line", "=", "self", ".", "stdin", ".", "readline", "(", ")", "line", "=", "line", ".", "rstrip", "(", "'\\r\\n'", ")", "if", "line", "==", "'EOF'", ":", "raise", "EOFError", "return", "line", "ns", "=", "self", ".", "curframe", ".", "f_globals", ".", "copy", "(", ")", "ns", ".", "update", "(", "self", ".", "get_locals", "(", "self", ".", "curframe", ")", ")", "if", "isinstance", "(", "self", ".", "stdin", ",", "RemoteSocket", ")", ":", "# Main interpreter redirection of the code module.", "if", "PY3", ":", "import", "sys", "as", "_sys", "else", ":", "# Parent module 'pdb_clone' not found while handling absolute", "# import.", "_sys", "=", "__import__", "(", "'sys'", ",", "level", "=", "0", ")", "code", ".", "sys", "=", "_sys", "self", ".", "redirect", "(", "code", ".", "interact", ",", "local", "=", "ns", ",", "readfunc", "=", "readfunc", ")", "else", ":", "code", ".", "interact", "(", "\"*interactive*\"", ",", "local", "=", "ns", ")" ]
interact Start an interative interpreter whose global namespace contains all the (global and local) names found in the current scope.
[ "interact" ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1620-L1648
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_alias
def do_alias(self, arg): """alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. As an example, here are two useful aliases (especially when placed in the .pdbrc file): # Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) # Print instance variables in self alias ps pi self """ args = arg.split() if len(args) == 0: keys = sorted(self.aliases.keys()) for alias in keys: self.message("%s = %s" % (alias, self.aliases[alias])) return if args[0] in self.aliases and len(args) == 1: self.message("%s = %s" % (args[0], self.aliases[args[0]])) else: self.aliases[args[0]] = ' '.join(args[1:])
python
def do_alias(self, arg): """alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. As an example, here are two useful aliases (especially when placed in the .pdbrc file): # Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) # Print instance variables in self alias ps pi self """ args = arg.split() if len(args) == 0: keys = sorted(self.aliases.keys()) for alias in keys: self.message("%s = %s" % (alias, self.aliases[alias])) return if args[0] in self.aliases and len(args) == 1: self.message("%s = %s" % (args[0], self.aliases[args[0]])) else: self.aliases[args[0]] = ' '.join(args[1:])
[ "def", "do_alias", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "keys", "=", "sorted", "(", "self", ".", "aliases", ".", "keys", "(", ")", ")", "for", "alias", "in", "keys", ":", "self", ".", "message", "(", "\"%s = %s\"", "%", "(", "alias", ",", "self", ".", "aliases", "[", "alias", "]", ")", ")", "return", "if", "args", "[", "0", "]", "in", "self", ".", "aliases", "and", "len", "(", "args", ")", "==", "1", ":", "self", ".", "message", "(", "\"%s = %s\"", "%", "(", "args", "[", "0", "]", ",", "self", ".", "aliases", "[", "args", "[", "0", "]", "]", ")", ")", "else", ":", "self", ".", "aliases", "[", "args", "[", "0", "]", "]", "=", "' '", ".", "join", "(", "args", "[", "1", ":", "]", ")" ]
alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. As an example, here are two useful aliases (especially when placed in the .pdbrc file): # Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) # Print instance variables in self alias ps pi self
[ "alias", "[", "name", "[", "command", "[", "parameter", "parameter", "...", "]", "]]", "Create", "an", "alias", "called", "name", "that", "executes", "command", ".", "The", "command", "must", "*", "not", "*", "be", "enclosed", "in", "quotes", ".", "Replaceable", "parameters", "can", "be", "indicated", "by", "%1", "%2", "and", "so", "on", "while", "%", "*", "is", "replaced", "by", "all", "the", "parameters", ".", "If", "no", "command", "is", "given", "the", "current", "alias", "for", "name", "is", "shown", ".", "If", "no", "name", "is", "given", "all", "aliases", "are", "listed", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1650-L1683
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_unalias
def do_unalias(self, arg): """unalias name Delete the specified alias. """ args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[0]]
python
def do_unalias(self, arg): """unalias name Delete the specified alias. """ args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[0]]
[ "def", "do_unalias", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "return", "if", "args", "[", "0", "]", "in", "self", ".", "aliases", ":", "del", "self", ".", "aliases", "[", "args", "[", "0", "]", "]" ]
unalias name Delete the specified alias.
[ "unalias", "name", "Delete", "the", "specified", "alias", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1685-L1692
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_thread
def do_thread(self, arg): """th(read) [threadnumber] Without argument, display a summary of all active threads. The summary prints for each thread: 1. the thread number assigned by pdb 2. the thread name 3. the python thread identifier 4. the current stack frame summary for that thread An asterisk '*' to the left of the pdb thread number indicates the current thread, a plus sign '+' indicates the thread being traced by pdb. With a pdb thread number as argument, make this thread the current thread. The 'where', 'up' and 'down' commands apply now to the frame stack of this thread. The current scope is now the frame currently executed by this thread at the time the command is issued and the 'list', 'll', 'args', 'p', 'pp', 'source' and 'interact' commands are run in the context of that frame. Note that this frame may bear no relationship (for a non-deadlocked thread) to that thread's current activity by the time you are examining the frame. This command does not stop the thread. """ # Import the threading module in the main interpreter to get an # enumeration of the main interpreter threads. if PY3: try: import threading except ImportError: import dummy_threading as threading else: # Do not use relative import detection to avoid the RuntimeWarning: # Parent module 'pdb_clone' not found while handling absolute # import. try: threading = __import__('threading', level=0) except ImportError: threading = __import__('dummy_threading', level=0) if not self.pdb_thread: self.pdb_thread = threading.current_thread() if not self.current_thread: self.current_thread = self.pdb_thread current_frames = sys._current_frames() tlist = sorted(threading.enumerate(), key=attrgetter('name', 'ident')) try: self._do_thread(arg, current_frames, tlist) finally: # For some reason this local must be explicitly deleted in order # to release the subinterpreter. del current_frames
python
def do_thread(self, arg): """th(read) [threadnumber] Without argument, display a summary of all active threads. The summary prints for each thread: 1. the thread number assigned by pdb 2. the thread name 3. the python thread identifier 4. the current stack frame summary for that thread An asterisk '*' to the left of the pdb thread number indicates the current thread, a plus sign '+' indicates the thread being traced by pdb. With a pdb thread number as argument, make this thread the current thread. The 'where', 'up' and 'down' commands apply now to the frame stack of this thread. The current scope is now the frame currently executed by this thread at the time the command is issued and the 'list', 'll', 'args', 'p', 'pp', 'source' and 'interact' commands are run in the context of that frame. Note that this frame may bear no relationship (for a non-deadlocked thread) to that thread's current activity by the time you are examining the frame. This command does not stop the thread. """ # Import the threading module in the main interpreter to get an # enumeration of the main interpreter threads. if PY3: try: import threading except ImportError: import dummy_threading as threading else: # Do not use relative import detection to avoid the RuntimeWarning: # Parent module 'pdb_clone' not found while handling absolute # import. try: threading = __import__('threading', level=0) except ImportError: threading = __import__('dummy_threading', level=0) if not self.pdb_thread: self.pdb_thread = threading.current_thread() if not self.current_thread: self.current_thread = self.pdb_thread current_frames = sys._current_frames() tlist = sorted(threading.enumerate(), key=attrgetter('name', 'ident')) try: self._do_thread(arg, current_frames, tlist) finally: # For some reason this local must be explicitly deleted in order # to release the subinterpreter. del current_frames
[ "def", "do_thread", "(", "self", ",", "arg", ")", ":", "# Import the threading module in the main interpreter to get an", "# enumeration of the main interpreter threads.", "if", "PY3", ":", "try", ":", "import", "threading", "except", "ImportError", ":", "import", "dummy_threading", "as", "threading", "else", ":", "# Do not use relative import detection to avoid the RuntimeWarning:", "# Parent module 'pdb_clone' not found while handling absolute", "# import.", "try", ":", "threading", "=", "__import__", "(", "'threading'", ",", "level", "=", "0", ")", "except", "ImportError", ":", "threading", "=", "__import__", "(", "'dummy_threading'", ",", "level", "=", "0", ")", "if", "not", "self", ".", "pdb_thread", ":", "self", ".", "pdb_thread", "=", "threading", ".", "current_thread", "(", ")", "if", "not", "self", ".", "current_thread", ":", "self", ".", "current_thread", "=", "self", ".", "pdb_thread", "current_frames", "=", "sys", ".", "_current_frames", "(", ")", "tlist", "=", "sorted", "(", "threading", ".", "enumerate", "(", ")", ",", "key", "=", "attrgetter", "(", "'name'", ",", "'ident'", ")", ")", "try", ":", "self", ".", "_do_thread", "(", "arg", ",", "current_frames", ",", "tlist", ")", "finally", ":", "# For some reason this local must be explicitly deleted in order", "# to release the subinterpreter.", "del", "current_frames" ]
th(read) [threadnumber] Without argument, display a summary of all active threads. The summary prints for each thread: 1. the thread number assigned by pdb 2. the thread name 3. the python thread identifier 4. the current stack frame summary for that thread An asterisk '*' to the left of the pdb thread number indicates the current thread, a plus sign '+' indicates the thread being traced by pdb. With a pdb thread number as argument, make this thread the current thread. The 'where', 'up' and 'down' commands apply now to the frame stack of this thread. The current scope is now the frame currently executed by this thread at the time the command is issued and the 'list', 'll', 'args', 'p', 'pp', 'source' and 'interact' commands are run in the context of that frame. Note that this frame may bear no relationship (for a non-deadlocked thread) to that thread's current activity by the time you are examining the frame. This command does not stop the thread.
[ "th", "(", "read", ")", "[", "threadnumber", "]", "Without", "argument", "display", "a", "summary", "of", "all", "active", "threads", ".", "The", "summary", "prints", "for", "each", "thread", ":", "1", ".", "the", "thread", "number", "assigned", "by", "pdb", "2", ".", "the", "thread", "name", "3", ".", "the", "python", "thread", "identifier", "4", ".", "the", "current", "stack", "frame", "summary", "for", "that", "thread", "An", "asterisk", "*", "to", "the", "left", "of", "the", "pdb", "thread", "number", "indicates", "the", "current", "thread", "a", "plus", "sign", "+", "indicates", "the", "thread", "being", "traced", "by", "pdb", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1740-L1790
train
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.do_help
def do_help(self, arg): """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command. """ if not arg: return cmd.Cmd.do_help(self, arg) try: try: topic = getattr(self, 'help_' + arg) return topic() except AttributeError: command = getattr(self, 'do_' + arg) except AttributeError: self.error('No help for %r' % arg) else: if sys.flags.optimize >= 2: self.error('No help for %r; please do not run Python with -OO ' 'if you need command help' % arg) return self.message(command.__doc__.rstrip())
python
def do_help(self, arg): """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command. """ if not arg: return cmd.Cmd.do_help(self, arg) try: try: topic = getattr(self, 'help_' + arg) return topic() except AttributeError: command = getattr(self, 'do_' + arg) except AttributeError: self.error('No help for %r' % arg) else: if sys.flags.optimize >= 2: self.error('No help for %r; please do not run Python with -OO ' 'if you need command help' % arg) return self.message(command.__doc__.rstrip())
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "return", "cmd", ".", "Cmd", ".", "do_help", "(", "self", ",", "arg", ")", "try", ":", "try", ":", "topic", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", ")", "return", "topic", "(", ")", "except", "AttributeError", ":", "command", "=", "getattr", "(", "self", ",", "'do_'", "+", "arg", ")", "except", "AttributeError", ":", "self", ".", "error", "(", "'No help for %r'", "%", "arg", ")", "else", ":", "if", "sys", ".", "flags", ".", "optimize", ">=", "2", ":", "self", ".", "error", "(", "'No help for %r; please do not run Python with -OO '", "'if you need command help'", "%", "arg", ")", "return", "self", ".", "message", "(", "command", ".", "__doc__", ".", "rstrip", "(", ")", ")" ]
h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command.
[ "h", "(", "elp", ")", "Without", "argument", "print", "the", "list", "of", "available", "commands", ".", "With", "a", "command", "name", "as", "argument", "print", "help", "about", "that", "command", ".", "help", "pdb", "shows", "the", "full", "pdb", "documentation", ".", "help", "exec", "gives", "help", "on", "the", "!", "command", "." ]
f781537c243a4874b246d43dbdef8c4279f0094d
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1825-L1847
train