repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
Nukesor/pueue
pueue/client/socket.py
receive_data
def receive_data(socket): """Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. Returns: dir or string: The unpickled answer. """ answer = b"" while True: packet = socket.recv(4096) if not packet: break answer += packet response = pickle.loads(answer) socket.close() return response
python
def receive_data(socket): """Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. Returns: dir or string: The unpickled answer. """ answer = b"" while True: packet = socket.recv(4096) if not packet: break answer += packet response = pickle.loads(answer) socket.close() return response
[ "def", "receive_data", "(", "socket", ")", ":", "answer", "=", "b\"\"", "while", "True", ":", "packet", "=", "socket", ".", "recv", "(", "4096", ")", "if", "not", "packet", ":", "break", "answer", "+=", "packet", "response", "=", "pickle", ".", "loads", "(", "answer", ")", "socket", ".", "close", "(", ")", "return", "response" ]
Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. Returns: dir or string: The unpickled answer.
[ "Receive", "an", "answer", "from", "the", "daemon", "and", "return", "the", "response", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/client/socket.py#L7-L23
Nukesor/pueue
pueue/client/socket.py
connect_socket
def connect_socket(root_dir): """Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A socket that is connected to the daemon. """ # Get config directory where the daemon socket is located config_dir = os.path.join(root_dir, '.config/pueue') # Create Socket and exit with 1, if socket can't be created try: client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket_path = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socket_path): client.connect(socket_path) else: print("Socket doesn't exist") raise Exception except: print("Error connecting to socket. Make sure the daemon is running") sys.exit(1) return client
python
def connect_socket(root_dir): """Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A socket that is connected to the daemon. """ # Get config directory where the daemon socket is located config_dir = os.path.join(root_dir, '.config/pueue') # Create Socket and exit with 1, if socket can't be created try: client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket_path = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socket_path): client.connect(socket_path) else: print("Socket doesn't exist") raise Exception except: print("Error connecting to socket. Make sure the daemon is running") sys.exit(1) return client
[ "def", "connect_socket", "(", "root_dir", ")", ":", "# Get config directory where the daemon socket is located", "config_dir", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'.config/pueue'", ")", "# Create Socket and exit with 1, if socket can't be created", "try", ":", "client", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ")", "socket_path", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "'pueue.sock'", ")", "if", "os", ".", "path", ".", "exists", "(", "socket_path", ")", ":", "client", ".", "connect", "(", "socket_path", ")", "else", ":", "print", "(", "\"Socket doesn't exist\"", ")", "raise", "Exception", "except", ":", "print", "(", "\"Error connecting to socket. Make sure the daemon is running\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "client" ]
Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A socket that is connected to the daemon.
[ "Connect", "to", "a", "daemon", "s", "socket", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/client/socket.py#L34-L58
dlecocq/nsq-py
nsq/response.py
Response.from_raw
def from_raw(conn, raw): '''Return a new response from a raw buffer''' frame_type = struct.unpack('>l', raw[0:4])[0] message = raw[4:] if frame_type == FRAME_TYPE_MESSAGE: return Message(conn, frame_type, message) elif frame_type == FRAME_TYPE_RESPONSE: return Response(conn, frame_type, message) elif frame_type == FRAME_TYPE_ERROR: return Error(conn, frame_type, message) else: raise TypeError('Unknown frame type: %s' % frame_type)
python
def from_raw(conn, raw): '''Return a new response from a raw buffer''' frame_type = struct.unpack('>l', raw[0:4])[0] message = raw[4:] if frame_type == FRAME_TYPE_MESSAGE: return Message(conn, frame_type, message) elif frame_type == FRAME_TYPE_RESPONSE: return Response(conn, frame_type, message) elif frame_type == FRAME_TYPE_ERROR: return Error(conn, frame_type, message) else: raise TypeError('Unknown frame type: %s' % frame_type)
[ "def", "from_raw", "(", "conn", ",", "raw", ")", ":", "frame_type", "=", "struct", ".", "unpack", "(", "'>l'", ",", "raw", "[", "0", ":", "4", "]", ")", "[", "0", "]", "message", "=", "raw", "[", "4", ":", "]", "if", "frame_type", "==", "FRAME_TYPE_MESSAGE", ":", "return", "Message", "(", "conn", ",", "frame_type", ",", "message", ")", "elif", "frame_type", "==", "FRAME_TYPE_RESPONSE", ":", "return", "Response", "(", "conn", ",", "frame_type", ",", "message", ")", "elif", "frame_type", "==", "FRAME_TYPE_ERROR", ":", "return", "Error", "(", "conn", ",", "frame_type", ",", "message", ")", "else", ":", "raise", "TypeError", "(", "'Unknown frame type: %s'", "%", "frame_type", ")" ]
Return a new response from a raw buffer
[ "Return", "a", "new", "response", "from", "a", "raw", "buffer" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L19-L30
dlecocq/nsq-py
nsq/response.py
Response.pack
def pack(cls, data): '''Pack the provided data into a Response''' return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + data
python
def pack(cls, data): '''Pack the provided data into a Response''' return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + data
[ "def", "pack", "(", "cls", ",", "data", ")", ":", "return", "struct", ".", "pack", "(", "'>ll'", ",", "len", "(", "data", ")", "+", "4", ",", "cls", ".", "FRAME_TYPE", ")", "+", "data" ]
Pack the provided data into a Response
[ "Pack", "the", "provided", "data", "into", "a", "Response" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L33-L35
dlecocq/nsq-py
nsq/response.py
Message.fin
def fin(self): '''Indicate that this message is finished processing''' self.connection.fin(self.id) self.processed = True
python
def fin(self): '''Indicate that this message is finished processing''' self.connection.fin(self.id) self.processed = True
[ "def", "fin", "(", "self", ")", ":", "self", ".", "connection", ".", "fin", "(", "self", ".", "id", ")", "self", ".", "processed", "=", "True" ]
Indicate that this message is finished processing
[ "Indicate", "that", "this", "message", "is", "finished", "processing" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L86-L89
dlecocq/nsq-py
nsq/response.py
Message.req
def req(self, timeout): '''Re-queue a message''' self.connection.req(self.id, timeout) self.processed = True
python
def req(self, timeout): '''Re-queue a message''' self.connection.req(self.id, timeout) self.processed = True
[ "def", "req", "(", "self", ",", "timeout", ")", ":", "self", ".", "connection", ".", "req", "(", "self", ".", "id", ",", "timeout", ")", "self", ".", "processed", "=", "True" ]
Re-queue a message
[ "Re", "-", "queue", "a", "message" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L91-L94
dlecocq/nsq-py
nsq/response.py
Message.handle
def handle(self): '''Make sure this message gets either 'fin' or 'req'd''' try: yield self except: # Requeue the message and raise the original exception typ, value, trace = sys.exc_info() if not self.processed: try: self.req(self.delay()) except socket.error: self.connection.close() raise typ, value, trace else: if not self.processed: try: self.fin() except socket.error: self.connection.close()
python
def handle(self): '''Make sure this message gets either 'fin' or 'req'd''' try: yield self except: # Requeue the message and raise the original exception typ, value, trace = sys.exc_info() if not self.processed: try: self.req(self.delay()) except socket.error: self.connection.close() raise typ, value, trace else: if not self.processed: try: self.fin() except socket.error: self.connection.close()
[ "def", "handle", "(", "self", ")", ":", "try", ":", "yield", "self", "except", ":", "# Requeue the message and raise the original exception", "typ", ",", "value", ",", "trace", "=", "sys", ".", "exc_info", "(", ")", "if", "not", "self", ".", "processed", ":", "try", ":", "self", ".", "req", "(", "self", ".", "delay", "(", ")", ")", "except", "socket", ".", "error", ":", "self", ".", "connection", ".", "close", "(", ")", "raise", "typ", ",", "value", ",", "trace", "else", ":", "if", "not", "self", ".", "processed", ":", "try", ":", "self", ".", "fin", "(", ")", "except", "socket", ".", "error", ":", "self", ".", "connection", ".", "close", "(", ")" ]
Make sure this message gets either 'fin' or 'req'd
[ "Make", "sure", "this", "message", "gets", "either", "fin", "or", "req", "d" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L105-L123
dlecocq/nsq-py
nsq/response.py
Error.find
def find(cls, name): '''Find the exception class by name''' if not cls.mapping: # pragma: no branch for _, obj in inspect.getmembers(exceptions): if inspect.isclass(obj): if issubclass(obj, exceptions.NSQException): # pragma: no branch if hasattr(obj, 'name'): cls.mapping[obj.name] = obj klass = cls.mapping.get(name) if klass == None: raise TypeError('No matching exception for %s' % name) return klass
python
def find(cls, name): '''Find the exception class by name''' if not cls.mapping: # pragma: no branch for _, obj in inspect.getmembers(exceptions): if inspect.isclass(obj): if issubclass(obj, exceptions.NSQException): # pragma: no branch if hasattr(obj, 'name'): cls.mapping[obj.name] = obj klass = cls.mapping.get(name) if klass == None: raise TypeError('No matching exception for %s' % name) return klass
[ "def", "find", "(", "cls", ",", "name", ")", ":", "if", "not", "cls", ".", "mapping", ":", "# pragma: no branch", "for", "_", ",", "obj", "in", "inspect", ".", "getmembers", "(", "exceptions", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "if", "issubclass", "(", "obj", ",", "exceptions", ".", "NSQException", ")", ":", "# pragma: no branch", "if", "hasattr", "(", "obj", ",", "'name'", ")", ":", "cls", ".", "mapping", "[", "obj", ".", "name", "]", "=", "obj", "klass", "=", "cls", ".", "mapping", ".", "get", "(", "name", ")", "if", "klass", "==", "None", ":", "raise", "TypeError", "(", "'No matching exception for %s'", "%", "name", ")", "return", "klass" ]
Find the exception class by name
[ "Find", "the", "exception", "class", "by", "name" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L134-L145
dlecocq/nsq-py
nsq/response.py
Error.exception
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
python
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
[ "def", "exception", "(", "self", ")", ":", "code", ",", "_", ",", "message", "=", "self", ".", "data", ".", "partition", "(", "' '", ")", "return", "self", ".", "find", "(", "code", ")", "(", "message", ")" ]
Return an instance of the corresponding exception
[ "Return", "an", "instance", "of", "the", "corresponding", "exception" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/response.py#L147-L150
corpusops/pdbclone
lib/pdb_clone/attach.py
parse_gdb_version
def parse_gdb_version(line): r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line. >>> DOCTEST_GDB_VERSIONS = [ ... r'~"GNU gdb (GDB) 7.5.1\n"', ... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-cvs\n"', ... r'~"GNU gdb (GDB) SUSE (7.5.1-2.5.1)\n"', ... r'~"GNU gdb (GDB) Fedora (7.6-32.fc19)\n"', ... r'~"GNU gdb (GDB) 7.6.1.dummy\n"', ... ] >>> for header in DOCTEST_GDB_VERSIONS: ... print(parse_gdb_version(header)) 7.5.1 7.2.50.20100908 7.5.1 7.6 7.6.1 """ if line.startswith('~"') and line.endswith(r'\n"'): version = line[2:-3].rsplit(' ', 1) if len(version) == 2: # Strip after first non digit or '.' character. Allow for linux # Suse non conformant implementation that encloses the version in # brackets. version = ''.join(takewhile(lambda x: x.isdigit() or x == '.', version[1].lstrip('('))) return version.strip('.') return ''
python
def parse_gdb_version(line): r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line. >>> DOCTEST_GDB_VERSIONS = [ ... r'~"GNU gdb (GDB) 7.5.1\n"', ... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-cvs\n"', ... r'~"GNU gdb (GDB) SUSE (7.5.1-2.5.1)\n"', ... r'~"GNU gdb (GDB) Fedora (7.6-32.fc19)\n"', ... r'~"GNU gdb (GDB) 7.6.1.dummy\n"', ... ] >>> for header in DOCTEST_GDB_VERSIONS: ... print(parse_gdb_version(header)) 7.5.1 7.2.50.20100908 7.5.1 7.6 7.6.1 """ if line.startswith('~"') and line.endswith(r'\n"'): version = line[2:-3].rsplit(' ', 1) if len(version) == 2: # Strip after first non digit or '.' character. Allow for linux # Suse non conformant implementation that encloses the version in # brackets. version = ''.join(takewhile(lambda x: x.isdigit() or x == '.', version[1].lstrip('('))) return version.strip('.') return ''
[ "def", "parse_gdb_version", "(", "line", ")", ":", "if", "line", ".", "startswith", "(", "'~\"'", ")", "and", "line", ".", "endswith", "(", "r'\\n\"'", ")", ":", "version", "=", "line", "[", "2", ":", "-", "3", "]", ".", "rsplit", "(", "' '", ",", "1", ")", "if", "len", "(", "version", ")", "==", "2", ":", "# Strip after first non digit or '.' character. Allow for linux", "# Suse non conformant implementation that encloses the version in", "# brackets.", "version", "=", "''", ".", "join", "(", "takewhile", "(", "lambda", "x", ":", "x", ".", "isdigit", "(", ")", "or", "x", "==", "'.'", ",", "version", "[", "1", "]", ".", "lstrip", "(", "'('", ")", ")", ")", "return", "version", ".", "strip", "(", "'.'", ")", "return", "''" ]
r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line. >>> DOCTEST_GDB_VERSIONS = [ ... r'~"GNU gdb (GDB) 7.5.1\n"', ... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-cvs\n"', ... r'~"GNU gdb (GDB) SUSE (7.5.1-2.5.1)\n"', ... r'~"GNU gdb (GDB) Fedora (7.6-32.fc19)\n"', ... r'~"GNU gdb (GDB) 7.6.1.dummy\n"', ... ] >>> for header in DOCTEST_GDB_VERSIONS: ... print(parse_gdb_version(header)) 7.5.1 7.2.50.20100908 7.5.1 7.6 7.6.1
[ "r", "Parse", "the", "gdb", "version", "from", "the", "gdb", "header", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/attach.py#L466-L497
corpusops/pdbclone
lib/pdb_clone/attach.py
spawn_gdb
def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False, ctx=None, proc_iut=None): """Spawn gdb and attach to a process.""" parent, child = socket.socketpair() proc = Popen([gdb, '--interpreter=mi', '-nx'], bufsize=0, stdin=child, stdout=child, stderr=STDOUT) child.close() connections = {} gdb = GdbSocket(ctx, address, proc, proc_iut, parent, verbose, connections) gdb.mi_command('-target-attach %d' % pid) gdb.cli_command('python import pdb_clone.bootstrappdb_gdb') asyncore.loop(map=connections) proc.wait() return gdb.error
python
def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False, ctx=None, proc_iut=None): """Spawn gdb and attach to a process.""" parent, child = socket.socketpair() proc = Popen([gdb, '--interpreter=mi', '-nx'], bufsize=0, stdin=child, stdout=child, stderr=STDOUT) child.close() connections = {} gdb = GdbSocket(ctx, address, proc, proc_iut, parent, verbose, connections) gdb.mi_command('-target-attach %d' % pid) gdb.cli_command('python import pdb_clone.bootstrappdb_gdb') asyncore.loop(map=connections) proc.wait() return gdb.error
[ "def", "spawn_gdb", "(", "pid", ",", "address", "=", "DFLT_ADDRESS", ",", "gdb", "=", "'gdb'", ",", "verbose", "=", "False", ",", "ctx", "=", "None", ",", "proc_iut", "=", "None", ")", ":", "parent", ",", "child", "=", "socket", ".", "socketpair", "(", ")", "proc", "=", "Popen", "(", "[", "gdb", ",", "'--interpreter=mi'", ",", "'-nx'", "]", ",", "bufsize", "=", "0", ",", "stdin", "=", "child", ",", "stdout", "=", "child", ",", "stderr", "=", "STDOUT", ")", "child", ".", "close", "(", ")", "connections", "=", "{", "}", "gdb", "=", "GdbSocket", "(", "ctx", ",", "address", ",", "proc", ",", "proc_iut", ",", "parent", ",", "verbose", ",", "connections", ")", "gdb", ".", "mi_command", "(", "'-target-attach %d'", "%", "pid", ")", "gdb", ".", "cli_command", "(", "'python import pdb_clone.bootstrappdb_gdb'", ")", "asyncore", ".", "loop", "(", "map", "=", "connections", ")", "proc", ".", "wait", "(", ")", "return", "gdb", ".", "error" ]
Spawn gdb and attach to a process.
[ "Spawn", "gdb", "and", "attach", "to", "a", "process", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/attach.py#L503-L519
corpusops/pdbclone
lib/pdb_clone/attach.py
attach_loop
def attach_loop(argv): """Spawn the process, then repeatedly attach to the process.""" # Check if the pdbhandler module is built into python. p = Popen((sys.executable, '-X', 'pdbhandler', '-c', 'import pdbhandler; pdbhandler.get_handler().host'), stdout=PIPE, stderr=STDOUT) p.wait() use_xoption = True if p.returncode == 0 else False # Spawn the process. args = [sys.executable] if use_xoption: # Use SIGUSR2 as faulthandler is set on python test suite with # SIGUSR1. args.extend(['-X', 'pdbhandler=localhost 7935 %d' % signal.SIGUSR2]) args.extend(argv) proc = Popen(args) else: args.extend(argv) proc = Popen(args) # Repeatedly attach to the process using the '-X' python option or gdb. ctx = Context() error = None time.sleep(.5 + random.random()) while not error and proc.poll() is None: if use_xoption: os.kill(proc.pid, signal.SIGUSR2) connections = {} dev_null = io.StringIO() if PY3 else StringIO.StringIO() asock = AttachSocketWithDetach(connections, stdout=dev_null) asock.create_socket(socket.AF_INET, socket.SOCK_STREAM) connect_process(asock, ctx, proc) asyncore.loop(map=connections) else: error = spawn_gdb(proc.pid, ctx=ctx, proc_iut=proc) time.sleep(random.random()) if error and gdb_terminated(error): error = None if proc.poll() is None: proc.terminate() else: print('pdb-attach: program under test return code:', proc.wait()) result = str(ctx.result) if result: print(result) return error
python
def attach_loop(argv): """Spawn the process, then repeatedly attach to the process.""" # Check if the pdbhandler module is built into python. p = Popen((sys.executable, '-X', 'pdbhandler', '-c', 'import pdbhandler; pdbhandler.get_handler().host'), stdout=PIPE, stderr=STDOUT) p.wait() use_xoption = True if p.returncode == 0 else False # Spawn the process. args = [sys.executable] if use_xoption: # Use SIGUSR2 as faulthandler is set on python test suite with # SIGUSR1. args.extend(['-X', 'pdbhandler=localhost 7935 %d' % signal.SIGUSR2]) args.extend(argv) proc = Popen(args) else: args.extend(argv) proc = Popen(args) # Repeatedly attach to the process using the '-X' python option or gdb. ctx = Context() error = None time.sleep(.5 + random.random()) while not error and proc.poll() is None: if use_xoption: os.kill(proc.pid, signal.SIGUSR2) connections = {} dev_null = io.StringIO() if PY3 else StringIO.StringIO() asock = AttachSocketWithDetach(connections, stdout=dev_null) asock.create_socket(socket.AF_INET, socket.SOCK_STREAM) connect_process(asock, ctx, proc) asyncore.loop(map=connections) else: error = spawn_gdb(proc.pid, ctx=ctx, proc_iut=proc) time.sleep(random.random()) if error and gdb_terminated(error): error = None if proc.poll() is None: proc.terminate() else: print('pdb-attach: program under test return code:', proc.wait()) result = str(ctx.result) if result: print(result) return error
[ "def", "attach_loop", "(", "argv", ")", ":", "# Check if the pdbhandler module is built into python.", "p", "=", "Popen", "(", "(", "sys", ".", "executable", ",", "'-X'", ",", "'pdbhandler'", ",", "'-c'", ",", "'import pdbhandler; pdbhandler.get_handler().host'", ")", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT", ")", "p", ".", "wait", "(", ")", "use_xoption", "=", "True", "if", "p", ".", "returncode", "==", "0", "else", "False", "# Spawn the process.", "args", "=", "[", "sys", ".", "executable", "]", "if", "use_xoption", ":", "# Use SIGUSR2 as faulthandler is set on python test suite with", "# SIGUSR1.", "args", ".", "extend", "(", "[", "'-X'", ",", "'pdbhandler=localhost 7935 %d'", "%", "signal", ".", "SIGUSR2", "]", ")", "args", ".", "extend", "(", "argv", ")", "proc", "=", "Popen", "(", "args", ")", "else", ":", "args", ".", "extend", "(", "argv", ")", "proc", "=", "Popen", "(", "args", ")", "# Repeatedly attach to the process using the '-X' python option or gdb.", "ctx", "=", "Context", "(", ")", "error", "=", "None", "time", ".", "sleep", "(", ".5", "+", "random", ".", "random", "(", ")", ")", "while", "not", "error", "and", "proc", ".", "poll", "(", ")", "is", "None", ":", "if", "use_xoption", ":", "os", ".", "kill", "(", "proc", ".", "pid", ",", "signal", ".", "SIGUSR2", ")", "connections", "=", "{", "}", "dev_null", "=", "io", ".", "StringIO", "(", ")", "if", "PY3", "else", "StringIO", ".", "StringIO", "(", ")", "asock", "=", "AttachSocketWithDetach", "(", "connections", ",", "stdout", "=", "dev_null", ")", "asock", ".", "create_socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "connect_process", "(", "asock", ",", "ctx", ",", "proc", ")", "asyncore", ".", "loop", "(", "map", "=", "connections", ")", "else", ":", "error", "=", "spawn_gdb", "(", "proc", ".", "pid", ",", "ctx", "=", "ctx", ",", "proc_iut", "=", "proc", ")", "time", ".", "sleep", "(", "random", ".", "random", "(", ")", ")", "if", "error", "and", "gdb_terminated", "(", "error", ")", ":", "error", "=", "None", "if", "proc", ".", "poll", "(", ")", "is", "None", ":", "proc", ".", "terminate", "(", ")", "else", ":", "print", "(", "'pdb-attach: program under test return code:'", ",", "proc", ".", "wait", "(", ")", ")", "result", "=", "str", "(", "ctx", ".", "result", ")", "if", "result", ":", "print", "(", "result", ")", "return", "error" ]
Spawn the process, then repeatedly attach to the process.
[ "Spawn", "the", "process", "then", "repeatedly", "attach", "to", "the", "process", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/attach.py#L521-L570
corpusops/pdbclone
lib/pdb_clone/attach.py
StatementLine.skip
def skip(self): """Skip this py-pdb command to avoid attaching within the same loop.""" line = self.line self.line = '' # 'line' is the statement line of the previous py-pdb command. if line in self.lines: if not self.skipping: self.skipping = True printflush('Skipping lines', end='') printflush('.', end='') return True elif line: self.lines.append(line) if len(self.lines) > 30: self.lines.popleft() return False
python
def skip(self): """Skip this py-pdb command to avoid attaching within the same loop.""" line = self.line self.line = '' # 'line' is the statement line of the previous py-pdb command. if line in self.lines: if not self.skipping: self.skipping = True printflush('Skipping lines', end='') printflush('.', end='') return True elif line: self.lines.append(line) if len(self.lines) > 30: self.lines.popleft() return False
[ "def", "skip", "(", "self", ")", ":", "line", "=", "self", ".", "line", "self", ".", "line", "=", "''", "# 'line' is the statement line of the previous py-pdb command.", "if", "line", "in", "self", ".", "lines", ":", "if", "not", "self", ".", "skipping", ":", "self", ".", "skipping", "=", "True", "printflush", "(", "'Skipping lines'", ",", "end", "=", "''", ")", "printflush", "(", "'.'", ",", "end", "=", "''", ")", "return", "True", "elif", "line", ":", "self", ".", "lines", ".", "append", "(", "line", ")", "if", "len", "(", "self", ".", "lines", ")", ">", "30", ":", "self", ".", "lines", ".", "popleft", "(", ")", "return", "False" ]
Skip this py-pdb command to avoid attaching within the same loop.
[ "Skip", "this", "py", "-", "pdb", "command", "to", "avoid", "attaching", "within", "the", "same", "loop", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/attach.py#L242-L259
Nukesor/pueue
pueue/daemon/logger.py
Logger.rotate
def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file.""" self.write(log, rotate=True) self.write({})
python
def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file.""" self.write(log, rotate=True) self.write({})
[ "def", "rotate", "(", "self", ",", "log", ")", ":", "self", ".", "write", "(", "log", ",", "rotate", "=", "True", ")", "self", ".", "write", "(", "{", "}", ")" ]
Move the current log to a new file with timestamp and create a new empty log file.
[ "Move", "the", "current", "log", "to", "a", "new", "file", "with", "timestamp", "and", "create", "a", "new", "empty", "log", "file", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/logger.py#L72-L75
Nukesor/pueue
pueue/daemon/logger.py
Logger.write
def write(self, log, rotate=False): """Write the output of all finished processes to a compiled log file.""" # Get path for logfile if rotate: timestamp = time.strftime('-%Y%m%d-%H%M') logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp)) else: logPath = os.path.join(self.log_dir, 'queue.log') # Remove existing Log if os.path.exists(logPath): os.remove(logPath) log_file = open(logPath, 'w') log_file.write('Pueue log for executed Commands: \n \n') # Format, color and write log for key, logentry in log.items(): if logentry.get('returncode') is not None: try: # Get returncode color: returncode = logentry['returncode'] if returncode == 0: returncode = Color('{autogreen}' + '{}'.format(returncode) + '{/autogreen}') else: returncode = Color('{autored}' + '{}'.format(returncode) + '{/autored}') # Write command id with returncode and actual command log_file.write( Color('{autoyellow}' + 'Command #{} '.format(key) + '{/autoyellow}') + 'exited with returncode {}: \n'.format(returncode) + '"{}" \n'.format(logentry['command']) ) # Write path log_file.write('Path: {} \n'.format(logentry['path'])) # Write times log_file.write('Start: {}, End: {} \n' .format(logentry['start'], logentry['end'])) # Write STDERR if logentry['stderr']: log_file.write(Color('{autored}Stderr output: {/autored}\n ') + logentry['stderr']) # Write STDOUT if len(logentry['stdout']) > 0: log_file.write(Color('{autogreen}Stdout output: {/autogreen}\n ') + logentry['stdout']) log_file.write('\n') except Exception as a: print('Failed while writing to log file. Wrong file permissions?') print('Exception: {}'.format(str(a))) log_file.close()
python
def write(self, log, rotate=False): """Write the output of all finished processes to a compiled log file.""" # Get path for logfile if rotate: timestamp = time.strftime('-%Y%m%d-%H%M') logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp)) else: logPath = os.path.join(self.log_dir, 'queue.log') # Remove existing Log if os.path.exists(logPath): os.remove(logPath) log_file = open(logPath, 'w') log_file.write('Pueue log for executed Commands: \n \n') # Format, color and write log for key, logentry in log.items(): if logentry.get('returncode') is not None: try: # Get returncode color: returncode = logentry['returncode'] if returncode == 0: returncode = Color('{autogreen}' + '{}'.format(returncode) + '{/autogreen}') else: returncode = Color('{autored}' + '{}'.format(returncode) + '{/autored}') # Write command id with returncode and actual command log_file.write( Color('{autoyellow}' + 'Command #{} '.format(key) + '{/autoyellow}') + 'exited with returncode {}: \n'.format(returncode) + '"{}" \n'.format(logentry['command']) ) # Write path log_file.write('Path: {} \n'.format(logentry['path'])) # Write times log_file.write('Start: {}, End: {} \n' .format(logentry['start'], logentry['end'])) # Write STDERR if logentry['stderr']: log_file.write(Color('{autored}Stderr output: {/autored}\n ') + logentry['stderr']) # Write STDOUT if len(logentry['stdout']) > 0: log_file.write(Color('{autogreen}Stdout output: {/autogreen}\n ') + logentry['stdout']) log_file.write('\n') except Exception as a: print('Failed while writing to log file. Wrong file permissions?') print('Exception: {}'.format(str(a))) log_file.close()
[ "def", "write", "(", "self", ",", "log", ",", "rotate", "=", "False", ")", ":", "# Get path for logfile", "if", "rotate", ":", "timestamp", "=", "time", ".", "strftime", "(", "'-%Y%m%d-%H%M'", ")", "logPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "log_dir", ",", "'queue{}.log'", ".", "format", "(", "timestamp", ")", ")", "else", ":", "logPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "log_dir", ",", "'queue.log'", ")", "# Remove existing Log", "if", "os", ".", "path", ".", "exists", "(", "logPath", ")", ":", "os", ".", "remove", "(", "logPath", ")", "log_file", "=", "open", "(", "logPath", ",", "'w'", ")", "log_file", ".", "write", "(", "'Pueue log for executed Commands: \\n \\n'", ")", "# Format, color and write log", "for", "key", ",", "logentry", "in", "log", ".", "items", "(", ")", ":", "if", "logentry", ".", "get", "(", "'returncode'", ")", "is", "not", "None", ":", "try", ":", "# Get returncode color:", "returncode", "=", "logentry", "[", "'returncode'", "]", "if", "returncode", "==", "0", ":", "returncode", "=", "Color", "(", "'{autogreen}'", "+", "'{}'", ".", "format", "(", "returncode", ")", "+", "'{/autogreen}'", ")", "else", ":", "returncode", "=", "Color", "(", "'{autored}'", "+", "'{}'", ".", "format", "(", "returncode", ")", "+", "'{/autored}'", ")", "# Write command id with returncode and actual command", "log_file", ".", "write", "(", "Color", "(", "'{autoyellow}'", "+", "'Command #{} '", ".", "format", "(", "key", ")", "+", "'{/autoyellow}'", ")", "+", "'exited with returncode {}: \\n'", ".", "format", "(", "returncode", ")", "+", "'\"{}\" \\n'", ".", "format", "(", "logentry", "[", "'command'", "]", ")", ")", "# Write path", "log_file", ".", "write", "(", "'Path: {} \\n'", ".", "format", "(", "logentry", "[", "'path'", "]", ")", ")", "# Write times", "log_file", ".", "write", "(", "'Start: {}, End: {} \\n'", ".", "format", "(", "logentry", "[", "'start'", "]", ",", "logentry", "[", "'end'", "]", ")", ")", "# Write STDERR", "if", "logentry", "[", "'stderr'", "]", ":", "log_file", ".", "write", "(", "Color", "(", "'{autored}Stderr output: {/autored}\\n '", ")", "+", "logentry", "[", "'stderr'", "]", ")", "# Write STDOUT", "if", "len", "(", "logentry", "[", "'stdout'", "]", ")", ">", "0", ":", "log_file", ".", "write", "(", "Color", "(", "'{autogreen}Stdout output: {/autogreen}\\n '", ")", "+", "logentry", "[", "'stdout'", "]", ")", "log_file", ".", "write", "(", "'\\n'", ")", "except", "Exception", "as", "a", ":", "print", "(", "'Failed while writing to log file. Wrong file permissions?'", ")", "print", "(", "'Exception: {}'", ".", "format", "(", "str", "(", "a", ")", ")", ")", "log_file", ".", "close", "(", ")" ]
Write the output of all finished processes to a compiled log file.
[ "Write", "the", "output", "of", "all", "finished", "processes", "to", "a", "compiled", "log", "file", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/logger.py#L77-L129
Nukesor/pueue
pueue/daemon/logger.py
Logger.remove_old
def remove_old(self, max_log_time): """Remove all logs which are older than the specified time.""" files = glob.glob('{}/queue-*'.format(self.log_dir)) files = list(map(lambda x: os.path.basename(x), files)) for log_file in files: # Get time stamp from filename name = os.path.splitext(log_file)[0] timestamp = name.split('-', maxsplit=1)[1] # Get datetime from time stamp time = datetime.strptime(timestamp, '%Y%m%d-%H%M') now = datetime.now() # Get total delta in seconds delta = now - time seconds = delta.total_seconds() # Delete log file, if the delta is bigger than the specified log time if seconds > int(max_log_time): log_filePath = os.path.join(self.log_dir, log_file) os.remove(log_filePath)
python
def remove_old(self, max_log_time): """Remove all logs which are older than the specified time.""" files = glob.glob('{}/queue-*'.format(self.log_dir)) files = list(map(lambda x: os.path.basename(x), files)) for log_file in files: # Get time stamp from filename name = os.path.splitext(log_file)[0] timestamp = name.split('-', maxsplit=1)[1] # Get datetime from time stamp time = datetime.strptime(timestamp, '%Y%m%d-%H%M') now = datetime.now() # Get total delta in seconds delta = now - time seconds = delta.total_seconds() # Delete log file, if the delta is bigger than the specified log time if seconds > int(max_log_time): log_filePath = os.path.join(self.log_dir, log_file) os.remove(log_filePath)
[ "def", "remove_old", "(", "self", ",", "max_log_time", ")", ":", "files", "=", "glob", ".", "glob", "(", "'{}/queue-*'", ".", "format", "(", "self", ".", "log_dir", ")", ")", "files", "=", "list", "(", "map", "(", "lambda", "x", ":", "os", ".", "path", ".", "basename", "(", "x", ")", ",", "files", ")", ")", "for", "log_file", "in", "files", ":", "# Get time stamp from filename", "name", "=", "os", ".", "path", ".", "splitext", "(", "log_file", ")", "[", "0", "]", "timestamp", "=", "name", ".", "split", "(", "'-'", ",", "maxsplit", "=", "1", ")", "[", "1", "]", "# Get datetime from time stamp", "time", "=", "datetime", ".", "strptime", "(", "timestamp", ",", "'%Y%m%d-%H%M'", ")", "now", "=", "datetime", ".", "now", "(", ")", "# Get total delta in seconds", "delta", "=", "now", "-", "time", "seconds", "=", "delta", ".", "total_seconds", "(", ")", "# Delete log file, if the delta is bigger than the specified log time", "if", "seconds", ">", "int", "(", "max_log_time", ")", ":", "log_filePath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "log_dir", ",", "log_file", ")", "os", ".", "remove", "(", "log_filePath", ")" ]
Remove all logs which are older than the specified time.
[ "Remove", "all", "logs", "which", "are", "older", "than", "the", "specified", "time", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/logger.py#L131-L152
dlecocq/nsq-py
nsq/http/__init__.py
wrap
def wrap(function, *args, **kwargs): '''Wrap a function that returns a request with some exception handling''' try: req = function(*args, **kwargs) logger.debug('Got %s: %s', req.status_code, req.content) if req.status_code == 200: return req else: raise ClientException(req.reason, req.content) except ClientException: raise except Exception as exc: raise ClientException(exc)
python
def wrap(function, *args, **kwargs): '''Wrap a function that returns a request with some exception handling''' try: req = function(*args, **kwargs) logger.debug('Got %s: %s', req.status_code, req.content) if req.status_code == 200: return req else: raise ClientException(req.reason, req.content) except ClientException: raise except Exception as exc: raise ClientException(exc)
[ "def", "wrap", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "req", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logger", ".", "debug", "(", "'Got %s: %s'", ",", "req", ".", "status_code", ",", "req", ".", "content", ")", "if", "req", ".", "status_code", "==", "200", ":", "return", "req", "else", ":", "raise", "ClientException", "(", "req", ".", "reason", ",", "req", ".", "content", ")", "except", "ClientException", ":", "raise", "except", "Exception", "as", "exc", ":", "raise", "ClientException", "(", "exc", ")" ]
Wrap a function that returns a request with some exception handling
[ "Wrap", "a", "function", "that", "returns", "a", "request", "with", "some", "exception", "handling" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/http/__init__.py#L12-L24
dlecocq/nsq-py
nsq/http/__init__.py
json_wrap
def json_wrap(function, *args, **kwargs): '''Return the json content of a function that returns a request''' try: # Some responses have data = None, but they generally signal a # successful API call as well. response = json.loads(function(*args, **kwargs).content) if 'data' in response: return response['data'] or True else: return response except Exception as exc: raise ClientException(exc)
python
def json_wrap(function, *args, **kwargs): '''Return the json content of a function that returns a request''' try: # Some responses have data = None, but they generally signal a # successful API call as well. response = json.loads(function(*args, **kwargs).content) if 'data' in response: return response['data'] or True else: return response except Exception as exc: raise ClientException(exc)
[ "def", "json_wrap", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# Some responses have data = None, but they generally signal a", "# successful API call as well.", "response", "=", "json", ".", "loads", "(", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ".", "content", ")", "if", "'data'", "in", "response", ":", "return", "response", "[", "'data'", "]", "or", "True", "else", ":", "return", "response", "except", "Exception", "as", "exc", ":", "raise", "ClientException", "(", "exc", ")" ]
Return the json content of a function that returns a request
[ "Return", "the", "json", "content", "of", "a", "function", "that", "returns", "a", "request" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/http/__init__.py#L28-L39
dlecocq/nsq-py
nsq/http/__init__.py
ok_check
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
python
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
[ "def", "ok_check", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "req", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "req", ".", "content", ".", "lower", "(", ")", "!=", "'ok'", ":", "raise", "ClientException", "(", "req", ".", "content", ")", "return", "req", ".", "content" ]
Ensure that the response body is OK
[ "Ensure", "that", "the", "response", "body", "is", "OK" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/http/__init__.py#L43-L48
dlecocq/nsq-py
nsq/http/__init__.py
BaseClient.get
def get(self, path, *args, **kwargs): '''GET the provided endpoint''' target = self._host.relative(path).utf8 if not isinstance(target, basestring): # on older versions of the `url` library, .utf8 is a method, not a property target = target() params = kwargs.get('params', {}) params.update(self._params) kwargs['params'] = params logger.debug('GET %s with %s, %s', target, args, kwargs) return requests.get(target, *args, **kwargs)
python
def get(self, path, *args, **kwargs): '''GET the provided endpoint''' target = self._host.relative(path).utf8 if not isinstance(target, basestring): # on older versions of the `url` library, .utf8 is a method, not a property target = target() params = kwargs.get('params', {}) params.update(self._params) kwargs['params'] = params logger.debug('GET %s with %s, %s', target, args, kwargs) return requests.get(target, *args, **kwargs)
[ "def", "get", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "target", "=", "self", ".", "_host", ".", "relative", "(", "path", ")", ".", "utf8", "if", "not", "isinstance", "(", "target", ",", "basestring", ")", ":", "# on older versions of the `url` library, .utf8 is a method, not a property", "target", "=", "target", "(", ")", "params", "=", "kwargs", ".", "get", "(", "'params'", ",", "{", "}", ")", "params", ".", "update", "(", "self", ".", "_params", ")", "kwargs", "[", "'params'", "]", "=", "params", "logger", ".", "debug", "(", "'GET %s with %s, %s'", ",", "target", ",", "args", ",", "kwargs", ")", "return", "requests", ".", "get", "(", "target", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
GET the provided endpoint
[ "GET", "the", "provided", "endpoint" ]
train
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/http/__init__.py#L67-L77
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
decode_resumable_upload_bitmap
def decode_resumable_upload_bitmap(bitmap_node, number_of_units): """Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to define the number of bits for bitmap """ bitmap = 0 for token_id in range(int(bitmap_node['count'])): value = int(bitmap_node['words'][token_id]) bitmap = bitmap | (value << (0xf * token_id)) result = {} for unit_id in range(number_of_units): mask = 1 << unit_id result[unit_id] = (bitmap & mask) == mask return result
python
def decode_resumable_upload_bitmap(bitmap_node, number_of_units): """Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to define the number of bits for bitmap """ bitmap = 0 for token_id in range(int(bitmap_node['count'])): value = int(bitmap_node['words'][token_id]) bitmap = bitmap | (value << (0xf * token_id)) result = {} for unit_id in range(number_of_units): mask = 1 << unit_id result[unit_id] = (bitmap & mask) == mask return result
[ "def", "decode_resumable_upload_bitmap", "(", "bitmap_node", ",", "number_of_units", ")", ":", "bitmap", "=", "0", "for", "token_id", "in", "range", "(", "int", "(", "bitmap_node", "[", "'count'", "]", ")", ")", ":", "value", "=", "int", "(", "bitmap_node", "[", "'words'", "]", "[", "token_id", "]", ")", "bitmap", "=", "bitmap", "|", "(", "value", "<<", "(", "0xf", "*", "token_id", ")", ")", "result", "=", "{", "}", "for", "unit_id", "in", "range", "(", "number_of_units", ")", ":", "mask", "=", "1", "<<", "unit_id", "result", "[", "unit_id", "]", "=", "(", "bitmap", "&", "mask", ")", "==", "mask", "return", "result" ]
Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to define the number of bits for bitmap
[ "Decodes", "bitmap_node", "to", "hash", "of", "unit_id", ":", "is_uploaded" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L117-L136
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
compute_hash_info
def compute_hash_info(fd, unit_size=None): """Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file hi.units -- list of sha256 hashes for each unit """ logger.debug("compute_hash_info(%s, unit_size=%s)", fd, unit_size) fd.seek(0, os.SEEK_END) file_size = fd.tell() fd.seek(0, os.SEEK_SET) units = [] unit_counter = 0 file_hash = hashlib.sha256() unit_hash = hashlib.sha256() for chunk in iter(lambda: fd.read(HASH_CHUNK_SIZE_BYTES), b''): file_hash.update(chunk) unit_hash.update(chunk) unit_counter += len(chunk) if unit_size is not None and unit_counter == unit_size: # flush the current unit hash units.append(unit_hash.hexdigest().lower()) unit_counter = 0 unit_hash = hashlib.sha256() if unit_size is not None and unit_counter > 0: # leftover block units.append(unit_hash.hexdigest().lower()) fd.seek(0, os.SEEK_SET) return MediaFireHashInfo( file=file_hash.hexdigest().lower(), units=units, size=file_size )
python
def compute_hash_info(fd, unit_size=None): """Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file hi.units -- list of sha256 hashes for each unit """ logger.debug("compute_hash_info(%s, unit_size=%s)", fd, unit_size) fd.seek(0, os.SEEK_END) file_size = fd.tell() fd.seek(0, os.SEEK_SET) units = [] unit_counter = 0 file_hash = hashlib.sha256() unit_hash = hashlib.sha256() for chunk in iter(lambda: fd.read(HASH_CHUNK_SIZE_BYTES), b''): file_hash.update(chunk) unit_hash.update(chunk) unit_counter += len(chunk) if unit_size is not None and unit_counter == unit_size: # flush the current unit hash units.append(unit_hash.hexdigest().lower()) unit_counter = 0 unit_hash = hashlib.sha256() if unit_size is not None and unit_counter > 0: # leftover block units.append(unit_hash.hexdigest().lower()) fd.seek(0, os.SEEK_SET) return MediaFireHashInfo( file=file_hash.hexdigest().lower(), units=units, size=file_size )
[ "def", "compute_hash_info", "(", "fd", ",", "unit_size", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"compute_hash_info(%s, unit_size=%s)\"", ",", "fd", ",", "unit_size", ")", "fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "file_size", "=", "fd", ".", "tell", "(", ")", "fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "units", "=", "[", "]", "unit_counter", "=", "0", "file_hash", "=", "hashlib", ".", "sha256", "(", ")", "unit_hash", "=", "hashlib", ".", "sha256", "(", ")", "for", "chunk", "in", "iter", "(", "lambda", ":", "fd", ".", "read", "(", "HASH_CHUNK_SIZE_BYTES", ")", ",", "b''", ")", ":", "file_hash", ".", "update", "(", "chunk", ")", "unit_hash", ".", "update", "(", "chunk", ")", "unit_counter", "+=", "len", "(", "chunk", ")", "if", "unit_size", "is", "not", "None", "and", "unit_counter", "==", "unit_size", ":", "# flush the current unit hash", "units", ".", "append", "(", "unit_hash", ".", "hexdigest", "(", ")", ".", "lower", "(", ")", ")", "unit_counter", "=", "0", "unit_hash", "=", "hashlib", ".", "sha256", "(", ")", "if", "unit_size", "is", "not", "None", "and", "unit_counter", ">", "0", ":", "# leftover block", "units", ".", "append", "(", "unit_hash", ".", "hexdigest", "(", ")", ".", "lower", "(", ")", ")", "fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "return", "MediaFireHashInfo", "(", "file", "=", "file_hash", ".", "hexdigest", "(", ")", ".", "lower", "(", ")", ",", "units", "=", "units", ",", "size", "=", "file_size", ")" ]
Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file hi.units -- list of sha256 hashes for each unit
[ "Get", "MediaFireHashInfo", "structure", "from", "the", "fd", "unit_size" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L139-L184
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L198-L289
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L292-L351
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L353-L363
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L367-L377
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L380-L407
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L409-L432
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L434-L456
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L458-L500
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L502-L549
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L56-L76
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L255-L288
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L290-L349
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L417-L429
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L587-L592
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L631-L636
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L713-L718
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L732-L763
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L1061-L1080
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L28-L40
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L43-L62
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L107-L129
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L147-L172
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L227-L232
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L235-L251
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L254-L262
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L265-L281
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L284-L302
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L305-L319
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L321-L333
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L335-L355
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", "()" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L359-L390
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L393-L417
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L419-L428
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L430-L438
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L441-L455
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L457-L469
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L471-L498
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L501-L527
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L529-L540
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L542-L551
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L554-L570
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L573-L591
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L594-L602
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L605-L622
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L625-L639
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L642-L658
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L661-L671
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" ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L674-L689
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L852-L863
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L866-L876
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L879-L896
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L899-L921
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L924-L940
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L943-L955
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L958-L966
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L969-L985
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L988-L996
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", "." ]
train
https://github.com/kamikaze/webdav/blob/6facff7224023d3e28c8e1592f3c58401c91a0e6/src/webdav/client.py#L999-L1020
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", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/files.py#L5-L16
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", "." ]
train
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/files.py#L19-L38
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" ]
train
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/media/conversion_server_client.py#L36-L80
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L115-L131
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L518-L532
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L534-L564
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L567-L571
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L574-L589
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L683-L706
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L708-L718
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L720-L746
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", ")" ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L815-L890
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L894-L970
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L973-L978
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L998-L1011
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1015-L1031
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1035-L1058
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1062-L1093
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", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1100-L1148
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", ")", "." ]
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L1171-L1188