Instruction:
Given the following Python 3 function, write the documentation
def _resolve_path(self, create=False):
        # Split up the key path
        if type(self._path) == str:
            key_path = self._path.split('.')
        else:
            key_path = [self._path]

        # Start at the root node
        node = self._root._data
        nodes = [self._root._data]

        # Traverse along key path
        while len(key_path):
            # Get the next key in the key path
            key = key_path.pop(0)

            # See if the test could be an int for array access, if so assume it is
            try:
                key = int(key)
            except:
                pass

            # If the next level doesn't exist, create it
            if create:
                if type(node) == dict and key not in node:
                    node[key] = {}
                elif type(node) == list and type(key) == int and len(node) < key:
                    node.append([None for i in range(key-len(node))])

            # Store the last node and traverse down the hierarchy
            nodes.append(node)
            try:
                node = node[key]
            except TypeError:
                if type(key) == int:
                    raise IndexError(key)
                else:
                    raise KeyError(key)

        return (nodes[-1], key)

Response: Resolves the path to the last container in the key path and returns a tuple of a reference to the last container in the path and the last component in the key path.


Instruction:
How would you code a function in Python 3 to
get the value represented by this node.

Response:
def _get_value(self):
        """
        Get the value represented by this node.
        """
        if self._path:
            try:
                container, last = self._resolve_path()
                return container[last]
            except KeyError:
                return None
            except IndexError:
                return None
        else:
            return self._data


Instruction:
Here you have a function in Python 3, explain what it does
def update(self, data={}, options={}):
        # Handle an update with a set of options like CherryPy does
        for key in options:
            self[key] = options[key]

        # Merge in any data in `data`
        if isinstance(data, ConfigNode):
            data = data._get_value()
        update_dict(self._get_value(), data)

Response: Update the configuration with new data.


Instruction:
Can you generate the documentation for the following Python 3 function
def load(self, reload=False):
        if reload or not self._loaded:
            # load defaults
            if self._defaults_file and type(self._defaults_file) == str:
                self._defaults_file = File(self._defaults_file, parent=self._parent)
            defaults = {}
            if self._defaults_file:
                defaults = yaml.safe_load(self._defaults_file.read().replace('\t', '    '))

            # load data
            data = {}
            if self.exists:
                data = yaml.safe_load(self.read().replace('\t', '    '))

            # initialise with the loaded data
            self._defaults = defaults
            self._data = copy.deepcopy(self._defaults)
            self.update(data=data)

            # if specified, apply environment variables
            if self._apply_env:
                self.update(ConfigEnv(self._env_prefix))

            self._loaded = True

        return self

Response: Load the config and defaults from files.


Instruction:
Write a Python 3 script for
applying the config to a string.

Response:
def apply_to_str(self, obj):
        """
        Apply the config to a string.
        """
        toks = re.split('({config:|})', obj)
        newtoks = []
        try:
            while len(toks):
                tok = toks.pop(0)
                if tok == '{config:':
                    # pop the config variable, look it up
                    var = toks.pop(0)
                    val = self.config[var]

                    # if we got an empty node, then it didn't exist
                    if type(val) == ConfigNode and val == None:
                        raise KeyError("No such config variable '{}'".format(var))

                    # add the value to the list
                    newtoks.append(str(val))

                    # pop the '}'
                    toks.pop(0)
                else:
                    # not the start of a config block, just append it to the list
                    newtoks.append(tok)
            return ''.join(newtoks)
        except IndexError:
            pass

        return obj


Instruction:
Write a Python 3 function that can
view decorator to validate requests from Twilio per http://www.twilio.com/docs/security.

