Instruction:
Write a Python 3 function that can
draw the attribute arrays in the specified mode.

Response:
def draw(self, mode='triangles', indices=None, check_error=True):
        """ Draw the attribute arrays in the specified mode.

        Parameters
        ----------
        mode : str | GL_ENUM
            'points', 'lines', 'line_strip', 'line_loop', 'triangles',
            'triangle_strip', or 'triangle_fan'.
        indices : array
            Array of indices to draw.
        check_error:
            Check error after draw.

        """

        # Invalidate buffer (data has already been sent)
        self._buffer = None

        # Check if mode is valid
        mode = check_enum(mode)
        if mode not in ['points', 'lines', 'line_strip', 'line_loop',
                        'triangles', 'triangle_strip', 'triangle_fan']:
            raise ValueError('Invalid draw mode: %r' % mode)

        # Check leftover variables, warn, discard them
        # In GLIR we check whether all attributes are indeed set
        for name in self._pending_variables:
            logger.warn('Variable %r is given but not known.' % name)
        self._pending_variables = {}

        # Check attribute sizes
        attributes = [vbo for vbo in self._user_variables.values()
                      if isinstance(vbo, DataBuffer)]
        sizes = [a.size for a in attributes]
        if len(attributes) < 1:
            raise RuntimeError('Must have at least one attribute')
        if not all(s == sizes[0] for s in sizes[1:]):
            msg = '\n'.join(['%s: %s' % (str(a), a.size) for a in attributes])
            raise RuntimeError('All attributes must have the same size, got:\n'
                               '%s' % msg)

        # Get the glir queue that we need now
        canvas = get_current_canvas()
        assert canvas is not None

        # Associate canvas
        canvas.context.glir.associate(self.glir)

        # Indexbuffer
        if isinstance(indices, IndexBuffer):
            canvas.context.glir.associate(indices.glir)
            logger.debug("Program drawing %r with index buffer" % mode)
            gltypes = {np.dtype(np.uint8): 'UNSIGNED_BYTE',
                       np.dtype(np.uint16): 'UNSIGNED_SHORT',
                       np.dtype(np.uint32): 'UNSIGNED_INT'}
            selection = indices.id, gltypes[indices.dtype], indices.size
            canvas.context.glir.command('DRAW', self._id, mode, selection)
        elif indices is None:
            selection = 0, attributes[0].size
            logger.debug("Program drawing %r with %r" % (mode, selection))
            canvas.context.glir.command('DRAW', self._id, mode, selection)
        else:
            raise TypeError("Invalid index: %r (must be IndexBuffer)" %
                            indices)

        # Process GLIR commands
        canvas.context.flush_commands()


Instruction:
How would you code a function in Python 3 to
update the data in this object.

Response:
def set_data(self, x=None, y=None, z=None, colors=None):
        """Update the data in this surface plot.

        Parameters
        ----------
        x : ndarray | None
            1D array of values specifying the x positions of vertices in the
            grid. If None, values will be assumed to be integers.
        y : ndarray | None
            1D array of values specifying the x positions of vertices in the
            grid. If None, values will be assumed to be integers.
        z : ndarray
            2D array of height values for each grid vertex.
        colors : ndarray
            (width, height, 4) array of vertex colors.
        """
        if x is not None:
            if self._x is None or len(x) != len(self._x):
                self.__vertices = None
            self._x = x

        if y is not None:
            if self._y is None or len(y) != len(self._y):
                self.__vertices = None
            self._y = y

        if z is not None:
            if self._x is not None and z.shape[0] != len(self._x):
                raise TypeError('Z values must have shape (len(x), len(y))')
            if self._y is not None and z.shape[1] != len(self._y):
                raise TypeError('Z values must have shape (len(x), len(y))')
            self._z = z
            if (self.__vertices is not None and
                    self._z.shape != self.__vertices.shape[:2]):
                self.__vertices = None

        if self._z is None:
            return

        update_mesh = False
        new_vertices = False

        # Generate vertex and face array
        if self.__vertices is None:
            new_vertices = True
            self.__vertices = np.empty((self._z.shape[0], self._z.shape[1], 3),
                                       dtype=np.float32)
            self.generate_faces()
            self.__meshdata.set_faces(self.__faces)
            update_mesh = True

        # Copy x, y, z data into vertex array
        if new_vertices or x is not None:
            if x is None:
                if self._x is None:
                    x = np.arange(self._z.shape[0])
                else:
                    x = self._x
            self.__vertices[:, :, 0] = x.reshape(len(x), 1)
            update_mesh = True

        if new_vertices or y is not None:
            if y is None:
                if self._y is None:
                    y = np.arange(self._z.shape[1])
                else:
                    y = self._y
            self.__vertices[:, :, 1] = y.reshape(1, len(y))
            update_mesh = True

        if new_vertices or z is not None:
            self.__vertices[..., 2] = self._z
            update_mesh = True

        if colors is not None:
            self.__meshdata.set_vertex_colors(colors)
            update_mesh = True

        # Update MeshData
        if update_mesh:
            self.__meshdata.set_vertices(
                self.__vertices.reshape(self.__vertices.shape[0] *
                                        self.__vertices.shape[1], 3))
            MeshVisual.set_data(self, meshdata=self.__meshdata)