Response:
def validate_twilio_signature(func=None, backend_name='twilio-backend'):
    """View decorator to validate requests from Twilio per http://www.twilio.com/docs/security."""

    def _dec(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            backend = kwargs.get('backend_name', backend_name)
            config = settings.INSTALLED_BACKENDS[backend]['config']
            validator = RequestValidator(config['auth_token'])
            signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
            url = request.build_absolute_uri()
            body = {}
            if request.method == 'POST':
                body = request.POST
            require_validation = config.get('validate', True)
            if validator.validate(url, body, signature) or not require_validation:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponseBadRequest()
        return _wrapped_view

    if func is None:
        return _dec
    else:
        return _dec(func)


Instruction:
How would you implement a function in Python 3 that
builds the Twilio callback url for confirming message delivery status

Response:
def build_callback_url(request, urlname, message):
    """
    Build Twilio callback url for confirming message delivery status

    :type message: OutgoingSMS
    """
    location = reverse(urlname, kwargs={"pk": message.pk})

    callback_domain = getattr(settings, "TWILIO_CALLBACK_DOMAIN", None)
    if callback_domain:
        url = "{}://{}{}".format(
            "https" if getattr(settings, "TWILIO_CALLBACK_USE_HTTPS", False) else "http",
            callback_domain,
            location
        )

    elif request is not None:
        url = request.build_absolute_uri(location)
    else:
        raise ValueError(
            "Unable to build callback url. Configure TWILIO_CALLBACK_DOMAIN "
            "or pass request object to function call"
        )
    return url


Instruction:
Can you generate a brief explanation for the following Python 3 code
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
    client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
    from_number = settings.TWILIO_PHONE_NUMBER

    message = OutgoingSMS.objects.create(
        from_number=from_number,
        to_number=to_number,
        body=body,
    )

    status_callback = None
    if callback_urlname:
        status_callback = build_callback_url(request, callback_urlname, message)

    logger.debug("Sending SMS message to %s with callback url %s: %s.",
                 to_number, status_callback, body)

    if not getattr(settings, "TWILIO_DRY_MODE", False):
        sent = client.sms.messages.create(
            to=to_number,
            from_=from_number,
            body=body,
            status_callback=status_callback
        )
        logger.debug("SMS message sent: %s", sent.__dict__)

        message.sms_sid = sent.sid
        message.account_sid = sent.account_sid
        message.status = sent.status
        message.to_parsed = sent.to
        if sent.price:
            message.price = Decimal(force_text(sent.price))
            message.price_unit = sent.price_unit
        message.sent_at = sent.date_created
        message.save(update_fields=[
            "sms_sid", "account_sid", "status", "to_parsed",
            "price", "price_unit", "sent_at"
        ])
    else:
        logger.info("SMS: from %s to %s: %s", from_number, to_number, body)
    return message

Response: Send SMS message to the specified phone number.


Instruction:
Can you tell what is the following Python 3 function doing
def main(port, export, css, files):
    options = { 'css': css, 'port': port }
    try:
        if not export:
            if len(files) != 1:
                error("please specify just one file to preview")
            preview(files[0], options)
        else:
            export_files(files, options)
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception as exc:
        die()

Response: Main function for the main function of the main function.


Instruction:
Given the following Python 3 function, write the documentation
def process_input(self):
        try:
            pyngus.read_socket_input(self.connection, self.socket)
        except Exception as e:
            LOG.error("Exception on socket read: %s", str(e))
            self.connection.close_input()
            self.connection.close()
        self.connection.process(time.time())

Response: Called when socket is ready to be read and process incoming data.


Instruction:
Explain what the following Python 3 code does
def send_output(self):
        try:
            pyngus.write_socket_output(self.connection,
                                       self.socket)
        except Exception as e:
            LOG.error("Exception on socket write: %s", str(e))
            self.connection.close_output()
            self.connection.close()
        self.connection.process(time.time())

Response: Called when socket is write - ready and socket is ready to send output


Instruction:
Write a Python 3 script to
process the current state of the current object.

Response:
def process(self):
        """ Do connection-based processing (I/O and timers) """
        readfd = []
        writefd = []
        if self.connection.needs_input > 0:
            readfd = [self.socket]
        if self.connection.has_output > 0:
            writefd = [self.socket]

        timeout = None
        deadline = self.connection.next_tick
        if deadline:
            now = time.time()
            timeout = 0 if deadline <= now else deadline - now

        LOG.debug("select() start (t=%s)", str(timeout))
        readable, writable, ignore = select.select(readfd,
                                                   writefd,
                                                   [],
                                                   timeout)
        LOG.debug("select() returned")

        if readable:
            try:
                pyngus.read_socket_input(self.connection,
                                         self.socket)
            except Exception as e:
                LOG.error("Exception on socket read: %s", str(e))
                self.connection.close_input()
                self.connection.close()

        self.connection.process(time.time())
        if writable:
            try:
                pyngus.write_socket_output(self.connection,
                                           self.socket)
            except Exception as e:
                LOG.error("Exception on socket write: %s", str(e))
                self.connection.close_output()
                self.connection.close()


Instruction:
Write a Python 3 script for
creating a new caller object and returns it.

Response:
def create_caller(self, method_map, source_addr, target_addr,
                      receiver_properties, sender_properties):
        """ Caller factory
        """
        if self.caller:
            self.caller.destroy()
        self.caller = MyCaller(method_map, self, source_addr, target_addr,
                               receiver_properties, sender_properties)
        return self.caller


Instruction:
Can you generate the documentation for the following Python 3 function
def _send_request(self):
        msg = Message()
        msg.subject = "An RPC call!"
        msg.address = self._to
        msg.reply_to = self._reply_to
        msg.body = self._method
        msg.correlation_id = 5  # whatever...

        print("sending RPC call request: %s" % str(self._method))
        # @todo send timeout self._sender.send(msg, self, None, time.time() +
        # 10)
        self._sender.send(msg, self)

Response: Send a message containing the RPC method call


Instruction:
How would you code a function in Python 3 to
read from the network layer and processes all data read.

Response:
def read_socket_input(connection, socket_obj):
    """Read from the network layer and processes all data read.  Can
    support both blocking and non-blocking sockets.
    Returns the number of input bytes processed, or EOS if input processing
    is done.  Any exceptions raised by the socket are re-raised.
    """
    count = connection.needs_input
    if count <= 0:
        return count  # 0 or EOS

    while True:
        try:
            sock_data = socket_obj.recv(count)
            break
        except socket.timeout as e:
            LOG.debug("Socket timeout exception %s", str(e))
            raise  # caller must handle
        except socket.error as e:
            err = e.errno
            if err in [errno.EAGAIN,
                       errno.EWOULDBLOCK,
                       errno.EINTR]:
                # try again later
                return 0
            # otherwise, unrecoverable, caller must handle
            LOG.debug("Socket error exception %s", str(e))
            raise
        except Exception as e:  # beats me... assume fatal
            LOG.debug("unknown socket exception %s", str(e))
            raise  # caller must handle

    if len(sock_data) > 0:
        count = connection.process_input(sock_data)
    else:
        LOG.debug("Socket closed")
        count = Connection.EOS
        connection.close_input()
        connection.close_output()
    return count


Instruction:
How would you implement a function in Python 3 that
writes data to the network layer.

Response:
def write_socket_output(connection, socket_obj):
    """Write data to the network layer.  Can support both blocking and
    non-blocking sockets.
    Returns the number of output bytes sent, or EOS if output processing
    is done.  Any exceptions raised by the socket are re-raised.
    """
    count = connection.has_output
    if count <= 0:
        return count  # 0 or EOS

    data = connection.output_data()
    if not data:
        # error - has_output > 0, but no data?
        return Connection.EOS

    while True:
        try:
            count = socket_obj.send(data)
            break
        except socket.timeout as e:
            LOG.debug("Socket timeout exception %s", str(e))
            raise  # caller must handle
        except socket.error as e:
            err = e.errno
            if err in [errno.EAGAIN,
                       errno.EWOULDBLOCK,
                       errno.EINTR]:
                # try again later
                return 0
            # else assume fatal let caller handle it:
            LOG.debug("Socket error exception %s", str(e))
            raise
        except Exception as e:  # beats me... assume fatal
            LOG.debug("unknown socket exception %s", str(e))
            raise

    if count > 0:
        connection.output_written(count)
    elif data:
        LOG.debug("Socket closed")
        count = Connection.EOS
        connection.close_output()
        connection.close_input()
    return count


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_remote_settle_modes(pn_link):
    modes = {}
    snd = pn_link.remote_snd_settle_mode
    if snd == proton.Link.SND_UNSETTLED:
        modes['snd-settle-mode'] = 'unsettled'
    elif snd == proton.Link.SND_SETTLED:
        modes['snd-settle-mode'] = 'settled'
    if pn_link.remote_rcv_settle_mode == proton.Link.RCV_SECOND:
        modes['rcv-settle-mode'] = 'second'
    return modes

Response: Return a map containing the settle modes as provided by the remote.


Instruction:
Here you have a function in Python 3, explain what it does
def configure(self, target_address, source_address, handler, properties):
        self._handler = handler
        self._properties = properties

        dynamic_props = None
        if properties:
            dynamic_props = properties.get("dynamic-node-properties")
            mode = _dist_modes.get(properties.get("distribution-mode"))
            if mode is not None:
                self._pn_link.source.distribution_mode = mode
            mode = _snd_settle_modes.get(properties.get("snd-settle-mode"))
            if mode is not None:
                self._pn_link.snd_settle_mode = mode
            mode = _rcv_settle_modes.get(properties.get("rcv-settle-mode"))
            if mode is not None:
                self._pn_link.rcv_settle_mode = mode

        if target_address is None:
            if not self._pn_link.is_sender:
                raise Exception("Dynamic target not allowed")
            self._pn_link.target.dynamic = True
            if dynamic_props:
                self._pn_link.target.properties.clear()
                self._pn_link.target.properties.put_dict(dynamic_props)
        elif target_address:
            self._pn_link.target.address = target_address

        if source_address is None:
            if not self._pn_link.is_receiver:
                raise Exception("Dynamic source not allowed")
            self._pn_link.source.dynamic = True
            if dynamic_props:
                self._pn_link.source.properties.clear()
                self._pn_link.source.properties.put_dict(dynamic_props)
        elif source_address:
            self._pn_link.source.address = source_address

Response: Assign addresses properties etc.


Instruction:
Can you implement a function in Python 3 that
returns the authorative source of the link.

Response:
def source_address(self):
        """Return the authorative source of the link."""
        # If link is a sender, source is determined by the local
        # value, else use the remote.
        if self._pn_link.is_sender:
            return self._pn_link.source.address
        else:
            return self._pn_link.remote_source.address


Instruction:
Can you create a Python 3 function that
returns the authorative target of the link.

Response:
def target_address(self):
        """Return the authorative target of the link."""
        # If link is a receiver, target is determined by the local
        # value, else use the remote.
        if self._pn_link.is_receiver:
            return self._pn_link.target.address
        else:
            return self._pn_link.remote_target.address


Instruction:
Given the following Python 3 function, write the documentation
def reject(self, pn_condition=None):
        self._pn_link.source.type = proton.Terminus.UNSPECIFIED
        super(SenderLink, self).reject(pn_condition)

Response: See Link Reject and AMQP1. 0 spec.


Instruction:
Make a summary of the following Python 3 code
def _process_delivery(self, pn_delivery):
        if pn_delivery.tag in self._send_requests:
            if pn_delivery.settled or pn_delivery.remote_state:
                # remote has reached a 'terminal state'
                outcome = pn_delivery.remote_state
                state = SenderLink._DISPOSITION_STATE_MAP.get(outcome,
                                                              self.UNKNOWN)
                pn_disposition = pn_delivery.remote
                info = {}
                if state == SenderLink.REJECTED:
                    if pn_disposition.condition:
                        info["condition"] = pn_disposition.condition
                elif state == SenderLink.MODIFIED:
                    info["delivery-failed"] = pn_disposition.failed
                    info["undeliverable-here"] = pn_disposition.undeliverable
                    annotations = pn_disposition.annotations
                    if annotations:
                        info["message-annotations"] = annotations
                send_req = self._send_requests.pop(pn_delivery.tag)
                send_req.destroy(state, info)
                pn_delivery.settle()
            elif pn_delivery.writable:
                # we can now send on this delivery
                if self._pending_sends:
                    tag = self._pending_sends.popleft()
                    send_req = self._send_requests[tag]
                    self._write_msg(pn_delivery, send_req)
        else:
            # tag no longer valid, expired or canceled send?
            LOG.debug("Delivery ignored, tag=%s", str(pn_delivery.tag))
            pn_delivery.settle()

Response: Check if the delivery can be processed.


Instruction:
Can you generate the documentation for the following Python 3 function
def reject(self, pn_condition=None):
        self._pn_link.target.type = proton.Terminus.UNSPECIFIED
        super(ReceiverLink, self).reject(pn_condition)

Response: See Link Reject spec.


Instruction:
Can you create a Python 3 function that
checks if the delivery can be processed.

Response:
def _process_delivery(self, pn_delivery):
        """Check if the delivery can be processed."""
        if pn_delivery.readable and not pn_delivery.partial:
            data = self._pn_link.recv(pn_delivery.pending)
            msg = proton.Message()
            msg.decode(data)
            self._pn_link.advance()

            if self._handler:
                handle = "rmsg-%s:%x" % (self._name, self._next_handle)
                self._next_handle += 1
                self._unsettled_deliveries[handle] = pn_delivery
                with self._callback_lock:
                    self._handler.message_received(self, msg, handle)
            else:
                # TODO(kgiusti): is it ok to assume Delivery.REJECTED?
                pn_delivery.settle()


Instruction:
Write a Python 3 function that can
create a new sender link.

Response:
def new_sender(self, name):
        """Create a new sender link."""
        pn_link = self._pn_session.sender(name)
        return self.request_sender(pn_link)


Instruction:
Make a summary of the following Python 3 code
def request_sender(self, pn_link):
        sl = SenderLink(self._connection, pn_link)
        self._links.add(sl)
        return sl

Response: Create a link from a request for a sender.


Instruction:
Explain what the following Python 3 code does
def new_receiver(self, name):
        pn_link = self._pn_session.receiver(name)
        return self.request_receiver(pn_link)

Response: Create a new receiver link.


Instruction:
Explain what the following Python 3 code does
def request_receiver(self, pn_link):
        rl = ReceiverLink(self._connection, pn_link)
        self._links.add(rl)
        return rl

Response: Create a receiver link from a request.


Instruction:
Can you create a Python 3 function that
calls when a link has been destroyed.

Response:
def link_destroyed(self, link):
        """Link has been destroyed."""
        self._links.discard(link)
        if not self._links:
            # no more links
            LOG.debug("destroying unneeded session")
            self._pn_session.close()
            self._pn_session.free()
            self._pn_session = None
            self._connection = None


Instruction:
How would you implement a function in Python 3 that
calls by the peer when it has closed its end of the session.

Response:
def _ep_need_close(self):
        """Peer has closed its end of the session."""
        LOG.debug("Session %s close requested - closing...",
                  self._name)
        links = self._links.copy()  # may modify _links
        for link in links:
            link._session_closed()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _process_endpoint_event(self, event):
        state_fsm = Endpoint._FSM[self._state]
        entry = state_fsm.get(event)
        if not entry:
            # protocol error: invalid event for current state
            old_state = self._state
            self._state = Endpoint.STATE_ERROR
            self._ep_error("invalid event=%s in state=%s" %
                           (Endpoint.EVENT_NAMES[event],
                            Endpoint.STATE_NAMES[old_state]))
            return

        self._state = entry[0]
        if entry[1]:
            entry[1](self)

Response:
Called when the Proton Engine generates an endpoint state change
            event.


Instruction:
Implement a Python 3 function for
calling when the receiver has closed its end of the link.

Response:
def receiver_remote_closed(self, receiver_link, pn_condition):
        """Peer has closed its end of the link."""
        LOG.debug("receiver_remote_closed condition=%s", pn_condition)
        receiver_link.close()
        self.done = True


Instruction:
Given the following Python 3 function, write the documentation
def receiver_failed(self, receiver_link, error):
        LOG.warn("receiver_failed error=%s", error)
        receiver_link.close()
        self.done = True

Response: Callback when the receiver failed.


Instruction:
Can you tell what is the following Python 3 function doing
def get_host_port(server_address):
    regex = re.compile(r"^amqp://([a-zA-Z0-9.]+)(:([\d]+))?$")
    x = regex.match(server_address)
    if not x:
        raise Exception("Bad address syntax: %s" % server_address)
    matches = x.groups()
    host = matches[0]
    port = int(matches[2]) if matches[2] else None
    return host, port

Response: Parse the hostname and port out of the server_address.


Instruction:
Explain what the following Python 3 code does
def connect_socket(host, port, blocking=True):
    addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
    if not addr:
        raise Exception("Could not translate address '%s:%s'"
                        % (host, str(port)))
    my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2])
    if not blocking:
        my_socket.setblocking(0)
    try:
        my_socket.connect(addr[0][4])
    except socket.error as e:
        if e.errno != errno.EINPROGRESS:
            raise
    return my_socket