Instruction:
Given the following Python 3 function, write the documentation
def map(self, coords):
        for tr in reversed(self.transforms):
            coords = tr.map(coords)
        return coords

Response: Map the given coords to the corresponding set of keys.


Instruction:
Implement a Python 3 function for
inversing map coordinates Parameters ---------- coords : array-like Coordinates to inverse map. Returns ------- coords : ndarray Coordinates.

Response:
def imap(self, coords):
        """Inverse map coordinates

        Parameters
        ----------
        coords : array-like
            Coordinates to inverse map.

        Returns
        -------
        coords : ndarray
            Coordinates.
        """
        for tr in self.transforms:
            coords = tr.imap(coords)
        return coords


Instruction:
Implement a Python 3 function for
adding a new transform to the end of the chain.

Response:
def append(self, tr):
        """
        Add a new transform to the end of this chain.

        Parameters
        ----------
        tr : instance of Transform
            The transform to use.
        """
        self.transforms.append(tr)
        tr.changed.connect(self._subtr_changed)
        self._rebuild_shaders()
        self.update()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def prepend(self, tr):
        self.transforms.insert(0, tr)
        tr.changed.connect(self._subtr_changed)
        self._rebuild_shaders()
        self.update()

Response: Adds a new transform to the beginning of this chain.


Instruction:
How would you code a function in Python 3 to
generate a simplified chain by joining adjacent transforms.

Response:
def source_changed(self, event):
        """Generate a simplified chain by joining adjacent transforms.
        """
        # bail out early if the chain is empty
        transforms = self._chain.transforms[:]
        if len(transforms) == 0:
            self.transforms = []
            return

        # If the change signal comes from a transform that already appears in
        # our simplified transform list, then there is no need to re-simplify.
        if event is not None:
            for source in event.sources[::-1]:
                if source in self.transforms:
                    self.update(event)
                    return

        # First flatten the chain by expanding all nested chains
        new_chain = []
        while len(transforms) > 0:
            tr = transforms.pop(0)
            if isinstance(tr, ChainTransform) and not tr.dynamic:
                transforms = tr.transforms[:] + transforms
            else:
                new_chain.append(tr)

        # Now combine together all compatible adjacent transforms
        cont = True
        tr = new_chain
        while cont:
            new_tr = [tr[0]]
            cont = False
            for t2 in tr[1:]:
                t1 = new_tr[-1]
                pr = t1 * t2
                if (not t1.dynamic and not t2.dynamic and not
                   isinstance(pr, ChainTransform)):
                    cont = True
                    new_tr.pop()
                    new_tr.append(pr)
                else:
                    new_tr.append(t2)
            tr = new_tr

        self.transforms = tr


Instruction:
Make a summary of the following Python 3 code
def pack_iterable(messages):
    '''Pack an iterable of messages in the TCP protocol format'''
    # [ 4-byte body size ]
    # [ 4-byte num messages ]
    # [ 4-byte message #1 size ][ N-byte binary data ]
    #      ... (repeated <num_messages> times)
    return pack_string(
        struct.pack('>l', len(messages)) +
        ''.join(map(pack_string, messages)))

Response: Pack an iterable of messages in the TCP protocol format


Instruction:
Can you generate a brief explanation for the following Python 3 code
def hexify(message):
    '''Print out printable characters, but others in hex'''
    import string
    hexified = []
    for char in message:
        if (char in '\n\r \t') or (char not in string.printable):
            hexified.append('\\x%02x' % ord(char))
        else:
            hexified.append(char)
    return ''.join(hexified)

Response: Print out printable characters but others in hex


Instruction:
Can you implement a function in Python 3 that
cleans the running items from a previous session.

Response:
def clean(self):
        """Clean queue items from a previous session.

        In case a previous session crashed and there are still some running
        entries in the queue ('running', 'stopping', 'killing'), we clean those
        and enqueue them again.
        """
        for _, item in self.queue.items():
            if item['status'] in ['paused', 'running', 'stopping', 'killing']:
                item['status'] = 'queued'
                item['start'] = ''
                item['end'] = ''


Instruction:
Implement a Python 3 function for
removing all completed tasks from the queue.

Response:
def clear(self):
        """Remove all completed tasks from the queue."""
        for key in list(self.queue.keys()):
            if self.queue[key]['status'] in ['done', 'failed']:
                del self.queue[key]
        self.write()


Instruction:
How would you explain what the following Python 3 function does
def next(self):
        smallest = None
        for key in self.queue.keys():
            if self.queue[key]['status'] == 'queued':
                if smallest is None or key < smallest:
                    smallest = key
        return smallest

Response: Get the next processable item in the queue.


Instruction:
Implement a Python 3 function for
reading the queue of the last pueue session or set self. queue = {}.

Response:
def read(self):
        """Read the queue of the last pueue session or set `self.queue = {}`."""
        queue_path = os.path.join(self.config_dir, 'queue')
        if os.path.exists(queue_path):
            queue_file = open(queue_path, 'rb')
            try:
                self.queue = pickle.load(queue_file)
            except Exception:
                print('Queue file corrupted, deleting old queue')
                os.remove(queue_path)
                self.queue = {}
            queue_file.close()
        else:
            self.queue = {}


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self):
        queue_path = os.path.join(self.config_dir, 'queue')
        queue_file = open(queue_path, 'wb+')
        try:
            pickle.dump(self.queue, queue_file, -1)
        except Exception:
            print('Error while writing to queue file. Wrong file permissions?')
        queue_file.close()

Response: Write the current queue to a file. We need this to continue an earlier session.


Instruction:
How would you explain what the following Python 3 function does
def add_new(self, command):
        self.queue[self.next_key] = command
        self.queue[self.next_key]['status'] = 'queued'
        self.queue[self.next_key]['returncode'] = ''
        self.queue[self.next_key]['stdout'] = ''
        self.queue[self.next_key]['stderr'] = ''
        self.queue[self.next_key]['start'] = ''
        self.queue[self.next_key]['end'] = ''

        self.next_key += 1
        self.write()

Response: Add a new entry to the queue.


Instruction:
Implement a Python 3 function for
removing a key from the queue return False if no such key exists.

Response:
def remove(self, key):
        """Remove a key from the queue, return `False` if no such key exists."""
        if key in self.queue:
            del self.queue[key]
            self.write()
            return True
        return False


Instruction:
Here you have a function in Python 3, explain what it does
def restart(self, key):
        if key in self.queue:
            if self.queue[key]['status'] in ['failed', 'done']:
                new_entry = {'command': self.queue[key]['command'],
                             'path': self.queue[key]['path']}
                self.add_new(new_entry)
                self.write()
                return True
        return False

Response: Restart a previously finished entry.


Instruction:
Can you generate the documentation for the following Python 3 function
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

Response: Receive an answer from the daemon and return the response.


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Connect to a daemon s socket.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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)

Response: Return a new response from a raw buffer


Instruction:
How would you explain what the following Python 3 function does
def pack(cls, data):
        '''Pack the provided data into a Response'''
        return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + data

Response: Pack the provided data into a Response


Instruction:
How would you implement a function in Python 3 that
indicates that this message is finished processing

Response:
def fin(self):
        '''Indicate that this message is finished processing'''
        self.connection.fin(self.id)
        self.processed = True


Instruction:
How would you implement a function in Python 3 that
handles the exception and requeue the message if necessary.

Response:
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()


Instruction:
Explain what the following Python 3 code does
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

Response: Find the exception class by name


Instruction:
Implement a Python 3 function for
returning an instance of the corresponding exception

Response:
def exception(self):
        '''Return an instance of the corresponding exception'''
        code, _, message = self.data.partition(' ')
        return self.find(code)(message)


Instruction:
How would you code a function in Python 3 to
parse the gdb version from the gdb header.

Response:
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 ''


Instruction:
Write a Python 3 script to
spawn gdb and attach to a process.

Response:
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


Instruction:
Implement a Python 3 function for
spawning the process then repeatedly attach to the process.

Response:
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


Instruction:
How would you implement a function in Python 3 that
skips this py - pdb command to avoid attaching within the same loop.

Response:
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


Instruction:
Write a Python 3 function that can
move the current log to a new file with timestamp and create a new empty log file.

Response:
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({})


Instruction:
Can you implement a function in Python 3 that
writes the output of all finished processes to a compiled log file.

Response:
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()


Instruction:
How would you implement a function in Python 3 that
removes all logs which are older than the specified time.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
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)