Response: Create a TCP connection to the server.


Instruction:
Explain what the following Python 3 code does
def server_socket(host, port, backlog=10):
    addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
    if not addr:
        raise Exception("Could not translate address '%s:%s'"
                        % (host, str(port)))
    my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2])
    my_socket.setblocking(0)  # 0=non-blocking
    try:
        my_socket.bind(addr[0][4])
        my_socket.listen(backlog)
    except socket.error as e:
        if e.errno != errno.EINPROGRESS:
            raise
    return my_socket

Response: Create a TCP listening socket for a server.


Instruction:
Here you have a function in Python 3, explain what it does
def process_connection(connection, my_socket):
    if connection.closed:
        return False

    work = False
    readfd = []
    writefd = []
    if connection.needs_input > 0:
        readfd = [my_socket]
        work = True
    if connection.has_output > 0:
        writefd = [my_socket]
        work = True

    timeout = None
    deadline = connection.next_tick
    if deadline:
        work = True
        now = time.time()
        timeout = 0 if deadline <= now else deadline - now

    if not work:
        return False

    readable, writable, ignore = select.select(readfd,
                                               writefd,
                                               [],
                                               timeout)
    if readable:
        try:
            pyngus.read_socket_input(connection, my_socket)
        except Exception as e:
            # treat any socket error as
            LOG.error("Socket error on read: %s", str(e))
            connection.close_input()
            # make an attempt to cleanly close
            connection.close()

    connection.process(time.time())
    if writable:
        try:
            pyngus.write_socket_output(connection, my_socket)
        except Exception as e:
            LOG.error("Socket error on write %s", str(e))
            connection.close_output()
            # this may not help, but it won't hurt:
            connection.close()
    return True

Response: Handle I / O and Timers on a single Connection.


Instruction:
Write a Python 3 function for
performing the actual processing of the current state of the connection.

Response:
def process(self, now):
        """Perform connection state processing."""
        if self._pn_connection is None:
            LOG.error("Connection.process() called on destroyed connection!")
            return 0

        # do nothing until the connection has been opened
        if self._pn_connection.state & proton.Endpoint.LOCAL_UNINIT:
            return 0

        if self._pn_sasl and not self._sasl_done:
            # wait until SASL has authenticated
            if (_PROTON_VERSION < (0, 10)):
                if self._pn_sasl.state not in (proton.SASL.STATE_PASS,
                                               proton.SASL.STATE_FAIL):
                    LOG.debug("SASL in progress. State=%s",
                              str(self._pn_sasl.state))
                    if self._handler:
                        with self._callback_lock:
                            self._handler.sasl_step(self, self._pn_sasl)
                    return self._next_deadline

                self._sasl_done = True
                if self._handler:
                    with self._callback_lock:
                        self._handler.sasl_done(self, self._pn_sasl,
                                                self._pn_sasl.outcome)
            else:
                if self._pn_sasl.outcome is not None:
                    self._sasl_done = True
                    if self._handler:
                        with self._callback_lock:
                            self._handler.sasl_done(self, self._pn_sasl,
                                                    self._pn_sasl.outcome)

        # process timer events:
        timer_deadline = self._expire_timers(now)
        transport_deadline = self._pn_transport.tick(now)
        if timer_deadline and transport_deadline:
            self._next_deadline = min(timer_deadline, transport_deadline)
        else:
            self._next_deadline = timer_deadline or transport_deadline

        # process events from proton:
        pn_event = self._pn_collector.peek()
        while pn_event:
            # LOG.debug("pn_event: %s received", pn_event.type)
            if _Link._handle_proton_event(pn_event, self):
                pass
            elif self._handle_proton_event(pn_event):
                pass
            elif _SessionProxy._handle_proton_event(pn_event, self):
                pass
            self._pn_collector.pop()
            pn_event = self._pn_collector.peek()

        # check for connection failure after processing all pending
        # engine events:
        if self._error:
            if self._handler:
                # nag application until connection is destroyed
                self._next_deadline = now
                with self._callback_lock:
                    self._handler.connection_failed(self, self._error)
        elif (self._endpoint_state == self._CLOSED and
              self._read_done and self._write_done):
            # invoke closed callback after endpoint has fully closed and
            # all pending I/O has completed:
            if self._handler:
                with self._callback_lock:
                    self._handler.connection_closed(self)

        return self._next_deadline


Instruction:
Create a Python 3 function to
get a buffer of data that needs to be written to the network.

Response:
def output_data(self):
        """Get a buffer of data that needs to be written to the network.
        """
        c = self.has_output
        if c <= 0:
            return None
        try:
            buf = self._pn_transport.peek(c)
        except Exception as e:
            self._connection_failed(str(e))
            return None
        return buf


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_sender(self, source_address, target_address=None,
                      event_handler=None, name=None, properties=None):
        """Factory method for Sender links."""
        ident = name or str(source_address)
        if ident in self._sender_links:
            raise KeyError("Sender %s already exists!" % ident)

        session = _SessionProxy("session-%s" % ident, self)
        session.open()
        sl = session.new_sender(ident)
        sl.configure(target_address, source_address, event_handler, properties)
        self._sender_links[ident] = sl
        return sl

Response: Factory method for sender links.


Instruction:
Write a Python 3 function for
rejecting the SenderLink and destroys the handle.

Response:
def reject_sender(self, link_handle, pn_condition=None):
        """Rejects the SenderLink, and destroys the handle."""
        link = self._sender_links.get(link_handle)
        if not link:
            raise Exception("Invalid link_handle: %s" % link_handle)
        link.reject(pn_condition)
        # note: normally, link.destroy() cannot be called from a callback,
        # but this link was never made available to the application so this
        # link is only referenced by the connection
        link.destroy()


Instruction:
How would you implement a function in Python 3 that
cleans up after connection failure detected.

Response:
def _connection_failed(self, error="Error not specified!"):
        """Clean up after connection failure detected."""
        if not self._error:
            LOG.error("Connection failed: %s", str(error))
            self._error = error


Instruction:
Explain what the following Python 3 code does
def _ep_active(self):
        LOG.debug("Connection is up")
        if self._handler:
            with self._callback_lock:
                self._handler.connection_active(self)

Response: Called when the connection is up.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _ep_need_close(self):
        LOG.debug("Connection remotely closed")
        if self._handler:
            cond = self._pn_connection.remote_condition
            with self._callback_lock:
                self._handler.connection_remote_closed(self, cond)

Response: The remote endpoint has closed its end of the endpoint.


Instruction:
Given the following Python 3 function, write the documentation
def _ep_error(self, error):
        super(Connection, self)._ep_error(error)
        self._connection_failed("Protocol error occurred.")

Response: The endpoint state machine failed due to protocol error.


Instruction:
Can you tell what is the following Python 3 function doing
def _get_color_string(self):
        s = ''
        if self.color_type == 'd':
            if self.name is "black":
                s = '%.3f G' % 0
            else:
                s = '%.3f %.3f %.3f RG' % (
                    self.red / 255.0, self.green / 255.0, self.blue / 255.0)
        elif self.color_type == 'f' or self.color_type == 't':
            if self.name is "black":
                s = '%.3f g' % 0
            else:
                s = '%.3f %.3f %.3f rg' % (
                    self.red / 255.0, self.green / 255.0, self.blue / 255.0)
        return s

Response: Return string for defining colors


Instruction:
Write a Python 3 script for
selecting a font ; size given in points

Response:
def _set_font(self, family=None, style=None, size=None):
        """Select a font; size given in points"""
        if style is not None:
            if 'B' in style:
                family += '_bold'
            if 'I' in style:
                family += '_italic'

        self._set_family(family)
        self._get_diffs()
        self._set_style(style)
        self._set_metrics()
        self._set_size(size)
        self._set_font_key()


Instruction:
Create a Python 3 function to
get the width of a string in the current font

Response:
def _string_width(self, s):
        """Get width of a string in the current font"""
        s = str(s)
        w = 0
        for char in s:
            char = ord(char)
            w += self.character_widths[char]
        return w * self.font_size / 1000.0


Instruction:
Given the following Python 3 function, write the documentation
def get_ttf(self):
        font_dict = {}
        families = []
        rootdirlist = string.split(self.search_path, os.pathsep)

        #for rootdir in rootdirlist:
        #    rootdir = os.path.expanduser(rootdir)
        for dirName, subdirList, filelist in itertools.chain.from_iterable(os.walk(path) for path in rootdirlist):
            for item in filelist:
                root, ext = os.path.splitext(item)
                if ext == '.ttf':
                    if root[0].lower() in english:
                        source = os.path.join(dirName, item)
                        name = root.lower().replace('_', ' ')
                        if ' bold' in name:
                            name = name.replace(' bold', '_bold')
                            if ' italic' in name:
                                name = name.replace(' italic', '_italic')
                        elif 'bold' in name:
                            name = name.replace('bold', '_bold')
                            if 'italic' in name:
                                name = name.replace('italic', '_italic')
                        elif ' italic' in name:
                            name = name.replace(' italic', '_italic')
                        elif 'italic' in name:
                            name = name.replace('italic', '_italic')
                        elif 'oblique' in name:
                            name = name.replace('oblique', '_italic')
                        else:
                            families.append(name)
                        font_dict[name] = source
                    else:
                        source = os.path.join(dirName, item)
                        name = root.lower().replace('_', ' ')
                        font_dict[name] = source
                        families.append(name)
        self.font_dict = font_dict
        self.families = families