Response: Wrap a function that returns a request with some exception handling


Instruction:
Make a summary of the following Python 3 code
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)

Response: Return the json content of a function that returns a request


Instruction:
Write a Python 3 function for
ensuring that the response body is OK

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
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)

Response: GET the provided endpoint


Instruction:
Create a Python 3 function to
decode a resumable upload bitmap node to hash of unit_id

Response:
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


Instruction:
Here you have a function in Python 3, explain what it does
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
    )

Response: Get the MediaFireHashInfo structure from the fd unit_size


Instruction:
Here you have a function in Python 3, explain what it does
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

Response: Upload a file to MediaFire and return a new object containing the upload result.


Instruction:
How would you implement a function in Python 3 that
polls upload until quickkey is found.

Response:
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']
        )


Instruction:
Write a Python 3 function that can
upload a single unit and return a raw upload and resumable unit.

Response:
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)


Instruction:
How would you implement a function in Python 3 that
prepares and upload all resumable units and return upload_key

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
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[:] = []

Response: Remove from sys. modules the modules imported by the debuggee.


Instruction:
Make a summary of the following Python 3 code
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))

Response: Returns the first line number of the last defined funcname function.


Instruction:
Write a Python 3 script for
getting the actual breakpoint line number.

Response:
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]


Instruction:
Here you have a function in Python 3, explain what it does
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]

Response: Return the list of breakpoints set at lineno.


Instruction:
Explain what the following Python 3 code does
def settrace(self, do_set):
        if do_set:
            sys.settrace(self.trace_dispatch)
        else:
            sys.settrace(None)

Response: Set or remove the trace function.


Instruction:
Here you have a function in Python 3, explain what it does
def restart(self):
        _module_finder.reset()
        linecache.checkcache()
        for module_bpts in self.breakpoints.values():
            module_bpts.reset()

Response: Restart the debugger after source code changes.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_until(self, frame, lineno=None):
        if lineno is None:
            lineno = frame.f_lineno + 1
        self._set_stopinfo(frame, lineno)

Response:
Stop when the current line number in frame is greater than lineno or
        when returning from frame.


Instruction:
Can you implement a function in Python 3 that
starts debugging from frame.

Response:
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)


Instruction:
Implement a function in Python 3 to
return True if the breakpoint is enabled and False if it is not.

Response:
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


Instruction:
Explain what the following Python 3 code does
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

Response: Returns list of files and directories for local directory by path


Instruction:
How would you explain what the following Python 3 function does
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

Response: Extract options for specified option type from all options dictionary


Instruction:
How would you code a function in Python 3 to
return the HTTP headers of the specified WebDAV actions.

Response:
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])


Instruction:
Can you write a function in Python 3 where it
executes a request to the WebDAV server for the specified action and path.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
def valid(self):
        return True if self.webdav.valid() and self.proxy.valid() else False

Response: Validates of WebDAV and proxy settings.


Instruction:
Make a summary of the following Python 3 code
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]

Response: Returns list of nested files and directories for remote WebDAV directory by path.


Instruction:
Implement a Python 3 function for
returning an amount of free space on remote WebDAV server.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
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

Response: Checks an existence of remote resource on WebDAV server by remote path.


Instruction:
Implement a function in Python 3 to
make new directory on WebDAV server.

Response:
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


Instruction:
Implement a Python 3 function for
downloading file from WebDAV and writes it in buffer.

Response:
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)


Instruction:
Can you tell what is the following Python 3 function doing
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)

Response: Downloads remote resource from WebDAV and saves it in local path.


Instruction:
Can you tell what is the following Python 3 function doing
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)

Response: Downloads all nested files and directories from remote WebDAV server to local WebDAV server.


Instruction:
Write a Python 3 function for
opening a file from WebDAV server and saves it temprorary then opens it for further manipulations.

Response:
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)


Instruction:
Write a Python 3 function that can
download file from WebDAV server and saves it locally.

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
def download_sync(self, remote_path, local_path, callback=None):
        self.download(local_path=local_path, remote_path=remote_path)
        if callback:
            callback()

Response: Downloads remote resources from WebDAV server synchronously.


Instruction:
Can you create a Python 3 function that
downloads remote resources from WebDAV server asynchronously.

Response:
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()


Instruction:
Given the following Python 3 function, write the documentation
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)

Response: Uploads file from buffer to remote path on WebDAV server.


Instruction:
How would you implement a function in Python 3 that
uploads resource to remote path on WebDAV server.

Response:
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)


Instruction:
Create a Python 3 function for
uploading a directory to WebDAV server.

Response:
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)


Instruction:
Explain what the following Python 3 code does
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)

Response: Uploads file to remote path on WebDAV server.


Instruction:
How would you implement a function in Python 3 that
uploads resource to remote path synchronously.

Response:
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()


Instruction:
How would you implement a function in Python 3 that
uploads resource to remote path on WebDAV server asynchronously.

Response:
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()


Instruction:
Create a Python 3 function to
copy resource from one place to another on WebDAV server.

Response:
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])


Instruction:
Write a Python 3 script to
move resource from one place to another on WebDAV server.

Response:
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])


Instruction:
Write a Python 3 function that can
clean ( Deletes ) a remote resource on WebDAV server.

Response:
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())


Instruction:
Write a Python 3 script for
getting information about resource on WebDAV.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
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)

Response: Checks if the remote resource is a directory.


Instruction:
Can you generate the documentation for the following Python 3 function
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'])

Response: Gets the metadata property of the remote resource on WebDAV server.


Instruction:
How would you explain what the following Python 3 function does
def set_property(self, remote_path, option):
        self.set_property_batch(remote_path=remote_path, option=[option])

Response: Sets the property of the remote resource on WebDAV server.


Instruction:
Explain what the following Python 3 code does
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)

Response: Sets batch metadata properties of remote resource on WebDAV server in batch.


Instruction:
Can you create a Python 3 function that
parses the response content XML from WebDAV server and extracts file and directory names.

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()


Instruction:
Make a summary of the following Python 3 code
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)

Response: Creates an XML string for requesting of free space on remote WebDAV server.


Instruction:
Can you generate the documentation for the following Python 3 function
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()

Response: Parses the response content XML from WebDAV server and extracts an amount of free space in bytes.


Instruction:
Implement a function in Python 3 to
parse the response content XML from WebDAV server and extracts an information about resource.

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


Instruction:
Write a Python 3 script to
parse the response content XML from WebDAV server and extracts an information about resource.

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


Instruction:
Can you tell what is the following Python 3 function doing
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)

Response: Creates an XML for requesting of getting a property value of remote WebDAV resource.


Instruction:
How would you explain what the following Python 3 function does
def parse_get_property_response(content, name):
        tree = etree.fromstring(content)
        return tree.xpath('//*[local-name() = $name]', name=name)[0].text

Response: Parses the response content XML from WebDAV server for getting metadata property value for some resource.


Instruction:
Explain what the following Python 3 code does
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)

Response: Creates an XML for requesting of setting a property values for remote WebDAV resource in batch.


Instruction:
Create a Python 3 function for
creating a string from lxml. etree. ElementTree with XML declaration and UTF - 8 encoding.

Response:
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()


Instruction:
Can you generate the documentation for the following Python 3 function
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)

Response: Extracts the response for a remote resource defined by path.


Instruction:
Explain what the following Python 3 code does
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)

Response: Remove temporary stderr and stdout files as well as the daemon socket.


Instruction:
Write a Python 3 function for
getting the descriptor output and handle incorrect UTF - 8 encoding of subprocess logs.

Response:
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    ')


Instruction:
Implement a Python 3 function for
requesting the conversion server for a given file.

Response:
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


Instruction:
How would you implement a function in Python 3 that
calls every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called False otherwise.

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def user_return(self, frame, return_value):
        frame.f_locals['__return__'] = return_value
        self.message('--Return--')
        self.interaction(frame, None)

Response: This function is called when a user returns a value.


Instruction:
Can you generate the documentation for the following Python 3 function
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)

Response: This function is called if an exception occurs and only if we are to stop at or just below this level.


Instruction:
Write a Python 3 script for
handling alias expansion and ';;' separator.

Response:
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


Instruction:
Explain what the following Python 3 code does
def onecmd(self, line):
        if not self.commands_defining:
            return cmd.Cmd.onecmd(self, line)
        else:
            return self.handle_command_def(line)

Response:
Interpret the argument as though it had been typed in response
        to the prompt.


Instruction:
Can you generate the documentation for the following Python 3 function
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

Response: Handles one command line during command list definition.


Instruction:
How would you implement a function in Python 3 that
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.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
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))

Response: Set a breakpoint at the current line of the current file.


Instruction:
How would you code a function in Python 3 to
produce a reasonable default.

Response:
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


Instruction:
Can you write a function in Python 3 where it
enables the breakpoint numbers given as a space separated list of breakpoint numbers.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
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)

Response: Disable the breakpoint with the given number.


Instruction:
How would you implement a function in Python 3 that
sets a condition for the breakpoint.

Response:
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)


Instruction:
Explain what the following Python 3 code does
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)

Response: ignore bpnumber [ count ]