Response: Given a search path find the TTF file and return a dictionary of font names and families.


Instruction:
Can you tell what is the following Python 3 function doing
def _set_compression(self, value):
        if isinstance(value, bool):
            self.compression = value
        else:
            raise Exception(
                TypeError, "%s is not a valid option for compression" % value)

Response: Sets the compression option for this object.


Instruction:
Write a Python 3 function that can
create the placeholder PDF objects for the most common PDF objects.

Response:
def _create_placeholder_objects(self):
        """ PDF objects #1 through #3 are typically saved for the
            Zeroth, Catalog, and Pages Objects. This program will save
            the numbers, but outputs the individual Page and Content objects
            first. The actual Catalog and Pages objects are calculated after.

        """
        self.objects.append("Zeroth")
        self.objects.append("Catalog")
        self.objects.append("Pages")


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _add_object(self, flag=None):
        self.offset = len(self.buffer)
        if flag is None:
            objnum = len(self.objects)
            obj = _PDFObject(objnum, self.offset)
            self.objects.append(obj)
        else:
            objnum = flag
            obj = _PDFObject(objnum, self.offset)
            self.objects[flag] = obj
        self._out(str(objnum) + ' 0 obj')
        return obj

Response: Add an object to the object array.


Instruction:
Create a Python 3 function for
writing the contents of the file into the buffer.

Response:
def _out(self, stream, page=None):
        """ Stores the pdf code in a buffer. If it is page related,
            provide the page object.

        """
        if page is not None:
            page.buffer += str(stream) + "\n"
        else:
            self.buffer += str(stream) + "\n"


Instruction:
Write a Python 3 function that can
create a PDF text stream

Response:
def _put_stream(self, stream):
        """ Creates a PDF text stream sandwich.

        """
        self._out('stream')
        self._out(stream)
        self._out('endstream')


Instruction:
Here you have a function in Python 3, explain what it does
def _add_page(self, text):
        save_cursor = self.parent.document.page.cursor.copy()
        save_cursor.x_reset()
        save_cursor.y_reset()
        self.parent.document.add_page()
        self.parent.document.set_cursor(save_cursor)
        self.parent.document.add_text(text)

Response: Helper function for PDFText to add a page and retry adding a large block of text.


Instruction:
Can you create a Python 3 function that
sets color scheme for the image.

Response:
def _set_color_scheme(self, draw_color=None, fill_color=None, text_color=None):
        """ Default color object is black letters
            & black lines."""
        if draw_color is None:
            draw_color = PDFColor()
            draw_color._set_type('d')
        if fill_color is None:
            fill_color = PDFColor()
            fill_color._set_type('f')
        if text_color is None:
            text_color = PDFColor()
            text_color._set_type('t')

        self.draw_color = draw_color
        self.fill_color = fill_color
        self.text_color = text_color


Instruction:
Can you generate the documentation for the following Python 3 function
def _set_default_font(self):
        self.font = PDFFont(self.session)
        self.font._set_index()
        self.fonts.append(self.font)
        self.fontkeys.append(self.font.font_key)

Response:
Internal method to set the default font. Change
            is a method that returns the font object.


Instruction:
How would you code a function in Python 3 to
add a new PDFPage to the PDF.

Response:
def add_page(self, page=None):
        """ May generate and add a PDFPage separately, or use this to generate
            a default page."""
        if page is None:
            self.page = PDFPage(self.orientation_default, self.layout_default, self.margins)
        else:
            self.page = page
        self.page._set_index(len(self.pages))
        self.pages.append(self.page)
        currentfont = self.font
        self.set_font(font=currentfont)
        self.session._reset_colors()


Instruction:
Can you generate the documentation for the following Python 3 function
def set_font(self, family=None, style='', size=None, font=None):
        if font:
            testfont = font
        elif isinstance(family, PDFFont):
            testfont = family
        else:
            # If size is not defined, keep the last size.
            if size is None:
                size = self.font.font_size

            # Create a font from givens to test its key
            if family in CORE_FONTS:
                testfont = PDFFont(self.session, family, style, size)
            else:
                testfont = PDFTTFont(self.session, family, style, size)

        testkey = testfont.font_key

        if testkey in self.fontkeys:
            index = self.fontkeys.index(testkey)
            self.font = self.fonts[index]
            if size != self.font.font_size:
                self.font._set_size(size)
            if style != self.font.style:
                self.font._set_style(style)
        else:
            self.font = testfont
            self._register_new_font(self.font)

        self.font.is_set = False

        if self.page.index > 0:
                self.session._out('BT /F%d %.2f Tf ET' %
                                  (self.font.index, self.font.font_size),
                                  self.page)
                self.font.is_set = True
        return self.font

Response: Set the document font object family style size and font.


Instruction:
How would you explain what the following Python 3 function does
def set_font_size(self, size):
        if self.font.font_size == size:
            pass
        else:
            self.font._set_size(size)

Response: Convenience method for just changing font size.


Instruction:
Can you implement a function in Python 3 that
inputs text short or long. Writes in order within the defined page boundaries.

Response:
def add_text(self, text, cursor=None, justification=None):
        """ Input text, short or long. Writes in order, within the defined page boundaries. Sequential add_text commands will print without
            additional whitespace. """
        if cursor is None:
            cursor = self.page.cursor

        text = re.sub("\s\s+" , " ", text)

        if justification is None:
            justification = self.justification

        if '\n' in text:
            text_list = text.split('\n')
            for text in text_list:
                PDFText(self.session, self.page, text, self.font, self.text_color, cursor, justification, self.double_spacing)
                self.add_newline()
        else:
            PDFText(self.session, self.page, text, self.font, self.text_color, cursor, justification, self.double_spacing)


Instruction:
Can you create a Python 3 function that
starts over at the new line.

Response:
def add_newline(self, number=1):
        """ Starts over again at the new line. If number is specified,
            it will leave multiple lines."""
        if isinstance(number, int):
            try:
                self.page._add_newline(self.font, number, self.double_spacing)
            except ValueError:
                self.add_page()
        else:
            raise TypeError("Number of newlines must be an integer.")


Instruction:
Make a summary of the following Python 3 code
def add_pie_chart(self, data, cursor, width, height, title=None, data_type="raw", fill_colors=None, labels=False, background=None, legend=None):
        save_draw_color = self.draw_color
        save_fill_color = self.fill_color

        chart = PDFPieChart(self.session, self.page, data, cursor, width, height, title, data_type, fill_colors, labels, background, legend)

        self.set_draw_color(save_draw_color)
        self.set_fill_color(save_fill_color)

Response: Add a pie chart to the page.


Instruction:
Write a Python 3 function for
calling by the PDFLite object to prompt creating the page objects.

Response:
def _output_pages(self):
        """ Called by the PDFLite object to prompt creating
            the page objects."""
        if not self.orientation_changes:
            self._get_orientation_changes()

        # Page
        for page in self.pages:
            obj = self.session._add_object()
            self.session._out('<</Type /Page')
            self.session._out('/Parent 1 0 R')
            if self.orientation_changes:
                self.session._out('/MediaBox [0 0 %.2f %.2f]' % (page.width, page.height))
            self.session._out('/Resources 2 0 R')
            self.session._out('/Group <</Type /Group /S /Transparency /CS /DeviceRGB>>')
            self.session._out('/Contents %s 0 R>>' % (obj.id + 1))
            self.session._out('endobj')

            # Page content
            self.session._add_object()
            if self.session.compression is True:
                textfilter = ' /Filter /FlateDecode '
                page._compress()
            else:
                textfilter = ''
            self.session._out('<<%s/Length %s >>' % (textfilter, len(page.buffer)))
            self.session._put_stream(page.buffer)
            self.session._out('endobj')


Instruction:
Implement a Python 3 function for
returning a list of the pages that have the most recent orientation changes.

Response:
def _get_orientation_changes(self):
        """ Returns a list of the pages that have
            orientation changes."""
        self.orientation_changes = []
        for page in self.pages:
            if page.orientation_change is True:
                self.orientation_changes.append(page.index)
            else:
                pass
        return self.orientation_changes


Instruction:
How would you explain what the following Python 3 function does
def _output_fonts(self):
        self.session._save_object_number()
        self._output_encoding_diffs()
        self._output_font_files()

        for font in self.fonts:
            obj = self.session._add_object()
            font._set_number(obj.id)
            font._output()

Response: Called by the PDFLite object to output the font objects.


Instruction:
Write a Python 3 function for
creating reference images that can be drawn throughout the document.

Response:
def _output_images(self):
        """ Creates reference images, that can be
            drawn throughout the document."""
        for image in self.images:
            obj = self.session._add_object()
            image._set_number(obj.id)
            image._output()


Instruction:
Can you generate the documentation for the following Python 3 function
def _output(self):
        self.session._out('<</Type /XObject')
        self.session._out('/Subtype /Image')
        self.session._out('/Width %s' % self.width)
        self.session._out('/Height %s' % self.height)

        if self.colorspace is 'Indexed':
            self.session._out('/ColorSpace [/Indexed /DeviceRGB %s %s 0 R' %
                              (self.pal, self.number + 1))
        else:
            self.session._out('/ColorSpace /%s' % self.colorspace)
            if self.colorspace is 'DeviceCMYK':
                self.session._out('/Decode [1 0 1 0 1 0 1 0]')

        self.session._out('/BitsPerComponent %s' % self.bits_per_component)

        if self.filter:
            self.session._out('/Filter /%s' % self.filter)
        if self.decode:
            self.session._out('/DecodeParms << %s >>' % self.decode)
        if self.transparent:
            self.session._out('/Mask [%s]' % self.transparent_string)
        if self.soft_mask:
            self.session._out('/SMask %s 0 R' % (self.number + 1))
        self.session._out('/Length %s >>' % self.size)
        self.session._put_stream(self.image_data)
        self.session._out('endobj')

        if self.colorspace is 'Indexed':
            self.session._out('<<%s /Length %s >>' % (self.palette_filter, self.palette_length))
            self.session._put_stream(self.palette)
            self.session._out('endobj')

        if isinstance(self.soft_mask, PDFImage):
            obj = self.session._add_object()
            self.soft_mask._set_number(obj.id)
            self.soft_mask._output()

Response: Prints the creation of image objects.


Instruction:
Given the following Python 3 function, write the documentation
def transform(self, a, b, c, d, e, f):
        a0, b0, c0, d0, e0, f0 = self._currentMatrix
        self._currentMatrix = (a0 * a + c0 * b, b0 * a + d0 * b,
                               a0 * c + c0 * d, b0 * c + d0 * d,
                               a0 * e + c0 * f + e0, b0 * e + d0 * f + f0)
        a1, b1, c1, d1, e1, f1 = self._currentMatrix
        self.session._out('%.2f %.2f %.2f %.2f %.2f %.2f cm' % (a1, b1, c1, d1, e1, f1), self.page)

Response: Adjust the current transformation state of the graphics state of the current graphics state.


Instruction:
Implement a function in Python 3 to
return the absolute position of x y in user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space w. r. t. default user space

Response:
def absolute_position(self, x, y):
        """return the absolute position of x,y in user space w.r.t. default user space"""
        (a, b, c, d, e, f) = self._currentMatrix
        xp = a * x + c * y + e
        yp = b * x + d * y + f
        return xp, yp


Instruction:
Can you write a function in Python 3 where it
rotates the current graphic state by the angle theta.

Response:
def rotate(self, theta):
        """Rotate current graphic state by the angle theta (in degrees)."""
        c = cos(theta * pi / 180)
        s = sin(theta * pi / 180)
        self.transform(c, s, -s, c, 0, 0)


Instruction:
Can you write a function in Python 3 where it
sets the style of the object.

Response:
def _set_style(self, style=None):
        """ Style should be a string, containing the letters 'B' for bold,
        'U' for underline, or 'I' for italic, or should be '', for no style.
        Symbol will not be underlined. The underline style can further be
        modified by specifying the underline thickness and position.

        """
        if style is None:
            self.style = ''
            self.underline = False
        # No syling for symbol
        elif self.family == ('symbol' or 'zapfdingbats'):
            self.style = ''
            self.underline = False

        self.style = style.upper()
            # SetUnderline

        if 'U' in self.style or self.style == 'U':
            self.underline = True
        else:
            self.underline = False


Instruction:
Write a Python 3 script for
selecting a font ; size given in points

Response:
def _set_font(self, family=None, style=None, size=None):
        """Select a font; size given in points"""
        self._set_family(family)
        self._set_style(style)
        self._set_size(size)
        self._set_font_key()
        self._set_name()
        self._set_character_widths()


Instruction:
Can you tell what is the following Python 3 function doing
def _string_width(self, s):
        s = str(s)
        w = 0
        for i in s:
            w += self.character_widths[i]
        return w * self.font_size / 1000.0

Response: Get the width of a string in the current font


Instruction:
Can you tell what is the following Python 3 function doing
def getCellVertexes(self, i, j):

        # Using unrotated centroid coordinates to avoid an extra computation
        x,y = self._getUnrotatedCellCentroidCoords(i, j)

        return [
            self.rotatePoint(x - self._side,       y                 ),
            self.rotatePoint(x - self._side / 2.0, y - self._hexPerp ),
            self.rotatePoint(x + self._side / 2.0, y - self._hexPerp ),
            self.rotatePoint(x + self._side,       y                 ),
            self.rotatePoint(x + self._side / 2.0, y + self._hexPerp ),
            self.rotatePoint(x - self._side / 2.0, y + self._hexPerp ),
            ]

Response: Returns a list of vertices of a cell in the system.


Instruction:
Explain what the following Python 3 code does
def rotatePoint(self, pointX, pointY):
        if(self.angle == 0 or self.angle == None):
            return(pointX, pointY)

        # 1. Compute the segment length
        length = math.sqrt((pointX - self.xll) ** 2 + (pointY - self.yll) ** 2)

        # 2. Compute beta
        beta = math.acos((pointX - self.xll) / length)
        if(pointY < self.yll):
            beta = math.pi * 2 - beta

        # 3. Compute offsets
        offsetX = math.cos(beta) * length - math.cos(self._angle_rd + beta) * length
        offsetY = math.sin(self._angle_rd + beta) * length - math.sin(beta) * length
        return (pointX - offsetX, pointY + offsetY)

Response: Rotates a point relative to the origin by the angle specified in the angle property.


Instruction:
Write a Python 3 function that can
set information about the items in the object.

Response:
def set_information(self, title=None, subject=None, author=None, keywords=None, creator=None):
        """ Convenience function to add property info, can set any attribute and leave the others blank, it won't over-write
            previously set items. """
        info_dict = {"title": title, "subject": subject,
                     "author": author, "keywords": keywords,
                     "creator": creator}

        for att, value in info_dict.iteritems():
            if hasattr(self, att):
                if value:
                    setattr(self, att, value)
            else:
                setattr(self, att, None)


Instruction:
Can you tell what is the following Python 3 function doing
def set_display_mode(self, zoom='fullpage', layout='continuous'):
        self.zoom_options = ["fullpage", "fullwidth", "real", "default"]
        self.layout_options = ["single", "continuous", "two", "default"]

        if zoom in self.zoom_options or (isinstance(zoom, int) and 0 < zoom <= 100):
            self.zoom_mode = zoom
        else:
            raise Exception('Incorrect zoom display mode: ' + zoom)

        if layout in self.layout_options:
            self.layout_mode = layout
        else:
            raise Exception('Incorrect layout display mode: ' + layout)

Response: Set the default viewing mode.


Instruction:
Given the following Python 3 function, write the documentation
def close(self):
        self.document._set_page_numbers()
        # Places header, pages, page content first.
        self._put_header()
        self._put_pages()
        self._put_resources()
        # Information object
        self._put_information()
        # Catalog object
        self._put_catalog()
        # Cross-reference object
        #self._put_cross_reference()
        # Trailer object
        self._put_trailer()

        if hasattr(self.destination, "write"):
            output = self._output_to_io()
        elif self.destination == 'string':
            output = self._output_to_string()
        else:
            self._output_to_file()
            output = None
        return output

Response: Prompt the objects to output pdf code and save to file.


Instruction:
Write a Python 3 script for
putting the header line in the PDF file.

Response:
def _put_header(self):
        """ Standard first line in a PDF. """
        self.session._out('%%PDF-%s' % self.pdf_version)
        if self.session.compression:
            self.session.buffer += '%' + chr(235) + chr(236) + chr(237) + chr(238) + "\n"


Instruction:
Can you tell what is the following Python 3 function doing
def _put_pages(self):
        self.document._get_orientation_changes()
        self.document._output_pages()

        # Pages Object, provides reference to page objects (Kids list).
        self.session._add_object(1)
        self.session._out('<</Type /Pages')
        kids = '/Kids ['
        for i in xrange(0, len(self.document.pages)):
            kids += str(3 + 2 * i) + ' 0 R '
        self.session._out(kids + ']')
        self.session._out('/Count %s' % len(self.document.pages))

        # Overall size of the default PDF page
        self.session._out('/MediaBox [0 0 %.2f %.2f]' %
                          (self.document.page.width,
                           self.document.page.height))
        self.session._out('>>')
        self.session._out('endobj')

Response: Create the pages object and output it.


Instruction:
How would you code a function in Python 3 to
add a dictionary containing the resource names and the font numbers.

Response:
def _put_resource_dict(self):
        """ Creates PDF reference to resource objects.

        """
        self.session._add_object(2)
        self.session._out('<<')
        self.session._out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]')
        self.session._out('/Font <<')
        for font in self.document.fonts:
            self.session._out('/F%s %s 0 R' % (font.index, font.number))
        self.session._out('>>')
        if self.document.images:
            self.session._out('/XObject <<')
            for image in self.document.images:
                self.session._out('/I%s %s 0 R' % (image.index, image.number))
            self.session._out('>>')
        self.session._out('>>')
        self.session._out('endobj')


Instruction:
Can you tell what is the following Python 3 function doing
def _put_information(self):
        self.session._add_object()
        self.session._out('<<')
        self.session._out('/Producer ' + self._text_to_string(
            'PDFLite, https://github.com/katerina7479'))
        if self.title:
            self.session._out('/Title ' + self._text_to_string(self.title))
        if self.subject:
            self.session._out('/Subject ' + self._text_to_string(self.subject))
        if self.author:
            self.session._out('/Author ' + self._text_to_string(self.author))
        if self.keywords:
            self.session._out('/Keywords ' +
                              self._text_to_string(self.keywords))
        if self.creator:
            self.session._out('/Creator ' + self._text_to_string(self.creator))
        self.session._out('/CreationDate ' + self._text_to_string(
            'D:' + datetime.now().strftime('%Y%m%d%H%M%S')))
        self.session._out('>>')
        self.session._out('endobj')

Response: Put the PDF Information object.


Instruction:
Given the following Python 3 function, write the documentation
def _put_catalog(self):
        self.session._add_object()
        self.session._out('<<')

        self.session._out('/Type /Catalog')
        self.session._out('/Pages 1 0 R')
        if self.zoom_mode == 'fullpage':
            self.session._out('/OpenAction [3 0 R /Fit]')
        elif self.zoom_mode == 'fullwidth':
            self.session._out('/OpenAction [3 0 R /FitH null]')
        elif self.zoom_mode == 'real':
            self.session._out('/OpenAction [3 0 R /XYZ null null 1]')
        elif not isinstance(self.zoom_mode, basestring):
            self.session._out(
                '/OpenAction [3 0 R /XYZ null null ' +
                (self.zoom_mode / 100) + ']')

        if self.layout_mode == 'single':
            self.session._out('/PageLayout /SinglePage')
        elif self.layout_mode == 'continuous':
            self.session._out('/PageLayout /OneColumn')
        elif self.layout_mode == 'two':
            self.session._out('/PageLayout /TwoColumnLeft')
        self.session._out('>>')
        self.session._out('endobj')

Response: Writes a catalog object.


Instruction:
Make a summary of the following Python 3 code
def _put_cross_reference(self):
        self.session._out('xref')
        self.session._out('0 %s' % len(self.session.objects))
        self.session._out('0000000000 65535 f ')
        for obj in self.session.objects:
            if isinstance(obj, basestring):
                pass
            else:
                self.session._out('%010d 00000 n ' % obj.offset)

Response: Put a Cross Reference Object.


Instruction:
Implement a function in Python 3 to
save the session to file.

Response:
def _output_to_file(self):
        """ Save to filepath specified on
            init. (Will throw an error if
            the document is already open).

        """
        f = open(self.filepath, 'wb')
        if not f:
            raise Exception('Unable to create output file: ', self.filepath)
        f.write(self.session.buffer)
        f.close()


Instruction:
Given the following Python 3 function, write the documentation
def _text_to_string(self, text):
        if text:
            for i,j in [("\\","\\\\"),(")","\\)"),("(", "\\(")]:
                text = text.replace(i, j)
            text = "(%s)" % text
        else:
            text = 'None'
        return text

Response: Converts text to string.


Instruction:
Make a summary of the following Python 3 code
def floyd(seqs, f=None, start=None, key=lambda x: x):

    tortise, hare = seqs

    yield hare.next()
    tortise_value = tortise.next()
    hare_value = hare.next()
    while hare_value != tortise_value:
        yield hare_value
        yield hare.next()
        hare_value = hare.next()
        tortise_value = tortise.next()

    if f is None:
        raise CycleDetected()

    hare_value = f(hare_value)
    first = 0
    tortise_value = start
    while key(tortise_value) != key(hare_value):
        tortise_value = f(tortise_value)
        hare_value = f(hare_value)
        first += 1

    period = 1
    hare_value = f(tortise_value)
    while key(tortise_value) != key(hare_value):
        hare_value = f(hare_value)
        period += 1

    raise CycleDetected(period=period, first=first)

Response: Floyd s Cycle Detector.


Instruction:
Here you have a function in Python 3, explain what it does
def gosper(seqs, f=None, start=None, key=lambda x: x):

    tab = []
    for c, value in enumerate(seqs[0], start=1):
        yield value
        try:
            e = tab.index(key(value))
            raise CycleDetected(
                period=c - ((((c >> e) - 1) | 1) << e))
        except ValueError:
            try:
                tab[(c ^ (c - 1)).bit_length() - 1] = key(value)
            except IndexError:
                tab.append(value)

Response: A generator function that yields values yielded by sequence_a if it terminates.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def brent(seqs, f=None, start=None, key=lambda x: x):

    power = period = 1
    tortise, hare = seqs

    yield hare.next()
    tortise_value = tortise.next()
    hare_value = hare.next()
    while key(tortise_value) != key(hare_value):
        yield hare_value
        if power == period:
            power *= 2
            period = 0
            if f:
                tortise = f_generator(f, hare_value)
                tortise_value = tortise.next()
            else:
                while tortise_value != hare_value:
                    tortise_value = tortise.next()
        hare_value = hare.next()
        period += 1

    if f is None:
        raise CycleDetected()

    first = 0
    tortise_value = hare_value = start
    for _ in xrange(period):
        hare_value = f(hare_value)

    while key(tortise_value) != key(hare_value):
        tortise_value = f(tortise_value)
        hare_value = f(hare_value)
        first += 1
    raise CycleDetected(period=period, first=first)

Response: A generator that yields all the possible values of a given function in a sequence.


Instruction:
Write a Python 3 script to
test to see if the line can have enough space for the given length.

Response:
def x_fit(self, test_length):
        """ Test to see if the line can has enough space for the given length. """
        if (self.x + test_length) >= self.xmax:
            return False
        else:
            return True


Instruction:
Write a Python 3 script to
test to see if the page has enough space for the given text height.

Response:
def y_fit(self, test_length):
        """ Test to see if the page has enough space for the given text height. """
        if (self.y + test_length) >= self.ymax:
            return False
        else:
            return True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def x_is_greater_than(self, test_ordinate):
        self._is_coordinate(test_ordinate)
        if self.x > test_ordinate.x:
            return True
        else:
            return False

Response: Returns True if self. x is greater than test_ordinate.


Instruction:
Make a summary of the following Python 3 code
def y_is_greater_than(self, test_ordinate):
        self._is_coordinate(test_ordinate)
        if self.y > test_ordinate.y:
            return True
        else:
            return False

Response: Returns True if y is greater than or equal to the y of the other instance.


Instruction:
Write a Python 3 function for
creating a copy of this cursor and return it.

Response:
def copy(self):
        """ Create a copy, and return it."""
        new_cursor = self.__class__(self.x, self.y)
        new_cursor.set_bounds(self.xmin, self.ymin, self.xmax, self.ymax, self.ymaxmax)
        new_cursor.set_deltas(self.dx, self.dy)
        return new_cursor


Instruction:
Explain what the following Python 3 code does
def x_plus(self, dx=None):
        if dx is None:
            self.x += self.dx
        else:
            self.x = self.x + dx

Response: Adds the x attribute to the current value.


Instruction:
How would you explain what the following Python 3 function does
def set_page_size(self, layout):
        self.layout = layout.lower()
        if self.layout in self.layout_dict:
            self.page_size = self.layout_dict[self.layout]
        else:
            dimensions = self.layout.split('x')
            if len(dimensions) == 2:
                self.page_size = (float(dimensions[0]) * 72, float(dimensions[1]) * 72)
            else:
                raise IndexError("Page is two dimensions, given: %s" % len(dimensions))

Response: Set page size of the related object.


Instruction:
How would you explain what the following Python 3 function does
def _draw(self):
        self._compile()
        self.rows[0]._advance_first_row()
        self._set_borders()
        self._draw_fill()
        self._draw_borders()
        self._draw_text()
        self._set_final_cursor()

Response: Don't use this, use document.draw_table


Instruction:
Write a Python 3 script to
create a new label and returns the response

Response:
def create(self, name, description=None, color=None):
        """
        Creates a new label and returns the response

        :param name: The label name
        :type name: str

        :param description: An optional description for the label. The name is
            used if no description is provided.
        :type description: str

        :param color: The hex color for the label (ex: 'ff0000' for red). If no
            color is provided, a random one will be assigned.
        :type color: str

        :returns: The response of your post
        :rtype: dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        data = {
            'name': name,
            'title': name,
            'description': description or name,
            'appearance': {
                'color': color or random_color()
            }
        }
        # Yes, it's confusing. the `/tags/` endpoint is used for labels
        return self._post(
            request=ApiActions.CREATE.value,
            uri=ApiUri.TAGS.value,
            params=data
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def list(self):
        return self._post(
            request='list',
            uri=ApiUri.TAGS.value,
        ).get('tags')

Response: Get all current labels in the Logentries API


Instruction:
Can you generate the documentation for the following Python 3 function
def get(self, name):
        labels = self.list()
        return [
            label
            for label
            in labels
            if name == label.get('name')
        ]

Response: Get labels by name.


Instruction:
Write a Python 3 script to
update a Label with the data in the format of dict.

Response:
def update(self, label):
        """
        Update a Label

        :param label: The data to update. Must include keys:

            * id (str)
            * appearance (dict)
            * description (str)
            * name (str)
            * title (str)
        :type label: dict

        Example:

        .. code-block:: python

            Labels().update(
                label={
                    'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43',
                    'appearance': {'color': '278abe'},
                    'name': 'My Sandbox',
                    'description': 'My Sandbox',
                    'title': 'My Sandbox',
                }
            )

        :return:
        :rtype: dict
        """
        data = {
            'id': label['id'],
            'name': label['name'],
            'appearance': label['appearance'],
            'description': label['description'],
            'title': label['title'],
        }
        return self._post(
            request=ApiActions.UPDATE.value,
            uri=ApiUri.TAGS.value,
            params=data
        )


Instruction:
Implement a function in Python 3 to
delete the specified label s ID

Response:
def delete(self, id):
        """
        Delete the specified label

        :param id: the label's ID
        :type id: str

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        return self._post(
            request=ApiActions.DELETE.value,
            uri=ApiUri.TAGS.value,
            params={'id': id}
        )


Instruction:
How would you explain what the following Python 3 function does
def create(self, label_id):
        data = {
            'type': 'tagit',
            'rate_count': 0,
            'rate_range': 'day',
            'limit_count': 0,
            'limit_range': 'day',
            'schedule': [],
            'enabled': True,
            'args': {
                'sn': label_id,
                'tag_sn': label_id
            }
        }
        # Yes, it's confusing. the `/actions/` endpoint is used for tags, while
        # the /tags/ endpoint is used for labels.
        return self._post(
            request=ApiActions.CREATE.value,
            uri=ApiUri.ACTIONS.value,
            params=data
        )

Response: This method creates a new tag entry in the Logentries database.


Instruction:
Can you write a function in Python 3 where it
gets all current tags in the logentries

Response:
def list(self):
        """
        Get all current tags

        :return: All tags
        :rtype: list of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        return list(
            filter(
                lambda x: x.get('type') == 'tagit',  # pragma: no cover
                self._post(
                    request=ApiActions.LIST.value,
                    uri=ApiUri.ACTIONS.value,
                ).get('actions')
            )
        )


Instruction:
Can you implement a function in Python 3 that
gets tags by a label s sn key.

Response:
def get(self, label_sn):
        """
        Get tags by a label's sn key

        :param label_sn: A corresponding label's ``sn`` key.
        :type label_sn: str or int

        :return: A list of matching tags. An empty list is returned if there are
            not any matches
        :rtype: list of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        tags = self.list()
        return [
            tag
            for tag
            in tags
            if str(label_sn) in tag.get('args', {}).values()
        ]


Instruction:
Create a Python 3 function to
create a new hook with the given name and regexes and tags.

Response:
def create(self, name, regexes, tag_ids, logs=None):
        """
        Create a hook

        :param name: The hook's name (should be the same as the tag)
        :type name: str

        :param regexes: The list of regular expressions that Logentries expects.
            Ex: `['user_agent = /curl\/[\d.]*/']` Would match where the
            user-agent is curl.
        :type regexes: list of str

        :param tag_id: The ids of the tags to associate the hook with.
            (The 'id' key of the create tag response)
        :type tag_id: list of str

        :param logs: The logs to add the hook to. Comes from the 'key'
            key in the log dict.
        :type logs: list of str

        :returns: The response of your post
        :rtype: dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        data = {
            'name': name,
            'triggers': regexes,
            'sources': logs or [],
            'groups': [],
            'actions': tag_ids
        }
        return self._post(
            request=ApiActions.CREATE.value,
            uri=ApiUri.HOOKS.value,
            params=data
        )


Instruction:
Here you have a function in Python 3, explain what it does
def list(self):
        return self._post(
            request=ApiActions.LIST.value,
            uri=ApiUri.HOOKS.value,
        ).get('hooks')

Response: Get all current hooks


Instruction:
Can you create a Python 3 function that
gets a list of matching tags.

Response:
def get(self, name_or_tag_id):
        """
        Get hooks by name or tag_id.
        :param name_or_tag_id: The hook's name or associated tag['id']
        :type name_or_tag_id: str

        :return: A list of matching tags. An empty list is returned if there are
            not any matches
        :rtype: list of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        hooks = self.list()

        return [
            hook
            for hook
            in hooks
            if name_or_tag_id in hook.get('actions')
            or name_or_tag_id == hook.get('name')
        ]


Instruction:
Implement a function in Python 3 to
update a specific hook.

Response:
def update(self, hook):
        """
        Update a hook

        :param hook: The data to update. Must include keys:

            * id (str)
            * name (str)
            * triggers (list of str)
            * sources (list of str)
            * groups (list of str)
            * actions (list of str)
        :type hook: dict

        Example:

        .. code-block:: python

            Hooks().update(
                hook={
                    'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43',
                    'name': 'My Sandbox',
                    'triggers': [
                        'host = you.example.com'
                    ],
                    'sources': [
                        '4d42c719-4005-4929-aa4a-994da4b95040'
                    ],
                    'groups': [],
                    'actions': [
                        '9f6adf69-37b9-4a4b-88fb-c3fc4c781a11',
                        'ddc36d71-33cb-4f4f-be1b-8591814b1946'
                    ],
                }
            )

        :return:
        :rtype: dict
        """
        data = {
            'id': hook['id'],
            'name': hook['name'],
            'triggers': hook['triggers'],
            'sources': hook['sources'],
            'groups': hook['groups'],
            'actions': hook['actions'],
        }
        return self._post(
            request=ApiActions.UPDATE.value,
            uri=ApiUri.HOOKS.value,
            params=data
        )


Instruction:
How would you explain what the following Python 3 function does
def create(self,
               alert_config,
               occurrence_frequency_count=None,
               occurrence_frequency_unit=None,
               alert_frequency_count=None,
               alert_frequency_unit=None):
        """
        Create a new alert

        :param alert_config: A list of AlertConfig classes (Ex:
            ``[EmailAlertConfig('me@mydomain.com')]``)
        :type alert_config: list of
            :class:`PagerDutyAlertConfig<logentries_api.alerts.PagerDutyAlertConfig>`,
            :class:`WebHookAlertConfig<logentries_api.alerts.WebHookAlertConfig>`,
            :class:`EmailAlertConfig<logentries_api.alerts.EmailAlertConfig>`,
            :class:`SlackAlertConfig<logentries_api.alerts.SlackAlertConfig>`, or
            :class:`HipChatAlertConfig<logentries_api.alerts.HipChatAlertConfig>`

        :param occurrence_frequency_count: How many times per
            ``alert_frequency_unit`` for a match before issuing an alert.
            Defaults to 1
        :type occurrence_frequency_count: int

        :param occurrence_frequency_unit: The time period to monitor for sending
            an alert. Must be 'day', or 'hour'. Defaults to 'hour'
        :type occurrence_frequency_unit: str

        :param alert_frequency_count: How many times per
            ``alert_frequency_unit`` to issue an alert. Defaults to 1
        :type alert_frequency_count: int

        :param alert_frequency_unit: How often to regulate sending alerts.
            Must be 'day', or 'hour'. Defaults to 'hour'
        :type alert_frequency_unit: str

        :returns: The response of your post
        :rtype: dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        data = {
            'rate_count': occurrence_frequency_count or 1,
            'rate_range': occurrence_frequency_unit or 'hour',
            'limit_count': alert_frequency_count or 1,
            'limit_range': alert_frequency_unit or 'hour',
            'schedule': [],
            'enabled': True,
        }
        data.update(alert_config.args())

        # Yes, it's confusing. the `/actions/` endpoint is used for alerts, while
        # the /tags/ endpoint is used for labels.
        return self._post(
            request=ApiActions.CREATE.value,
            uri=ApiUri.ACTIONS.value,
            params=data
        )

Response: Creates a new alert in the logentries base.


Instruction:
Create a Python 3 function for
getting alerts that match the provided alert type and args.

Response:
def get(self, alert_type, alert_args=None):
        """
        Get alerts that match the alert type and args.

        :param alert_type: The type of the alert. Must be one of 'pagerduty',
            'mailto', 'webhook', 'slack', or 'hipchat'
        :type alert_type: str

        :param alert_args: The args for the alert. The provided args must be a
            subset of the actual alert args. If no args are provided, all
            alerts matching the ``alert_type`` are returned. For example:
            ``.get('mailto', alert_args={'direct': 'me@mydomain.com'})`` or
            ``.get('slack', {'url': 'https://hooks.slack.com/services...'})``

        :return: A list of matching alerts. An empty list is returned if there
            are not any matches
        :rtype: list of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        alert_args = alert_args or {}

        alerts = self.list()
        return [
            alert
            for alert
            in alerts
            if alert.get('type') == alert_type
            and dict_is_subset(alert_args, alert.get('args'))
        ]


Instruction:
Write a Python 3 function that can
update an alert with the data in the format that is expected by the API.

Response:
def update(self, alert):
        """
        Update an alert

        :param alert: The data to update. Must include keys:

            * id (str)
            * rate_count (int)
            * rate_range (str): 'day' or 'hour'
            * limit_count (int)
            * limit_range (str): 'day' or 'hour'
            * type (str)
            * schedule (list)
            * args (dict)
        :type alert: dict

        Example:

        .. code-block:: python

            Alert().update(
                alert={
                    'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43',
                    'args': {'direct': 'you@example.com'},
                    'rate_count': 1,
                    'rate_range': 'hour',
                    'limit_count': 1,
                    'limit_range': 'hour',
                    'schedule': [],
                    'enabled': True,
                    'type': 'mailto',
                }
            )

        :return:
        :rtype: dict
        """
        data = {
            'id': alert['id'],
            'args': alert['args'],
            'rate_count': alert['rate_count'],
            'rate_range': alert['rate_range'],
            'limit_count': alert['limit_count'],
            'limit_range': alert['limit_range'],
            'schedule': alert['schedule'],
            'enabled': alert['enabled'],
            'type': alert['type'],
        }

        return self._post(
            request=ApiActions.UPDATE.value,
            uri=ApiUri.ACTIONS.value,
            params=data
        )


Instruction:
Implement a function in Python 3 to
initialize this Sphinx extension

Response:
def setup(app):
    """
    Initialize this Sphinx extension
    """
    app.setup_extension('sphinx.ext.todo')
    app.setup_extension('sphinx.ext.mathjax')

    app.setup_extension("sphinx.ext.intersphinx")
    app.config.intersphinx_mapping.update({
        'https://docs.python.org/': None
        })
    app.config.intersphinx_mapping.update({
        sage_doc_url + doc + "/": None
        for doc in sage_documents
        })
    app.config.intersphinx_mapping.update({
        sage_doc_url + "reference/" + module: None
        for module in sage_modules
        })

    app.setup_extension("sphinx.ext.extlinks")
    app.config.extlinks.update({
        'python': ('https://docs.python.org/release/'+pythonversion+'/%s', ''),
        # Sage trac ticket shortcuts. For example, :trac:`7549` .
        'trac': ('https://trac.sagemath.org/%s', 'trac ticket #'),
        'wikipedia': ('https://en.wikipedia.org/wiki/%s', 'Wikipedia article '),
        'arxiv': ('http://arxiv.org/abs/%s', 'Arxiv '),
        'oeis': ('https://oeis.org/%s', 'OEIS sequence '),
        'doi': ('https://dx.doi.org/%s', 'doi:'),
        'pari': ('http://pari.math.u-bordeaux.fr/dochtml/help/%s', 'pari:'),
        'mathscinet': ('http://www.ams.org/mathscinet-getitem?mr=%s', 'MathSciNet ')
        })

    app.config.html_theme = 'sage'


Instruction:
How would you code a function in Python 3 to
retrieve the location of the themes directory from the location of this package

Response:
def themes_path():
    """
    Retrieve the location of the themes directory from the location of this package

    This is taken from Sphinx's theme documentation
    """
    package_dir = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(package_dir, 'themes')


Instruction:
Make a summary of the following Python 3 code
def _post(self, request, uri, params=None):
        request_data = {
            'acl': self.account_key,
            'account': self.account_key,
            'request': request,
        }

        request_data.update(params or {})

        response = requests.post(
            url='https://api.logentries.com/v2/{}'.format(uri),
            headers=self.headers,
            data=json.dumps(request_data)
        )

        if not response.ok:
            raise ServerException(
                '{}: {}'.format(response.status_code, response.text))
        return response.json()

Response: A wrapper for making a POST request to the Logentries API endpoint.


Instruction:
Can you generate the documentation for the following Python 3 function
def list(self):
        response = requests.get(self.base_url)

        if not response.ok:
            raise ServerException(
                '{}: {}'.format(response.status_code, response.text))

        return {
            host.get('name'): [
                log.get('key')
                for log
                in host.get('logs')]
            for host
            in response.json().get('list')
        }

Response: Get all log sets in the Logentries API.


Instruction:
How would you explain what the following Python 3 function does
def get(self, log_set):
        response = requests.get(self.base_url + log_set.rstrip('/'))

        if not response.ok:
            raise ServerException(
                '{}: {}'.format(response.status_code, response.text))
        return response.json()

Response: Get a specific log set or log.


Instruction:
Can you generate the documentation for the following Python 3 function
def find_attacker_slider(dest_list, occ_bb, piece_bb, target_bb, pos,
                             domain):
    """ Find a slider attacker

    Parameters
    ----------
    dest_list : list
        To store the results.
    occ_bb : int, bitboard
        Occupancy bitboard.
    piece_bb : int, bitboard
        Bitboard with the position of the attacker piece.
    target_bb : int, bitboard
        Occupancy bitboard without any of the sliders in question.
    pos : int
        Target position.
    pos_map : function
        Mapping between a board position and its position in a single
        rotated/translated rank produced with domain_trans.
    domain_trans : function
        Transformation from a rank/file/diagonal/anti-diagonal containing pos
        to a single rank
    pos_inv_map : function
        Inverse of pos_map
    """
    pos_map, domain_trans, pos_inv_map = domain
    r = reach[pos_map(pos)][domain_trans(target_bb, pos)]
    m = r & domain_trans(piece_bb, pos)
    while m:
        r = m&-m
        rpos = r.bit_length()-1
        if not (ray[rpos][pos_map(pos)] & domain_trans(occ_bb, pos)):
            dest_list.append(pos_inv_map(rpos, pos))
        m ^= r

Response: Find a slider attacker that is in question.


Instruction:
Can you tell what is the following Python 3 function doing
def duration(self):
        '''
        The approximate transit duration for the general case of an eccentric orbit

        '''
        ecc = self.ecc if not np.isnan(self.ecc) else np.sqrt(self.ecw**2 + self.esw**2)
        esw = self.esw if not np.isnan(self.esw) else ecc * np.sin(self.w)
        aRs = ((G * self.rhos * (1. + self.MpMs) *
              (self.per * DAYSEC)**2.) / (3. * np.pi))**(1./3.)
        inc = np.arccos(self.bcirc/aRs)
        becc = self.bcirc * (1 - ecc**2)/(1 - esw)
        tdur = self.per / 2. / np.pi * np.arcsin(((1. + self.RpRs)**2 -
               becc**2)**0.5 / (np.sin(inc) * aRs))
        tdur *= np.sqrt(1. - ecc**2.)/(1. - esw)
        return tdur

Response: Returns the approximate transit duration for the general case of an eccentric orbit


Instruction:
How would you implement a function in Python 3 that
updates the transit keyword arguments

Response:
def update(self, **kwargs):
    '''
    Update the transit keyword arguments

    '''

    if kwargs.get('verify_kwargs', True):
      valid = [y[0] for x in [TRANSIT, LIMBDARK, SETTINGS] for y in x._fields_]       # List of valid kwargs
      valid += ['b', 'times']                                                         # These are special!
      for k in kwargs.keys():
        if k not in valid:
          raise Exception("Invalid kwarg '%s'." % k)

    if ('q1' in kwargs.keys()) and ('q2' in kwargs.keys()):
      kwargs.update({'ldmodel': KIPPING})
    elif ('c1' in kwargs.keys()) and ('c2' in kwargs.keys()) and \
         ('c3' in kwargs.keys()) and ('c4' in kwargs.keys()):
      kwargs.update({'ldmodel': NONLINEAR})

    self.limbdark.update(**kwargs)
    self.transit.update(**kwargs)
    self.settings.update(**kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
def Compute(self):
    '''
    Computes the light curve model

    '''

    err = _Compute(self.transit, self.limbdark, self.settings, self.arrays)
    if err != _ERR_NONE: RaiseError(err)

Response: Computes the light curve model.


Instruction:
Write a Python 3 function that can
bin the light curve model to the provided time array.

Response:
def Bin(self):
    '''
    Bins the light curve model to the provided time array

    '''

    err = _Bin(self.transit, self.limbdark, self.settings, self.arrays)
    if err != _ERR_NONE: RaiseError(err)


Instruction:
Implement a function in Python 3 to
free the memory used by all of the dynamically allocated C arrays.

Response:
def Free(self):
    '''
    Frees the memory used by all of the dynamically allocated C arrays.

    '''

    if self.arrays._calloc:
      _dbl_free(self.arrays._time)
      _dbl_free(self.arrays._flux)
      _dbl_free(self.arrays._bflx)
      _dbl_free(self.arrays._M)
      _dbl_free(self.arrays._E)
      _dbl_free(self.arrays._f)
      _dbl_free(self.arrays._r)
      _dbl_free(self.arrays._x)
      _dbl_free(self.arrays._y)
      _dbl_free(self.arrays._z)
      self.arrays._calloc = 0
    if self.arrays._balloc:
      _dbl_free(self.arrays._b)
      self.arrays._balloc = 0
    if self.arrays._ialloc:
      _dbl_free(self.arrays._iarr)
      self.arrays._ialloc = 0


Instruction:
Write a Python 3 function that can
read data from the socket and writes it to the buffer.

Response:
def __recv(self, size=4096):
        """Reads data from the socket.

        Raises:
            NNTPError: When connection times out or read from socket fails.
        """
        data = self.socket.recv(size)
        if not data:
            raise NNTPError("Failed to read from socket")
        self.__buffer.write(data)


Instruction:
How would you explain what the following Python 3 function does
def __buf_gen(self, length=0):
        while True:
            buf = self.__buffer.read(length)
            if not buf:
                self.__recv()
                continue
            yield buf

Response: Generator that reads a block of data from the server.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def status(self):
        line = next(self.__line_gen()).rstrip()
        parts = line.split(None, 1)

        try:
            code, message = int(parts[0]), ""
        except ValueError:
            raise NNTPProtocolError(line)

        if code < 100 or code >= 600:
            raise NNTPProtocolError(line)

        if len(parts) > 1:
            message = parts[1]

        if 400 <= code <= 499:
            raise NNTPTemporaryError(code, message)

        if 500 <= code <= 599:
            raise NNTPPermanentError(code, message)

        return code, message

Response: Reads a status line from the socket and returns it as a tuple.


Instruction:
Here you have a function in Python 3, explain what it does
def __info_gzip_gen(self):
        self.__generating = True

        inflate = zlib.decompressobj(15+32)

        done, buf = False, fifo.Fifo()
        while not done:
            try:
                data = inflate.decompress(next(self.__buf_gen()))
            except zlib.error:
                raise NNTPDataError("Decompression failed")
            if data:
                buf.write(data)
            if inflate.unused_data:
                buf.write(inflate.unused_data)
            for line in buf:
                if line == ".\r\n":
                    done = True
                    break
                if line.startswith("."):
                    yield line[1:]
                yield line

        self.__generating = False

Response: Generator for the lines of a compressed info response.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __info_yenczlib_gen(self):

        escape = 0
        dcrc32 = 0
        inflate = zlib.decompressobj(-15)

        # header
        header = next(self.__info_plain_gen())
        if not header.startswith("=ybegin"):
            raise NNTPDataError("Bad yEnc header")

        # data
        buf, trailer = fifo.Fifo(), ""
        for line in self.__info_plain_gen():
            if line.startswith("=yend"):
                trailer = line
                continue
            data, escape, dcrc32 = yenc.decode(line, escape, dcrc32)
            try:
                data = inflate.decompress(data)
            except zlib.error:
                raise NNTPDataError("Decompression failed")
            if not data:
                continue
            buf.write(data)
            for l in buf:
                yield l

        # trailer
        if not trailer:
            raise NNTPDataError("Missing yEnc trailer")

        # expected crc32
        ecrc32 = yenc.crc32(trailer)
        if ecrc32 is None:
            raise NNTPDataError("Bad yEnc trailer")

        # check crc32
        if ecrc32 != dcrc32 & 0xffffffff:
            raise NNTPDataError("Bad yEnc CRC")

Response: Generator for the lines of a compressed info response.


Instruction:
Given the following Python 3 function, write the documentation
def info_gen(self, code, message, compressed=False):
        if "COMPRESS=GZIP" in message:
            return self.__info_gzip_gen()
        if compressed:
            return self.__info_yenczlib_gen()
        return self.__info_plain_gen()

Response: This function is used to generate the info for a specific entry point.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def info(self, code, message, compressed=False):
        return "".join([x for x in self.info_gen(code, message, compressed)])

Response: Returns the complete content of an info response.


Instruction:
Implement a Python 3 function for
calling a command on the server.

Response:
def command(self, verb, args=None):
        """Call a command on the server.

        If the user has not authenticated then authentication will be done
        as part of calling the command on the server.

        For commands that don't return a status message the status message
        will default to an empty string.

        Args:
            verb: The verb of the command to call.
            args: The arguments of the command as a string (default None).

        Returns:
            A tuple of status code (as an integer) and status message.

        Note:
            You can run raw commands by supplying the full command (including
            args) in the verb.

        Note: Although it is possible you shouldn't issue more than one command
            at a time by adding newlines to the verb as it will most likely lead
            to undesirable results.
        """
        if self.__generating:
            raise NNTPSyncError("Command issued while a generator is active")

        cmd = verb
        if args:
            cmd += " " + args
        cmd += "\r\n"

        self.socket.sendall(cmd)

        try:
            code, message = self.status()
        except NNTPTemporaryError as e:
            if e.code() != 480:
                raise e
            code, message = self.command("AUTHINFO USER", self.username)
            if code == 381:
                code, message = self.command("AUTHINFO PASS", self.password)
            if code != 281:
                raise NNTPReplyError(code, message)
            code, message = self.command(verb, args)

        return code, message


Instruction:
Can you generate the documentation for the following Python 3 function
def mode_reader(self):
        code, message = self.command("MODE READER")
        if not code in [200, 201]:
            raise NNTPReplyError(code, message)

        return code == 200

Response: Instructs a mode - switching server to switch modes.