Instruction:
How would you code a function in Python 3 to
block function. Opens OpenCV window to display stream.

Response:
def preview(self):
        """ Blocking function. Opens OpenCV window to display stream. """
        win_name = 'Camera'
        cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE)
        cv2.moveWindow(win_name,20,20)
        self.open()
        while(self.isOpened()):
            cv2.imshow(win_name,self._stream.read()[1])
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break
        cv2.waitKey()
        cv2.destroyAllWindows()
        cv2.waitKey()


Instruction:
Given the following Python 3 function, write the documentation
def createWidgets(self):
    # Create Setup button
    self.setup = Button(self.master, width=20, padx=3, pady=3)
    self.setup["text"] = "Setup"
    self.setup["command"] = self.setupMovie
    self.setup.grid(row=1, column=0, padx=2, pady=2)

    # Create Play button
    self.start = Button(self.master, width=20, padx=3, pady=3)
    self.start["text"] = "Play"
    self.start["command"] = self.playMovie
    self.start.grid(row=1, column=1, padx=2, pady=2)

    # Create Pause button
    self.pause = Button(self.master, width=20, padx=3, pady=3)
    self.pause["text"] = "Pause"
    self.pause["command"] = self.pauseMovie
    self.pause.grid(row=1, column=2, padx=2, pady=2)

    # Create Teardown button
    self.teardown = Button(self.master, width=20, padx=3, pady=3)
    self.teardown["text"] = "Teardown"
    self.teardown["command"] =  self.exitClient
    self.teardown.grid(row=1, column=3, padx=2, pady=2)

    # Create a label to display the movie
    self.label = Label(self.master, height=19)
    self.label.grid(row=0, column=0, columnspan=4, sticky=W+E+N+S, padx=5, pady=5)

Response:
Create the GUI for the movie
   .


Instruction:
How would you explain what the following Python 3 function does
def writeFrame(self, data):

    cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT

    try:
      file = open(cachename, "wb")
    except:
      print "file open error"

    try:
      file.write(data)
    except:
      print "file write error"

    file.close()

    return cachename

Response: Write the received frame to a temp image file. Return the image file.


Instruction:
Can you tell what is the following Python 3 function doing
def connectToServer(self):
    self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
      self.rtspSocket.connect((self.serverAddr, self.serverPort))
    except:
      tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)

Response: Connect to the Server.


Instruction:
Can you generate the documentation for the following Python 3 function
def openRtpPort(self):
    #-------------
    # TO COMPLETE
    #-------------
    # Create a new datagram socket to receive RTP packets from the server
    # self.rtpSocket = ...

    # Set the timeout value of the socket to 0.5sec
    # ...
    self.rtpSocket.settimeout(0.5)
#   try:
      # Bind the socket to the address using the RTP port given by the client user
      # ...
#   except:
#     tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)

    try:
      #self.rtpSocket.connect(self.serverAddr,self.rtpPort)
      self.rtpSocket.bind((self.serverAddr,self.rtpPort))   # WATCH OUT THE ADDRESS FORMAT!!!!!  rtpPort# should be bigger than 1024
      #self.rtpSocket.listen(5)
      print "Bind RtpPort Success"

    except:
      tkMessageBox.showwarning('Connection Failed', 'Connection to rtpServer failed...')

Response: Open a datagram socket binded to a specified port.


Instruction:
Explain what the following Python 3 code does
def handler(self):
    self.pauseMovie()
    if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):
      self.exitClient()
    else: # When the user presses cancel, resume playing.
      #self.playMovie()
      print "Playing Movie"
      threading.Thread(target=self.listenRtp).start()
      #self.playEvent = threading.Event()
      #self.playEvent.clear()
      self.sendRtspRequest(self.PLAY)

Response: Handler on explicitly closing the GUI window.


Instruction:
Make a summary of the following Python 3 code
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):

		timestamp = int(time())
		print("timestamp: " + str(timestamp))
		self.header = bytearray(HEADER_SIZE)
		#--------------
		# TO COMPLETE
		#--------------
		# Fill the header bytearray with RTP header fields

		#RTP-version filed(V), must set to 2
		#padding(P),extension(X),number of contributing sources(CC) and marker(M) fields all set to zero in this lab

		#Because we have no other contributing sources(field CC == 0),the CSRC-field does not exist
		#Thus the length of the packet header is therefore 12 bytes

			#Above all done in ServerWorker.py

		# ...
		#header[] =

		#header[0] = version + padding + extension + cc + seqnum + marker + pt + ssrc
		self.header[0] = version << 6
		self.header[0] = self.header[0] | padding << 5
		self.header[0] = self.header[0] | extension << 4
		self.header[0] = self.header[0] | cc
		self.header[1] = marker << 7
		self.header[1] = self.header[1] | pt

		self.header[2] = seqnum >> 8
		self.header[3] = seqnum

		self.header[4] = (timestamp >> 24) & 0xFF
		self.header[5] = (timestamp >> 16) & 0xFF
		self.header[6] = (timestamp >> 8) & 0xFF
		self.header[7] = timestamp & 0xFF

		self.header[8] = ssrc >> 24
		self.header[9] = ssrc >> 16
		self.header[10] = ssrc >> 8
		self.header[11] = ssrc

		# Get the payload from the argument
		# self.payload = ...
		self.payload = payload

Response: Encode the RTP packet with header fields and payload.


Instruction:
Write a Python 3 script to
skip through the input iterator without recording the content.

Response:
def skip(self):
        """
        Eats through the input iterator without recording the content.
        """
        for pos, element in self.element_iter:
            tag, class_attr = _tag_and_class_attr(element)
            if tag == "div" and "thread" in class_attr and pos == "end":
                break


Instruction:
How would you code a function in Python 3 to
parse an HTML element and stores the relevant attributes.

Response:
def _process_element(self, pos, e):
        """
        Parses an incoming HTML element/node for data.

        pos -- the part of the element being parsed
               (start/end)
        e   -- the element being parsed
        """
        tag, class_attr = _tag_and_class_attr(e)

        start_of_message = tag == 'div' and class_attr == 'message' and pos == 'start'
        end_of_thread = tag == 'div' and 'thread' in class_attr and pos == 'end'

        if start_of_message and not self.messages_started:
            self.messages_started = True
        elif tag == "span" and pos == "end":
            if "user" in class_attr:
                self.current_sender = self.name_resolver.resolve(e.text)
            elif "meta" in class_attr:
                self.current_timestamp =\
                    parse_timestamp(e.text, self.use_utc, self.timezone_hints)
        elif tag == 'p' and pos == 'end':
            # This is only necessary because of accidental double <p> nesting on
            # Facebook's end. Clearly, QA and testing is one of Facebook's strengths ;)
            if not self.current_text:
                self.current_text = e.text.strip() if e.text else ''
        elif tag == 'img' and pos == 'start':
            self.current_text = '(image reference: {})'.format(e.attrib['src'])
        elif (start_of_message or end_of_thread) and self.messages_started:
            if not self.current_timestamp:
                # This is the typical error when the new Facebook format is
                # used with the legacy parser.
                raise UnsuitableParserError
            if not self.current_sender:
                if not self.no_sender_warning_status:
                    sys.stderr.write(
                        "\rWARNING: The sender was missing in one or more parsed messages. "
                        "This is an error on Facebook's end that unfortunately cannot be "
                        "recovered from. Some or all messages in the output may show the "
                        "sender as 'Unknown' within each thread.\n")
                    self.no_sender_warning_status = True
                self.current_sender = "Unknown"

            cm = ChatMessage(timestamp=self.current_timestamp,
                             sender=self.current_sender,
                             content=self.current_text or '',
                             seq_num=self.seq_num)
            self.messages += [cm]

            self.seq_num -= 1
            self.current_sender, self.current_timestamp, self.current_text = None, None, None

        return end_of_thread


Instruction:
Given the following Python 3 function, write the documentation
def should_record_thread(self, participants):
        if not self.thread_filter:
            return True
        if len(participants) != len(self.thread_filter):
            return False
        participants = [[p.lower()] + p.lower().split(" ")
                        for p in participants]
        matches = defaultdict(set)
        for e, p in enumerate(participants):
            for f in self.thread_filter:
                if f in p:
                    matches[f].add(e)
        matched = set()
        for f in matches:
            if len(matches[f]) == 0:
                return False
            matched |= matches[f]
        return len(matched) == len(participants)

Response: Determines if the thread should be parsed based on the filter given.


Instruction:
Given the following Python 3 function, write the documentation
def parse_thread(self, participants, element_iter, require_flush):

        # Very rarely threads may lack information on who the
        # participants are. We will consider those threads corrupted
        # and skip them.
        participants_text = _truncate(', '.join(participants), 60)
        if participants:
            skip_thread = not self.should_record_thread(participants)
            participants_text = yellow("[%s]" % participants_text)
        else:
            participants_text = "unknown participants"
            skip_thread = True
        if skip_thread:
            line = "\rSkipping chat thread with %s..." % \
                   yellow(participants_text)
        else:
            participants_key = ", ".join(participants)
            if participants_key in self.chat_threads:
                thread_current_len = len(self.chat_threads[participants_key])
                line = "\rContinuing chat thread with %s %s..." \
                       % (yellow(participants_text), magenta("<@%d messages>" % thread_current_len))
            else:
                line = "\rDiscovered chat thread with %s..." \
                       % yellow(participants_text)
        if self.progress_output:
            sys.stderr.write(line.ljust(self.last_line_len))
            sys.stderr.flush()
        self.last_line_len = len(line)

        parser = ChatThreadParser(
            element_iter, self.timezone_hints, self.use_utc, self.name_resolver,
            self.no_sender_warning, self.seq_num)

        if skip_thread:
            if require_flush:
                parser.skip()
        else:
            self.no_sender_warning, thread = parser.parse(participants)
            return thread

Response: Parses a thread with appropriate CLI feedback.


Instruction:
Write a Python 3 function that can
clear the output of the current process.

Response:
def _clear_output(self):
        """
        Clears progress output (if any) that was written to the screen.
        """
        # If progress output was being written, clear it from the screen.
        if self.progress_output:
            sys.stderr.write("\r".ljust(self.last_line_len))
            sys.stderr.write("\r")
            sys.stderr.flush()


Instruction:
How would you implement a function in Python 3 that
parses the HTML content as a stream.

Response:
def parse_impl(self):
        """
        Parses the HTML content as a stream. This is far less memory
        intensive than loading the entire HTML file into memory, like
        BeautifulSoup does.
        """

        # Cast to str to ensure not unicode under Python 2, as the parser
        # doesn't like that.
        parser = XMLParser(encoding=str('UTF-8'))
        element_iter = ET.iterparse(self.handle, events=("start", "end"), parser=parser)
        for pos, element in element_iter:
            tag, class_attr = _tag_and_class_attr(element)
            if tag == "h1" and pos == "end":
                if not self.user:
                    self.user = element.text.strip()
            elif tag == "div" and "thread" in class_attr and pos == "start":
                participants = self.parse_participants(element)
                thread = self.parse_thread(participants, element_iter, True)
                self.save_thread(thread)


Instruction:
Can you tell what is the following Python 3 function doing
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory):
    with colorize_output(nocolor):
        try:
            chat_history = _process_history(
                path=path, thread=thread, timezones=timezones,
                utc=utc, noprogress=noprogress, resolve=resolve)
        except ProcessingFailure:
            return
        if directory:
            set_all_color(enabled=False)
        write(fmt, chat_history, directory or sys.stdout)

Response: Writes the chat history to a file.


Instruction:
Explain what the following Python 3 code does
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length):
    with colorize_output(nocolor):
        try:
            chat_history = _process_history(
                path=path, thread='', timezones=timezones,
                utc=utc, noprogress=noprogress, resolve=resolve)
        except ProcessingFailure:
            return
        statistics = ChatHistoryStatistics(
            chat_history, most_common=None if most_common < 0 else most_common)
        if fmt == 'text':
            statistics.write_text(sys.stdout, -1 if length < 0 else length)
        elif fmt == 'json':
            statistics.write_json(sys.stdout)
        elif fmt == 'pretty-json':
            statistics.write_json(sys.stdout, pretty=True)
        elif fmt == 'yaml':
            statistics.write_yaml(sys.stdout)

Response: Analysis of Facebook chat history.


Instruction:
Implement a function in Python 3 to
set sys. stdout and sys. stderr to stream.

Response:
def set_stream_color(stream, disabled):
    """
    Remember what our original streams were so that we
    can colorize them separately, which colorama doesn't
    seem to natively support.
    """
    original_stdout = sys.stdout
    original_stderr = sys.stderr

    init(strip=disabled)

    if stream != original_stdout:
        sys.stdout = original_stdout
        sys.stderr = BinaryStreamWrapper(stream, sys.stderr)
    if stream != original_stderr:
        sys.stderr = original_stderr
        sys.stdout = BinaryStreamWrapper(stream, sys.stdout)


Instruction:
Make a summary of the following Python 3 code
def _manual_lookup(self, facebook_id, facebook_id_string):
        resp = self._session.get(
            'https://www.facebook.com/%s' % facebook_id,
            allow_redirects=True, timeout=10
        )
        # No point in trying to get this using BeautifulSoup. The HTML here
        # is the very epitome of what it is to be invalid...
        m = _MANUAL_NAME_MATCHER.search(resp.text)
        if m:
            name = m.group(1)
        else:
            name = facebook_id_string
        self._cached_profiles[facebook_id] = name
        return name

Response: Get the user s name from Facebook.


Instruction:
How would you explain what the following Python 3 function does
def parse_timestamp(raw_timestamp, use_utc, hints):
    global FACEBOOK_TIMESTAMP_FORMATS
    timestamp_string, offset = raw_timestamp.rsplit(" ", 1)
    if "UTC+" in offset or "UTC-" in offset:
        if offset[3] == '-':
            offset = [-1 * int(x) for x in offset[4:].split(':')]
        else:
            offset = [int(x) for x in offset[4:].split(':')]
    else:
        offset_hint = hints.get(offset, None)
        if not offset_hint:
            if offset not in TIMEZONE_MAP:
                raise UnexpectedTimeFormatError(raw_timestamp)
            elif len(TIMEZONE_MAP[offset]) > 1:
                raise AmbiguousTimeZoneError(offset, TIMEZONE_MAP[offset])
            offset = list(TIMEZONE_MAP[offset].keys())[0][:2]
        else:
            offset = offset_hint

    if len(offset) == 1:
        # Timezones without minute offset may be formatted
        # as UTC+X (e.g UTC+8)
        offset += [0]

    delta = dt_timedelta(hours=offset[0], minutes=offset[1])

    # Facebook changes the format depending on whether the user is using
    # 12-hour or 24-hour clock settings.
    for number, date_parser in enumerate(_LOCALIZED_DATE_PARSERS):
        timestamp = date_parser.parse(timestamp_string)
        if timestamp is None:
            continue
        # Re-orient the list to ensure that the one that worked is tried first next time.
        if number > 0:
            del FACEBOOK_TIMESTAMP_FORMATS[number]
            FACEBOOK_TIMESTAMP_FORMATS = [date_parser] + FACEBOOK_TIMESTAMP_FORMATS
        break
    else:
        raise UnexpectedTimeFormatError(raw_timestamp)
    if use_utc:
        timestamp -= delta
        return timestamp.replace(tzinfo=pytz.utc)
    else:
        return timestamp.replace(tzinfo=TzInfoByOffset(delta))

Response: Parses a string into a FACEBOOK_TIMESTAMP_FORMATS dictionary.


Instruction:
How would you code a function in Python 3 to
register an exporter to use for a specific type of object.

Response:
def register_exporter(name, base_class):
    """
    Register an exporter to use for a :class:`Part <cqparts.Part>`,
    :class:`Assembly <cqparts.Assembly>`, or both
    (with :class:`Component <cqparts.Component>`).

    Registration is necessary to use with
    :meth:`Component.exporter() <cqparts.Component.exporter>`.

    :param name: name (or 'key') of exporter
    :type name: :class:`str`
    :param base_class: class of :class:`Component <cqparts.Component>` to export
    :type base_class: :class:`type`

    .. doctest::

        >>> from cqparts import Part
        >>> from cqparts.codec import Exporter, register_exporter

        >>> @register_exporter('my_type', Part)
        ... class MyExporter(Exporter):
        ...     def __call__(self, filename='out.mytype'):
        ...         print("export %r to %s" % (self.obj, filename))

        >>> from cqparts_misc.basic.primatives import Sphere
        >>> thing = Sphere(radius=5)
        >>> thing.exporter('my_type')('some-file.mytype')
        export <Sphere: radius=5.0> to some-file.mytype

    """
    # Verify params
    if not isinstance(name, str) or (not name):
        raise TypeError("invalid name: %r" % name)
    if not issubclass(base_class, Component):
        raise TypeError("invalid base_class: %r, must be a %r subclass" % (base_class, Component))

    def decorator(cls):
        # --- Verify
        # Can only be registered once
        if base_class in exporter_index[name]:
            raise TypeError("'%s' exporter type %r has already been registered" % (
                name, base_class
            ))

        # Verify class hierarchy will not conflict
        # (so you can't have an exporter for a Component, and a Part. must be
        #  an Assembly, and a Part, respectively)
        for key in exporter_index[name].keys():
            if issubclass(key, base_class) or issubclass(base_class, key):
                raise TypeError("'%s' exporter type %r is in conflict with %r" % (
                    name, base_class, key,
                ))

        # --- Index
        exporter_index[name][base_class] = cls

        return cls
    return decorator


Instruction:
How would you code a function in Python 3 to
get an exporter instance for the given object

Response:
def get_exporter(obj, name):
    """
    Get an exporter for the

    :param obj: object to export
    :type obj: :class:`Component <cqparts.Component>`
    :param name: registered name of exporter
    :type name: :class:`str`
    :return: an exporter instance of the given type
    :rtype: :class:`Exporter`
    :raises TypeError: if exporter cannot be found
    """
    if name not in exporter_index:
        raise TypeError(
            ("exporter type '%s' is not registered: " % name) +
            ("registered types: %r" % sorted(exporter_index.keys()))
        )

    for base_class in exporter_index[name]:
        if isinstance(obj, base_class):
            return exporter_index[name][base_class](obj)

    raise TypeError("exporter type '%s' for a %r is not registered" % (
        name, type(obj)
    ))


Instruction:
Here you have a function in Python 3, explain what it does
def get_importer(cls, name):
    if name not in importer_index:
        raise TypeError(
            ("importer type '%s' is not registered: " % name) +
            ("registered types: %r" % sorted(importer_index.keys()))
        )

    for base_class in importer_index[name]:
        if issubclass(cls, base_class):
            return importer_index[name][base_class](cls)

    raise TypeError("importer type '%s' for a %r is not registered" % (
        name, cls
    ))

Response: Returns an importer instance of the given type.


Instruction:
Write a Python 3 script for
parsing pagenated list of products

Response:
def parse(self, response):
        """Parse pagenated list of products"""

        # Check if page is out of range
        no_more_products = re.search(
            r'No matching products were found',
            response.css('div.paged-results').extract_first(),
            flags=re.I
        )
        if no_more_products:
            pass  # no more pages to populate, stop scraping

        else:
            # Scrape products list
            for product in response.css('article.product-list__item'):
                product_url = product.css('a::attr("href")').extract_first()
                yield response.follow(product_url, self.parse_detail)

            (base, params) = split_url(response.url)
            params.update({'page': int(params.get('page', '1')) + 1})
            next_page_url = join_url(base, params)
            self.logger.info(next_page_url)
            yield response.follow(next_page_url, self.parse)


Instruction:
How would you implement a function in Python 3 that
parses individual product s detail

Response:
def parse_detail(self, response):
        """Parse individual product's detail"""
        # Product Information (a start)
        product_data = {
            'url': response.url,
            'name': response.css('div.page-title h1::text').extract_first(),
        }

        # Inventory Number
        inventory_number = re.search(
            r'(?P<inv_num>\d+)$',
            response.css('span.product-in::text').extract_first(),
        ).group('inv_num')
        product_data.update({'in': inventory_number})

        # Specifications (arbitrary key:value pairs)
        specs_table = response.css('#tab-specs dl')
        for row in specs_table.css('div.spec-row'):
            keys = row.css('dt::text').extract()
            values = row.css('dd::text').extract()
            product_data.update({
                key: value
                for (key, value) in zip(keys, values)
            })

        self.logger.info(product_data['name'])
        yield product_data


Instruction:
Can you tell what is the following Python 3 function doing
def solver(constraints, coord_sys=None):

    if coord_sys is None:
        coord_sys = CoordSystem()  # default

    # Verify list contains constraints
    for constraint in constraints:
        if not isinstance(constraint, Constraint):
            raise ValueError("{!r} is not a constraint".format(constraint))

    solved_count = 0

    indexed = list(constraints)

    # Continue running solver until no solution is found
    while indexed:
        indexes_solved = []
        for (i, constraint) in enumerate(indexed):

            # Fixed
            if isinstance(constraint, Fixed):
                indexes_solved.append(i)
                yield (
                    constraint.mate.component,
                    coord_sys + constraint.world_coords + (CoordSystem() - constraint.mate.local_coords)
                )

            # Coincident
            elif isinstance(constraint, Coincident):
                try:
                    relative_to = constraint.to_mate.world_coords
                except ValueError:
                    relative_to = None

                if relative_to is not None:
                    indexes_solved.append(i)
                    # note: relative_to are world coordinates; adding coord_sys is not necessary
                    yield (
                        constraint.mate.component,
                        relative_to + (CoordSystem() - constraint.mate.local_coords)
                    )

        if not indexes_solved:  # no solutions found
            # At least 1 solution must be found each iteration.
            # if not, we'll just be looping forever.
            break
        else:
            # remove constraints from indexed list (so they're not solved twice)
            for j in reversed(indexes_solved):
                del indexed[j]

    if indexed:
        raise ValueError("not all constraints could be solved")

Response:
Solve constraints. Solutions pair :class:`Constraint <cqparts.constraint.Constraint>`
    instances with their suitable :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`
    world coordinates.

    :param constraints: constraints to solve
    :type constraints: iterable of :class:`Constraint <cqparts.constraint.Constraint>`
    :param coord_sys: coordinate system to offset solutions (default: no offset)
    :type coord_sys: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`

    :return: generator of (:class:`Component <cqparts.Component>`,
             :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`) tuples.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def solid(solid_in):
    if isinstance(solid_in, cadquery.Solid):
        return solid_in
    elif isinstance(solid_in, cadquery.CQ):
        return solid_in.val()

    raise CastingError(
        "Cannot cast object type of {!r} to a solid".format(solid_in)
    )

Response: Casts a solid instance to cadquery. Solid instance.


Instruction:
Make a summary of the following Python 3 code
def vector(vect_in):
    if isinstance(vect_in, cadquery.Vector):
        return vect_in
    elif isinstance(vect_in, (tuple, list)):
        return cadquery.Vector(vect_in)

    raise CastingError(
        "Cannot cast object type of {!r} to a vector".format(vect_in)
    )

Response: Converts a single object to a cadquery. Vector instance.


Instruction:
Write a Python 3 script for
creating solid to cut the fastener s into the head of the fastener s material.

Response:
def make_cutter(self):
        """
        Create solid to subtract from material to make way for the fastener's
        head (just the head)
        """
        return cadquery.Workplane('XY') \
            .circle(self.access_diameter / 2) \
            .extrude(self.access_height)


Instruction:
Create a Python 3 function for
verifying version consistency and return the correct classifier

Response:
def version_classifier(version_str):
    """
    Verify version consistency:
    version number must correspond to the correct "Development Status" classifier
    :raises: ValueError if error found, but ideally this function does nothing
    """
    # cast version
    version = LooseVersion(version_str)

    for (test_ver, classifier) in reversed(sorted(VERSION_CLASSIFIER_MAP, key=lambda x: x[0])):
        if version >= test_ver:
            return classifier

    raise ValueError("could not find valid 'Development Status' classifier for v{}".format(version_str))


Instruction:
Create a Python 3 function for
topping of the stator

Response:
def mate_top(self):
        " top of the stator"
        return Mate(self, CoordSystem(
            origin=(0, 0, self.length/2),
            xDir=(0, 1, 0),
            normal=(0, 0, 1)
            ))


Instruction:
How would you implement a function in Python 3 that
bottoms of the stator

Response:
def mate_bottom(self):
        " bottom of the stator"
        return Mate(self, CoordSystem(
            origin=(0, 0, -self.length/2),
            xDir=(1, 0, 0),
            normal=(0, 0, -1)
            ))


Instruction:
Implement a function in Python 3 to
return the names of all class parameters.

Response:
def class_param_names(cls, hidden=True):
        """
        Return the names of all class parameters.

        :param hidden: if ``False``, excludes parameters with a ``_`` prefix.
        :type hidden: :class:`bool`
        :return: set of parameter names
        :rtype: :class:`set`
        """
        param_names = set(
            k for (k, v) in cls.__dict__.items()
            if isinstance(v, Parameter)
        )
        for parent in cls.__bases__:
            if hasattr(parent, 'class_param_names'):
                param_names |= parent.class_param_names(hidden=hidden)

        if not hidden:
            param_names = set(n for n in param_names if not n.startswith('_'))
        return param_names


Instruction:
Can you implement a function in Python 3 that
returns a dictionary of all class parameters and their values.

Response:
def class_params(cls, hidden=True):
        """
        Gets all class parameters, and their :class:`Parameter` instances.

        :return: dict of the form: ``{<name>: <Parameter instance>, ... }``
        :rtype: :class:`dict`

        .. note::

            The :class:`Parameter` instances returned do not have a value, only
            a default value.

            To get a list of an **instance's** parameters and values, use
            :meth:`params` instead.

        """
        param_names = cls.class_param_names(hidden=hidden)
        return dict(
            (name, getattr(cls, name))
            for name in param_names
        )


Instruction:
Can you implement a function in Python 3 that
gets all instance parameters and their cast values.

Response:
def params(self, hidden=True):
        """
        Gets all instance parameters, and their *cast* values.

        :return: dict of the form: ``{<name>: <value>, ... }``
        :rtype: :class:`dict`
        """
        param_names = self.class_param_names(hidden=hidden)
        return dict(
            (name, getattr(self, name))
            for name in param_names
        )


Instruction:
Make a summary of the following Python 3 code
def serialize(self):
        return {
            # Encode library information (future-proofing)
            'lib': {
                'name': 'cqparts',
                'version': __version__,
            },
            # class & name record, for automated import when decoding
            'class': {
                'module': type(self).__module__,
                'name': type(self).__name__,
            },
            'params': self.serialize_parameters(),
        }

Response: Serialize a cqpart object to an object that can be serialized by the json module.


Instruction:
Can you implement a function in Python 3 that
gets the parameter data in its serialized form.

Response:
def serialize_parameters(self):
        """
        Get the parameter data in its serialized form.

        Data is serialized by each parameter's :meth:`Parameter.serialize`
        implementation.

        :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}``
        :rtype: :class:`dict`
        """

        # Get parameter data
        class_params = self.class_params()
        instance_params = self.params()

        # Serialize each parameter
        serialized = {}
        for name in class_params.keys():
            param = class_params[name]
            value = instance_params[name]
            serialized[name] = param.serialize(value)
        return serialized


Instruction:
How would you implement a function in Python 3 that
creates instance from serial data

Response:
def deserialize(data):
        """
        Create instance from serial data
        """
        # Import module & get class
        try:
            module = import_module(data.get('class').get('module'))
            cls = getattr(module, data.get('class').get('name'))
        except ImportError:
            raise ImportError("No module named: %r" % data.get('class').get('module'))
        except AttributeError:
            raise ImportError("module %r does not contain class %r" % (
                data.get('class').get('module'),
                data.get('class').get('name')
            ))

        # Deserialize parameters
        class_params = cls.class_params(hidden=True)
        params = dict(
            (name, class_params[name].deserialize(value))
            for (name, value) in data.get('params').items()
        )

        # Instantiate new instance
        return cls(**params)


Instruction:
Write a Python 3 function for
classing decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( type='motor', current_class='dc', part_number='ABC123X', ) class SomeMotor(cqparts.Assembly): shaft_diam = PositiveFloat(5) def make_components(self): return {} # build assembly content motor_class = cqparts.search.find(part_number='ABC123X') motor = motor_class(shaft_diam=6.0) Then use :meth:`find` &/or :meth:`search` to instantiate it. .. warning:: Multiple classes *can* be registered with identical criteria, but should be avoided. If multiple classes share the same criteria, :meth:`find` will never yield the part you want. Try adding unique criteria, such as *make*, *model*, *part number*, *library name*, &/or *author*. To avoid this, learn more in :ref:`tutorial_component-index`.

Response:
def register(**criteria):
    """
    class decorator to add :class:`Part <cqparts.Part>` or
    :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index:

    .. testcode::

        import cqparts
        from cqparts.params import *

        # Created Part or Assembly
        @cqparts.search.register(
            type='motor',
            current_class='dc',
            part_number='ABC123X',
        )
        class SomeMotor(cqparts.Assembly):
            shaft_diam = PositiveFloat(5)
            def make_components(self):
                return {}  # build assembly content

        motor_class = cqparts.search.find(part_number='ABC123X')
        motor = motor_class(shaft_diam=6.0)

    Then use :meth:`find` &/or :meth:`search` to instantiate it.

    .. warning::

        Multiple classes *can* be registered with identical criteria, but
        should be avoided.

        If multiple classes share the same criteria, :meth:`find` will never
        yield the part you want.

        Try adding unique criteria, such as *make*, *model*, *part number*,
        *library name*, &/or *author*.

        To avoid this, learn more in :ref:`tutorial_component-index`.
    """

    def inner(cls):
        # Add class references to search index
        class_list.add(cls)
        for (category, value) in criteria.items():
            index[category][value].add(cls)

        # Retain search criteria
        _entry = dict((k, set([v])) for (k, v) in criteria.items())
        if cls not in class_criteria:
            class_criteria[cls] = _entry
        else:
            for key in _entry.keys():
                class_criteria[cls][key] = class_criteria[cls].get(key, set()) | _entry[key]

        # Return class
        return cls

    return inner


Instruction:
How would you implement a function in Python 3 that
searches registered component classes matching the given criteria.

Response:
def search(**criteria):
    """
    Search registered *component* classes matching the given criteria.

    :param criteria: search criteria of the form: ``a='1', b='x'``
    :return: parts registered with the given criteria
    :rtype: :class:`set`

    Will return an empty :class:`set` if nothing is found.

    ::

        from cqparts.search import search
        import cqparts_motors  # example of a 3rd party lib

        # Get all DC motor classes
        dc_motors = search(type='motor', current_class='dc')

        # For more complex queries:
        air_cooled = search(cooling='air')
        non_aircooled_dcmotors = dc_motors - air_cooled
        # will be all DC motors that aren't air-cooled
    """
    # Find all parts that match the given criteria
    results = copy(class_list)  # start with full list
    for (category, value) in criteria.items():
        results &= index[category][value]

    return results


Instruction:
How would you implement a function in Python 3 that
finds a single component class with the given criteria.

Response:
def find(**criteria):
    """
    Find a single *component* class with the given criteria.

    Finds classes indexed with :meth:`register`

    :raises SearchMultipleFoundError: if more than one result found
    :raises SearchNoneFoundError: if nothing found

    ::

        from cqparts.search import find
        import cqparts_motors  # example of a 3rd party lib

        # get a specific motor class
        motor_class = find(type='motor', part_number='ABC123X')
        motor = motor_class(shaft_diameter=6.0)
    """
    # Find all parts that match the given criteria
    results = search(**criteria)

    # error cases
    if len(results) > 1:
        raise SearchMultipleFoundError("%i results found" % len(results))
    elif not results:
        raise SearchNoneFoundError("%i results found" % len(results))

    # return found Part|Assembly class
    return results.pop()


Instruction:
Write a Python 3 function for
wrapping a function to always call with the given ``common`` named parameters. :property common: criteria common to your function call :return: decorator function :rtype: :class:`function` .. doctest:: >>> import cqparts >>> from cqparts.search import register, search, find >>> from cqparts.search import common_criteria >>> # Somebody elses (boring) library may register with... >>> @register(a='one', b='two') ... class BoringThing(cqparts.Part): ... pass >>> # But your library is awesome; only registering with unique criteria... >>> lib_criteria = { ... 'author': 'your_name', ... 'libname': 'awesome_things', ... } >>> awesome_register = common_criteria(**lib_criteria)(register) >>> @awesome_register(a='one', b='two') # identical to BoringThing ... class AwesomeThing(cqparts.Part): ... pass >>> # So lets try a search >>> len(search(a='one', b='two')) # doctest: +SKIP 2 >>> # oops, that returned both classes >>> # To narrow it down, we add something unique: >>> len(search(a='one', b='two', libname='awesome_things')) # finds only yours # doctest: +SKIP 1 >>> # or, we could use common_criteria again... >>> awesome_search = common_criteria(**lib_criteria)(search) >>> awesome_find = common_criteria(**lib_criteria)(find) >>> len(awesome_search(a='one', b='two')) # doctest: +SKIP 1 >>> awesome_find(a='one', b='two').__name__ 'AwesomeThing' A good universal way to apply unique criteria is with .. testcode:: import cadquery, cqparts from cqparts.search import register, common_criteria _register = common_criteria(module=__name__)(register) @_register(shape='cube', scale='unit') class Cube(cqparts.Part): # just an example... def make(self): return cadquery.Workplane('XY').box(1, 1, 1)

Response:
def common_criteria(**common):
    """
    Wrap a function to always call with the given ``common`` named parameters.

    :property common: criteria common to your function call
    :return: decorator function
    :rtype: :class:`function`

    .. doctest::

        >>> import cqparts
        >>> from cqparts.search import register, search, find
        >>> from cqparts.search import common_criteria

        >>> # Somebody elses (boring) library may register with...
        >>> @register(a='one', b='two')
        ... class BoringThing(cqparts.Part):
        ...     pass

        >>> # But your library is awesome; only registering with unique criteria...
        >>> lib_criteria = {
        ...     'author': 'your_name',
        ...     'libname': 'awesome_things',
        ... }

        >>> awesome_register = common_criteria(**lib_criteria)(register)

        >>> @awesome_register(a='one', b='two')  # identical to BoringThing
        ... class AwesomeThing(cqparts.Part):
        ...     pass

        >>> # So lets try a search
        >>> len(search(a='one', b='two')) # doctest: +SKIP
        2
        >>> # oops, that returned both classes

        >>> # To narrow it down, we add something unique:
        >>> len(search(a='one', b='two', libname='awesome_things'))  # finds only yours # doctest: +SKIP
        1

        >>> # or, we could use common_criteria again...
        >>> awesome_search = common_criteria(**lib_criteria)(search)
        >>> awesome_find = common_criteria(**lib_criteria)(find)
        >>> len(awesome_search(a='one', b='two')) # doctest: +SKIP
        1
        >>> awesome_find(a='one', b='two').__name__
        'AwesomeThing'

    A good universal way to apply unique criteria is with

    .. testcode::

        import cadquery, cqparts
        from cqparts.search import register, common_criteria
        _register = common_criteria(module=__name__)(register)

        @_register(shape='cube', scale='unit')
        class Cube(cqparts.Part):
            # just an example...
            def make(self):
                return cadquery.Workplane('XY').box(1, 1, 1)

    """
    def decorator(func):
        def inner(*args, **kwargs):
            merged_kwargs = copy(common)
            merged_kwargs.update(kwargs)
            return func(*args, **merged_kwargs)
        return inner
    return decorator


Instruction:
Can you write a function in Python 3 where it
combines bounding boxes to result in a single BoundBox that encloses all of them.

Response:
def merge_boundboxes(*bb_list):
    """
    Combine bounding boxes to result in a single BoundBox that encloses
    all of them.

    :param bb_list: List of bounding boxes
    :type bb_list: :class:`list` of :class:`cadquery.BoundBox`
    """
    # Verify types
    if not all(isinstance(x, cadquery.BoundBox) for x in bb_list):
        raise TypeError(
            "parameters must be cadquery.BoundBox instances: {!r}".format(bb_list)
        )

    if len(bb_list) <= 1:
        return bb_list[0]  # if only 1, nothing to merge; simply return it

    # Find the smallest bounding box to enclose each of those given
    min_params = list(min(*vals) for vals in zip(  # minimum for each axis
        *((bb.xmin, bb.ymin, bb.zmin) for bb in bb_list)
    ))
    max_params = list(max(*vals) for vals in zip(  # maximum for each axis
        *((bb.xmax, bb.ymax, bb.zmax) for bb in bb_list)
    ))

    #__import__('ipdb').set_trace()

    # Create new object with combined parameters
    WrappedType = type(bb_list[0].wrapped)  # assuming they're all the same
    wrapped_bb = WrappedType(*(min_params + max_params))
    return cadquery.BoundBox(wrapped_bb)


Instruction:
Write a Python 3 function for
returning a new instance of a new cqterm object with the same attributes as the given plane

Response:
def from_plane(cls, plane):
        """
        :param plane: cadquery plane instance to base coordinate system on
        :type plane: :class:`cadquery.Plane`
        :return: duplicate of the given plane, in this class
        :rtype: :class:`CoordSystem`

        usage example:

        .. doctest::

            >>> import cadquery
            >>> from cqparts.utils.geometry import CoordSystem
            >>> obj = cadquery.Workplane('XY').circle(1).extrude(5)
            >>> plane = obj.faces(">Z").workplane().plane
            >>> isinstance(plane, cadquery.Plane)
            True
            >>> coord_sys = CoordSystem.from_plane(plane)
            >>> isinstance(coord_sys, CoordSystem)
            True
            >>> coord_sys.origin.z
            5.0
        """
        return cls(
            origin=plane.origin.toTuple(),
            xDir=plane.xDir.toTuple(),
            normal=plane.zDir.toTuple(),
        )


Instruction:
Make a summary of the following Python 3 code
def from_transform(cls, matrix):
        # Create reference points at origin
        offset = FreeCAD.Vector(0, 0, 0)
        x_vertex = FreeCAD.Vector(1, 0, 0)  # vertex along +X-axis
        z_vertex = FreeCAD.Vector(0, 0, 1)  # vertex along +Z-axis

        # Transform reference points
        offset = matrix.multiply(offset)
        x_vertex = matrix.multiply(x_vertex)
        z_vertex = matrix.multiply(z_vertex)

        # Get axis vectors (relative to offset vertex)
        x_axis = x_vertex - offset
        z_axis = z_vertex - offset

        # Return new instance
        vect_tuple = lambda v: (v.x, v.y, v.z)
        return cls(
            origin=vect_tuple(offset),
            xDir=vect_tuple(x_axis),
            normal=vect_tuple(z_axis),
        )

Response: r Returns a unit zero offset coordinate system transformed by the given affine transform.


Instruction:
Write a Python 3 function for
creating a randomized coordinate system.

Response:
def random(cls, span=1, seed=None):
        """
        Creates a randomized coordinate system.

        Useful for confirming that an *assembly* does not rely on its
        origin coordinate system to remain intact.

        For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes
        along each of the :math:`XYZ` axes.
        Positioning it randomly by setting its ``world_coords`` shows that each
        box is always positioned orthogonally to the other two.

        .. doctest::

            from cqparts_misc.basic.indicators import CoordSysIndicator
            from cqparts.display import display
            from cqparts.utils import CoordSystem

            cs = CoordSysIndicator()
            cs.world_coords = CoordSystem.random()

            display(cs)  # doctest: +SKIP

        :param span: origin of return will be :math:`\pm span` per axis
        :param seed: if supplied, return is psudorandom (repeatable)
        :type seed: hashable object
        :return: randomized coordinate system
        :rtype: :class:`CoordSystem`
        """
        if seed is not None:
            random.seed(seed)

        def rand_vect(min, max):
            return (
                random.uniform(min, max),
                random.uniform(min, max),
                random.uniform(min, max),
            )

        while True:
            try:
                return cls(
                    origin=rand_vect(-span, span),
                    xDir=rand_vect(-1, 1),
                    normal=rand_vect(-1, 1),
                )
            except RuntimeError:  # Base.FreeCADError inherits from RuntimeError
                # Raised if xDir & normal vectors are parallel.
                # (the chance is very low, but it could happen)
                continue


Instruction:
How would you code a function in Python 3 to
convert a function to a cqparts. Part instance.

Response:
def as_part(func):
    """
    Converts a function to a :class:`Part <cqparts.Part>` instance.

    So the conventionally defined *part*::

        import cadquery
        from cqparts import Part
        from cqparts.params import Float

        class Box(Part):
            x = Float(1)
            y = Float(2)
            z = Float(4)
            def make(self):
                return cadquery.Workplane('XY').box(self.x, self.y, self.z)

        box = Box(x=6, y=3, z=1)

    May also be written as::

        import cadquery
        from cqparts.utils.wrappers import as_part

        @as_part
        def make_box(x=1, y=2, z=4):
            return cadquery.Workplane('XY').box(x, y, z)

        box = make_box(x=6, y=3, z=1)

    In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance.
    """
    from .. import Part

    def inner(*args, **kwargs):
        part_class = type(func.__name__, (Part,), {
            'make': lambda self: func(*args, **kwargs),
        })
        return part_class()
    inner.__doc__ = func.__doc__
    return inner


Instruction:
How would you explain what the following Python 3 function does
def find(self, *args, **kwargs):
        result = self.search(*args, **kwargs)

        if len(result) == 0:
            raise SearchNoneFoundError("nothing found")
        elif len(result) > 1:
            raise SearchMultipleFoundError("more than one result found")

        return result[0]

Response: Performs the same action as : meth : search but asserts a single result.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add(self, id, obj, criteria={}, force=False, _check_id=True):
        # Verify component
        if not isinstance(obj, Component):
            raise TypeError("can only add(%r), component is a %r" % (
                Component, type(obj)
            ))

        # Serialize object
        obj_data = obj.serialize()

        # Add to database
        q = tinydb.Query()
        if (force or _check_id) and self.items.count(q.id == id):
            if force:
                self.items.remove(q.id == id)
            else:
                raise ValueError("entry with id '%s' already exists" % (id))

        index = self.items.insert({
            'id': id,  # must be unique
            'criteria': criteria,
            'obj': obj_data,
        })

        return index

Response: Add a new entry to the catalogue.


Instruction:
Can you generate the documentation for the following Python 3 function
def start_point(self):
        edge = self.result.wire().val().Edges()[0]
        return edge.Vertices()[0].Center()

Response: Start vertex of effect


Instruction:
Write a Python 3 script to
return the coordinate system at the start of the effect.

Response:
def start_coordsys(self):
        """
        Coordinate system at start of effect.

        All axes are parallel to the original vector evaluation location, with
        the origin moved to this effect's start point.

        :return: coordinate system at start of effect
        :rtype: :class:`CoordSys`
        """
        coordsys = copy(self.location)
        coordsys.origin = self.start_point
        return coordsys


Instruction:
Given the following Python 3 function, write the documentation
def end_coordsys(self):
        coordsys = copy(self.location)
        coordsys.origin = self.end_point
        return coordsys

Response: Returns the coordinate system at the end of the effect.


Instruction:
How would you code a function in Python 3 to
return the planar distance of origin from self. location along Z axis

Response:
def origin_displacement(self):
        """
        planar distance of start point from self.location along :math:`-Z` axis
        """
        return self.start_point.sub(self.location.origin).dot(-self.location.zDir)


Instruction:
Make a summary of the following Python 3 code
def max_effect_length(self):
        # Method: using each solid's bounding box:
        #   - get vector from start to bounding box center
        #   - get vector from bounding box center to any corner
        #   - add the length of both vectors
        #   - return the maximum of these from all solids
        def max_length_iter():
            for part in self.parts:
                if part.local_obj.findSolid():
                    bb = part.local_obj.findSolid().BoundingBox()
                    yield abs(bb.center - self.location.origin) + (bb.DiagonalLength / 2)
        try:
            return max(max_length_iter())
        except ValueError as e:
            # if iter returns before yielding anything
            return 0

Response: Returns the maximum length of the longest possible effect vector.


Instruction:
Here you have a function in Python 3, explain what it does
def perform_evaluation(self):
        # Create effect vector (with max length)
        if not self.max_effect_length:
            # no effect is possible, return an empty list
            return []
        edge = cadquery.Edge.makeLine(
            self.location.origin,
            self.location.origin + (self.location.zDir * -(self.max_effect_length + 1))  # +1 to avoid rounding errors
        )
        wire = cadquery.Wire.assembleEdges([edge])
        wp = cadquery.Workplane('XY').newObject([wire])

        effect_list = []  # list of self.effect_class instances
        for part in self.parts:
            solid = part.world_obj.translate((0, 0, 0))
            intersection = solid.intersect(copy(wp))
            effect = self.effect_class(
                location=self.location,
                part=part,
                result=intersection,
            )
            if effect:
                effect_list.append(effect)

        return sorted(effect_list)

Response: Compute the effect vector for the given set of parts and return the list of effects on the given parts.


Instruction:
Can you implement a function in Python 3 that
displays the given component based on the environment it s run from.

Response:
def display(component, **kwargs):
    """
    Display the given component based on the environment it's run from.
    See :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>`
    documentation for more details.

    :param component: component to display
    :type component: :class:`Component <cqparts.Component>`

    Additional parameters may be used by the chosen
    :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>`
    """

    disp_env = get_display_environment()
    if disp_env is None:
        raise LookupError('valid display environment could not be found')

    disp_env.display(component, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def render_props(**kwargs):
    # Pop named args
    template = kwargs.pop('template', 'default')
    doc = kwargs.pop('doc', "render properties")

    params = {}

    # Template parameters
    if template in TEMPLATE:
        params.update(TEMPLATE[template])

    # override template with any additional params
    params.update(kwargs)

    # return parameter instance
    return RenderParam(params, doc=doc)

Response: Return a valid property for cleaner referencing in cqparts. Part <cqparts. Part >


Instruction:
Implement a Python 3 function for
applying the indentation into a workplane.

Response:
def apply(self, workplane, world_coords=CoordSystem()):
        """
        Application of screwdrive indentation into a workplane
        (centred on the given world coordinates).

        :param workplane: workplane with solid to alter
        :type workplane: :class:`cadquery.Workplane`
        :param world_coords: coorindate system relative to ``workplane`` to move
                             cutter before it's cut from the ``workplane``
        :type world_coords: :class:`CoordSystem`
        """

        self.world_coords = world_coords
        return workplane.cut(self.world_obj)


Instruction:
Write a Python 3 script for
adding the parameter lines to the list of documentation lines that are used in the parametric object.

Response:
def add_parametric_object_params(prepend=False, hide_private=True):
    """
    Add :class:`ParametricObject <cqparts.params.ParametricObject>` parameters
    in a list to the *docstring*.

    This is only intended to be used with *sphinx autodoc*.

    In your *sphinx* ``config.py`` file::

        from cqparts.utils.sphinx import add_parametric_object_params
        def setup(app):
            app.connect("autodoc-process-docstring", add_parametric_object_params())

    Then, when documenting your :class:`Part <cqparts.Part>` or
    :class:`Assembly <cqparts.Assembly>` the
    :class:`ParametricObject <cqparts.params.ParametricObject>` parameters
    will also be documented in the output.

    :param prepend: if True, parameters are added to the beginning of the *docstring*.
                    otherwise, they're appended at the end.
    :type prepend: :class:`bool`
    :param hide_private: if True, parameters with a ``_`` prefix are not documented.
    :type hide_private: :class:`bool`
    """

    from ..params import ParametricObject

    def param_lines(app, obj):
        params = obj.class_params(hidden=(not hide_private))

        # Header
        doc_lines = []
        if params:  # only add a header if it's relevant
            doc_lines += [
                ":class:`ParametricObject <cqparts.params.ParametricObject>` constructor parameters:",
                "",
            ]

        for (name, param) in sorted(params.items(), key=lambda x: x[0]):  # sort by name
            doc_lines.append(':param {name}: {doc}'.format(
                name=name, doc=param._param(),
            ))
            doc_lines.append(':type {name}: {doc}'.format(
                name=name, doc=param._type(),
            ))

        return doc_lines

    # Conditions for running above `param_lines` function (in order)
    conditions = [  # (all conditions must be met)
        lambda o: type(o) == type,
        lambda o: o is not ParametricObject,
        lambda o: issubclass(o, ParametricObject),
    ]

    def callback(app, what, name, obj, options, lines):
        # sphinx callback
        # (this method is what actually gets sent to the sphinx runtime)
        if all(c(obj) for c in conditions):
            new_lines = param_lines(app, obj)
            _add_lines(lines, new_lines, prepend=prepend)

    return callback


Instruction:
Write a Python 3 function for
adding the search index criteria to the output.

Response:
def add_search_index_criteria(prepend=False):
    """
    Add the search criteria used when calling :meth:`register() <cqparts.search.register>`
    on a :class:`Component <cqparts.Component>` as a table to the *docstring*.

    This is only intended to be used with *sphinx autodoc*.

    In your *sphinx* ``config.py`` file::

        from cqparts.utils.sphinx import add_search_index_criteria
        def setup(app):
            app.connect("autodoc-process-docstring", add_search_index_criteria())

    Then, when documenting your :class:`Part <cqparts.Part>` or
    :class:`Assembly <cqparts.Assembly>` the
    search criteria will also be documented in the output.

    :param prepend: if True, table is added to the beginning of the *docstring*.
                    otherwise, it's appended at the end.
    :type prepend: :class:`bool`
    """

    from ..search import class_criteria
    from .. import Component

    COLUMN_INFO = [
        # (<title>, <width>, <method>),
        ('Key', 50, lambda k, v: "``%s``" % k),
        ('Value', 10, lambda k, v: ', '.join("``%s``" % w for w in v)),
    ]  # note: last column width is irrelevant

    def param_lines(app, obj):
        doc_lines = []

        criteria = class_criteria.get(obj, {})
        row_seperator = ' '.join(('=' * w) for (_, w, _) in COLUMN_INFO)

        # Header
        if criteria:  # only add a header if it's relevant
            doc_lines += [
                "**Search Criteria:**",
                "",
                "This object can be found with :meth:`find() <cqparts.search.find>` ",
                "and :meth:`search() <cqparts.search.search>` using the following ",
                "search criteria.",
                "",
                row_seperator,
                ' '.join((("%%-%is" % w) % t) for (t, w, _) in COLUMN_INFO),
                row_seperator,
            ]

        # Add criteria
        for (key, value) in sorted(criteria.items(), key=lambda x: x[0]):
            doc_lines.append(' '.join(
                ("%%-%is" % w) % m(key, value)
                for (_, w, m) in COLUMN_INFO
            ))

        # Footer
        if criteria:
            doc_lines += [
                row_seperator,
                "",
            ]

        return doc_lines

    # Conditions for running above `param_lines` function (in order)
    conditions = [  # (all conditions must be met)
        lambda o: type(o) == type,
        lambda o: o is not Component,
        lambda o: issubclass(o, Component),
    ]

    def callback(app, what, name, obj, options, lines):
        # sphinx callback
        # (this method is what actually gets sent to the sphinx runtime)
        if all(c(obj) for c in conditions):
            new_lines = param_lines(app, obj)
            _add_lines(lines, new_lines, prepend=prepend)

    return callback


Instruction:
Write a Python 3 script for
iterating through list and indicate which item is the last

Response:
def indicate_last(items):
    """
    iterate through list and indicate which item is the last, intended to
    assist tree displays of hierarchical content.

    :return: yielding (<bool>, <item>) where bool is True only on last entry
    :rtype: generator
    """
    last_index = len(items) - 1
    for (i, item) in enumerate(items):
        yield (i == last_index, item)


Instruction:
Can you implement a function in Python 3 that
changes working directory within a context

Response:
def working_dir(path):
    """
    Change working directory within a context::

        >>> import os
        >>> from cqparts.utils import working_dir

        >>> print(os.getcwd())
        /home/myuser/temp

        >>> with working_dir('..'):
        ...     print(os.getcwd())
        ...
        /home/myuser

    :param path: working path to use while in context
    :type path: :class:`str`
    """
    initial_path = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(initial_path)


Instruction:
Here you have a function in Python 3, explain what it does
def profile_to_cross_section(profile, lefthand=False, start_count=1, min_vertices=20):
    # verify parameter(s)
    if not isinstance(profile, cadquery.Workplane):
        raise TypeError("profile %r must be a %s instance" % (profile, cadquery.Workplane))
    if not isinstance(min_vertices, (int, list, tuple)):
        raise TypeError("min_vertices %r must be an int, list, or tuple" % (min_vertices))

    # get wire from Workplane
    wire = profile.val()  # cadquery.Wire
    if not isinstance(wire, cadquery.Wire):
        raise TypeError("a valid profile Wire type could not be found in the given Workplane")

    profile_bb = wire.BoundingBox()
    pitch = profile_bb.zmax - profile_bb.zmin
    lead = pitch * start_count

    # determine vertices count per edge
    edges = wire.Edges()
    vertices_count = None
    if isinstance(min_vertices, int):
        # evenly spread vertices count along profile wire
        # (weighted by the edge's length)
        vertices_count = [
            int(ceil(round(e.Length() / wire.Length(), 7) * min_vertices))
            for e in edges
        ]
        # rounded for desired contrived results
        # (trade-off: an error of 1 is of no great consequence)
    else:
        # min_vertices is defined per edge (already what we want)
        if len(min_vertices) != len(edges):
            raise ValueError(
                "min_vertices list size does not match number of profile edges: "
                "len(%r) != %i" % (min_vertices, len(edges))
            )
        vertices_count = min_vertices

    # Utilities for building cross-section
    def get_xz(vertex):
        if isinstance(vertex, cadquery.Vector):
            vertex = vertex.wrapped  # TODO: remove this, it's messy
        # where isinstance(vertex, FreeCAD.Base.Vector)
        return (vertex.x, vertex.z)

    def cart2polar(x, z, z_offset=0):
        """
        Convert cartesian coordinates to polar coordinates.
        Uses thread's lead height to give full 360deg translation.
        """
        radius = x
        angle = ((z + z_offset) / lead) * (2 * pi)  # radians
        if not lefthand:
            angle = -angle
        return (radius, angle)

    def transform(vertex, z_offset=0):
        # where isinstance(vertex, FreeCAD.Base.Vector)
        """
        Transform profile vertex on the XZ plane to it's equivalent on
        the cross-section's XY plane
        """
        (radius, angle) = cart2polar(*get_xz(vertex), z_offset=z_offset)
        return (radius * cos(angle), radius * sin(angle))

    # Conversion methods
    def apply_spline(wp, edge, vert_count, z_offset=0):
        """
        Trace along edge and create a spline from the transformed verteces.
        """
        curve = edge.wrapped.Curve  # FreeCADPart.Geom* (depending on type)
        if edge.geomType() == 'CIRCLE':
            iter_dist = edge.wrapped.ParameterRange[1] / vert_count
        else:
            iter_dist = edge.Length() / vert_count
        points = []
        for j in range(vert_count):
            dist = (j + 1) * iter_dist
            vert = curve.value(dist)
            points.append(transform(vert, z_offset))
        return wp.spline(points)

    def apply_arc(wp, edge, z_offset=0):
        """
        Create an arc using edge's midpoint and endpoint.
        Only intended for use for vertical lines on the given profile.
        """
        return wp.threePointArc(
            point1=transform(edge.wrapped.valueAt(edge.Length() / 2), z_offset),
            point2=transform(edge.wrapped.valueAt(edge.Length()), z_offset),
        )

    def apply_radial_line(wp, edge, z_offset=0):
        """
        Create a straight radial line
        """
        return wp.lineTo(*transform(edge.endPoint(), z_offset))

    # Build cross-section
    start_v = edges[0].startPoint().wrapped
    cross_section = cadquery.Workplane("XY") \
        .moveTo(*transform(start_v))

    for i in range(start_count):
        z_offset = i * pitch
        for (j, edge) in enumerate(wire.Edges()):
            # where: isinstance(edge, cadquery.Edge)
            if (edge.geomType() == 'LINE') and (edge.startPoint().x == edge.endPoint().x):
                # edge is a vertical line, plot a circular arc
                cross_section = apply_arc(cross_section, edge, z_offset)
            elif (edge.geomType() == 'LINE') and (edge.startPoint().z == edge.endPoint().z):
                # edge is a horizontal line, plot a radial line
                cross_section = apply_radial_line(cross_section, edge, z_offset)
            else:
                # create bezier spline along transformed points (default)
                cross_section = apply_spline(cross_section, edge, vertices_count[j], z_offset)

    return cross_section.close()

Response: r Converts a thread profile to a cross - section.


Instruction:
Can you tell what is the following Python 3 function doing
def profile(self):
        if self._profile is None:
            self._profile = self.build_profile()
        return self._profile

Response: Return the profile of the user.


Instruction:
Make a summary of the following Python 3 code
def get_radii(self):
        bb = self.profile.val().BoundingBox()
        return (bb.xmin, bb.xmax)

Response: Get the inner and outer radii of the thread.


Instruction:
Can you generate the documentation for the following Python 3 function
def make_simple(self):
        (inner_radius, outer_radius) = self.get_radii()
        radius = (inner_radius + outer_radius) / 2
        return cadquery.Workplane('XY') \
            .circle(radius).extrude(self.length)

Response: Return a simple cylinder with the thread s average radius & length.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def make_pilothole_cutter(self):
        # get pilothole ratio
        #   note: not done in .initialize_parameters() because this would cause
        #   the thread's profile to be created at initialisation (by default).
        pilothole_radius = self.pilothole_radius
        if pilothole_radius is None:
            (inner_radius, outer_radius) = self.get_radii()
            pilothole_radius = inner_radius + self.pilothole_ratio * (outer_radius - inner_radius)

        return cadquery.Workplane('XY') \
            .circle(pilothole_radius) \
            .extrude(self.length)

Response: Make a solid to subtract from an interfacing solid to bore a pilot - hole.


Instruction:
Given the following Python 3 function, write the documentation
def components(self):
        if self._components is None:
            self.build(recursive=False)
        return self._components

Response:
Returns full dict of named component instances after
        a successful build.


Instruction:
Can you create a Python 3 function that
returns full list of constraints after a successful build.

Response:
def constraints(self):
        """
        Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after
        a successful :meth:`build`

        :return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances
        :rtype: :class:`list`

        For more information read about the :ref:`parts_assembly-build-cycle` .
        """
        if self._constraints is None:
            self.build(recursive=False)
        return self._constraints


Instruction:
Make a summary of the following Python 3 code
def solve(self):
        if self.world_coords is None:
            log.warning("solving for Assembly without world coordinates set: %r", self)

        for (component, world_coords) in solver(self.constraints, self.world_coords):
            component.world_coords = world_coords

Response: Solve the Assembly for the given set of world coordinates.


Instruction:
Make a summary of the following Python 3 code
def verify_components(components):
        # verify returned type from user-defined function
        if not isinstance(components, dict):
            raise ValueError(
                "invalid type returned by make_components(): %r (must be a dict)" % components
            )

        # check types for (name, component) pairs in dict
        for (name, component) in components.items():
            # name is a string
            if not isinstance(name, str):
                raise ValueError((
                    "invalid name from make_components(): (%r, %r) "
                    "(must be a (str, Component))"
                ) % (name, component))

            # component is a Component instance
            if not isinstance(component, Component):
                raise ValueError((
                    "invalid component type from make_components(): (%r, %r) "
                    "(must be a (str, Component))"
                ) % (name, component))

            # check component name validity
            invalid_chars = set(name) - VALID_NAME_CHARS
            if invalid_chars:
                raise ValueError(
                    "component name {!r} invalid; cannot include {!r}".format(
                        name, invalid_chars
                    )
                )

Response: Verify that the components returned from a function are valid.


Instruction:
Can you tell what is the following Python 3 function doing
def verify_constraints(constraints):
        # verify return is a list
        if not isinstance(constraints, list):
            raise ValueError(
                "invalid type returned by make_constraints: %r (must be a list)" % constraints
            )

        # verify each list element is a Constraint instance
        for constraint in constraints:
            if not isinstance(constraint, Constraint):
                raise ValueError(
                    "invalid constraint type: %r (must be a Constriant)" % constraint
                )

Response: Verify that the return value returned from the make_constraints method is a list of constraints. Raises ValueError if verification fails.


Instruction:
Explain what the following Python 3 code does
def build(self, recursive=True):

        # initialize values
        self._components = {}
        self._constraints = []

        def genwrap(obj, name, iter_type=None):
            # Force obj to act like a generator.
            # this wrapper will always yield at least once.
            if isinstance(obj, GeneratorType):
                for i in obj:
                    if (iter_type is not None) and (not isinstance(i, iter_type)):
                        raise TypeError("%s must yield a %r" % (name, iter_type))
                    yield i
            else:
                if (iter_type is not None) and (not isinstance(obj, iter_type)):
                    raise TypeError("%s must return a %r" % (name, iter_type))
                yield obj

        # Make Components
        components_iter = genwrap(self.make_components(), "make_components", dict)
        new_components = next(components_iter)
        self.verify_components(new_components)
        self._components.update(new_components)

        # Make Constraints
        constraints_iter = genwrap(self.make_constraints(), "make_components", list)
        new_constraints = next(constraints_iter)
        self.verify_constraints(new_constraints)
        self._constraints += new_constraints

        # Run solver : sets components' world coordinates
        self.solve()

        # Make Alterations
        alterations_iter = genwrap(self.make_alterations(), "make_alterations")
        next(alterations_iter)  # return value is ignored

        while True:
            (s1, s2, s3) = (True, True, True)  # stages
            # Make Components
            new_components = None
            try:
                new_components = next(components_iter)
                self.verify_components(new_components)
                self._components.update(new_components)
            except StopIteration:
                s1 = False

            # Make Constraints
            new_constraints = None
            try:
                new_constraints = next(constraints_iter)
                self.verify_constraints(new_constraints)
                self._constraints += new_constraints
            except StopIteration:
                s2 = False

            # Run solver : sets components' world coordinates
            if new_components or new_constraints:
                self.solve()

            # Make Alterations
            try:
                next(alterations_iter)  # return value is ignored
            except StopIteration:
                s3 = False

            # end loop when all iters are finished
            if not any((s1, s2, s3)):
                break

        if recursive:
            for (name, component) in self._components.items():
                component.build(recursive=recursive)

Response: Builds an assembly buffer of the current set of components and constraints.


Instruction:
Can you implement a function in Python 3 that
finds an entry in the Assembly by a list of keys.

Response:
def find(self, keys, _index=0):
        """
        :param keys: key path. ``'a.b'`` is equivalent to ``['a', 'b']``
        :type keys: :class:`str` or :class:`list`

        Find a nested :class:`Component` by a "`.`" separated list of names.
        for example::

            >>> motor.find('bearing.outer_ring')

        would return the Part instance of the motor bearing's outer ring.

        ::

            >>> bearing = motor.find('bearing')
            >>> ring = bearing.find('inner_ring')  # equivalent of 'bearing.inner_ring'

        the above code does much the same thing, ``bearing`` is an :class:`Assembly`,
        and ``ring`` is a :class:`Part`.

        .. note::

            For a key path of ``a.b.c`` the ``c`` key can referernce any
            :class:`Component` type.

            Everything prior (in this case ``a`` and ``b``) must reference an
            :class:`Assembly`.
        """

        if isinstance(keys, six.string_types):
            keys = re.split(r'[\.-]+', keys)
        if _index >= len(keys):
            return self

        key = keys[_index]
        if key in self.components:
            component = self.components[key]
            if isinstance(component, Assembly):
                return component.find(keys, _index=(_index + 1))
            elif _index == len(keys) - 1:
                # this is the last search key; component is a leaf, return it
                return component
            else:
                raise AssemblyFindError(
                    "could not find '%s' (invalid type at [%i]: %r)" % (
                        '.'.join(keys), _index, component
                    )
                )
        else:
            raise AssemblyFindError(
                "could not find '%s', '%s' is not a component of %r" % (
                    '.'.join(keys), key, self
                )
            )


Instruction:
Write a Python 3 function for
getting a neat relative path to files relative to the CWD

Response:
def _relative_path_to(path_list, filename):
    """Get a neat relative path to files relative to the CWD"""
    return os.path.join(
        os.path.relpath(os.path.join(*path_list), os.getcwd()),
        filename
    )


Instruction:
Write a Python 3 script for
building a single tooth template for the current site.

Response:
def _make_tooth_template(self):
        """
        Builds a single tooth including the cylinder with tooth faces
        tangential to its circumference.
        """
        # parameters
        period_arc = (2 * pi) / self.tooth_count
        tooth_arc = period_arc * self.spacing_ratio  # the arc between faces at effective_radius
        outer_radius = self.effective_radius + (self.tooth_height / 2)
        face_angle_rad = radians(self.face_angle)

        # cartesian isosceles trapezoid dimensions
        side_angle = face_angle_rad - (tooth_arc / 2)
        side_tangent_radius = sin(face_angle_rad) * self.effective_radius
        extra_side_angle = side_angle + acos(side_tangent_radius / outer_radius)

        tooth = cadquery.Workplane('XY', origin=(0, 0, -self.width / 2)) \
            .moveTo(
                side_tangent_radius * cos(side_angle),
                side_tangent_radius * sin(side_angle)
            )
        opposite_point = (
            -side_tangent_radius * cos(side_angle),
            side_tangent_radius * sin(side_angle)
        )
        if self.face_angle:
            tooth = tooth.lineTo(*opposite_point)
            #tooth = tooth.threePointArc(
            #    (0, -side_tangent_radius),
            #    opposite_point
            #)
        tooth = tooth.lineTo(
                -cos(extra_side_angle) * outer_radius,
                sin(extra_side_angle) * outer_radius
            )
        opposite_point = (
            cos(extra_side_angle) * outer_radius,
            sin(extra_side_angle) * outer_radius
        )
        if self.flat_top:
            tooth = tooth.lineTo(*opposite_point)
        else:
            tooth = tooth.threePointArc((0, outer_radius), opposite_point)
        tooth = tooth.close().extrude(self.width)

        return tooth


Instruction:
Can you tell what is the following Python 3 function doing
def get_mate_center(self, angle=0):
        return Mate(self, CoordSystem.from_plane(
            cadquery.Plane(
                origin=(0, 0, self.width / 2),
                xDir=(1, 0, 0),
                normal=(0, 0, 1),
            ).rotated((0, 0, angle))  # rotate about z-axis
        ))

Response: Return a Mate at ring s center rotated about z - axis.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.):

        min_arc = asin(((ball_diam + min_gap) / 2) / rolling_radius) * 2
        return int((2 * pi) / min_arc)

Response: Returns the maximum number of balls given the rolling_radius and ball_diam.


Instruction:
Make a summary of the following Python 3 code
def display_callback(self, component, **kwargs):
        if type(self) is DisplayEnvironment:
            raise RuntimeError(
                ("%r is not a functional display environment, " % (type(self))) +
                "it's meant to be inherited by an implemented environment"
            )
        raise NotImplementedError(
            "display_callback function not overridden by %r" % (type(self))
        )

Response: Display given component in this environment.


Instruction:
Can you tell what is the following Python 3 function doing
def add_vertex(self, x, y, z):
        self.vert_data.write(
            struct.pack('<f', x) +
            struct.pack('<f', y) +
            struct.pack('<f', z)
        )

        # retain min/max values
        self.vert_min = _list3_min(self.vert_min, (x, y, z))
        self.vert_max = _list3_max(self.vert_max, (x, y, z))

Response: Add a vertex to the internal buffer.


Instruction:
Given the following Python 3 function, write the documentation
def add_poly_index(self, i, j, k):
        self.idx_data.write(
            struct.pack(self.idx_fmt, i) +
            struct.pack(self.idx_fmt, j) +
            struct.pack(self.idx_fmt, k)
        )

Response: Add 3 - Scalar of uint to the idx_data buffer.


Instruction:
Write a Python 3 script to
iterate through chunks of the vertices and indices buffers seamlessly.

Response:
def buffer_iter(self, block_size=1024):
        """
        Iterate through chunks of the vertices, and indices buffers seamlessly.

        .. note::

            To see a usage example, look at the :class:`ShapeBuffer` description.
        """
        streams = (
            self.vert_data,
            self.idx_data,
        )

        # Chain streams seamlessly
        for stream in streams:
            stream.seek(0)
            while True:
                chunk = stream.read(block_size)
                if chunk:
                    yield chunk
                else:
                    break


Instruction:
Can you write a function in Python 3 where it
reads the key - value pairs from the buffer.

Response:
def read(self):
        """
        Read buffer out as a single stream.

        .. warning::

            Avoid using this function!

            **Why?** This is a *convenience* function; it doesn't encourage good
            memory management.

            All memory required for a mesh is duplicated, and returned as a
            single :class:`str`. So at best, using this function will double
            the memory required for a single model.

            **Instead:** Wherever possible, please use :meth:`buffer_iter`.
        """
        buffer = BytesIO()
        for chunk in self.buffer_iter():
            log.debug('buffer.write(%r)', chunk)
            buffer.write(chunk)
        buffer.seek(0)
        return buffer.read()


Instruction:
Can you tell what is the following Python 3 function doing
def world_coords(self):
        if self.component is None:
            # no component, world == local
            return copy(self.local_coords)
        else:
            cmp_origin = self.component.world_coords
            if cmp_origin is None:
                raise ValueError(
                    "mate's component does not have world coordinates; "
                    "cannot get mate's world coordinates"
                )

            return cmp_origin + self.local_coords

Response: world coordinates of mate.


Instruction:
Can you implement a function in Python 3 that
creates and return a simple representation of the current export entry.

Response:
def make_simple(self):
        """
        Create and return *simplified* solid part.

        The simplified representation of a ``Part`` is to lower the export
        quality of an ``Assembly`` or ``Part`` for rendering.

        Overriding this is optional, but highly recommended.

        The default behaviour returns the full complexity object's bounding box.
        But to do this, theh full complexity object must be generated first.

        There are 2 main problems with this:

        #. building the full complexity part is not efficient.
        #. a bounding box may not be a good representation of the part.

        **Bolts**

        A good example of this is a bolt.

        * building a bolt's thread is not a trivial task;
          it can take some time to generate.
        * a box is not a good visual representation of a bolt

        So for the ``Fastener`` parts, all ``make_simple`` methods are overridden
        to provide 2 cylinders, one for the bolt's head, and another for the thread.
        """
        complex_obj = self.make()
        bb = complex_obj.findSolid().BoundingBox()
        simple_obj = cadquery.Workplane('XY', origin=(bb.xmin, bb.ymin, bb.zmin)) \
            .box(bb.xlen, bb.ylen, bb.zlen, centered=(False, False, False))
        return simple_obj


Instruction:
Write a Python 3 script for
returning the local object of the current object.

Response:
def local_obj(self):
        """
        Buffered result of :meth:`make` which is (probably) a
        :class:`cadquery.Workplane` instance. If ``_simple`` is ``True``, then
        :meth:`make_simple` is returned instead.

        .. note::
            This is usually the correct way to get your part's object
            for rendering, exporting, or measuring.

            Only call :meth:`cqparts.Part.make` directly if you explicitly intend
            to re-generate the model from scratch, then dispose of it.
        """
        if self._local_obj is None:
            # Simplified or Complex
            if self._simple:
                value = self.make_simple()
            else:
                value = self.make()
            # Verify type
            if not isinstance(value, cadquery.CQ):
                raise MakeError("invalid object type returned by make(): %r" % value)
            # Buffer object
            self._local_obj = value
        return self._local_obj


Instruction:
Here you have a function in Python 3, explain what it does
def world_obj(self):
        if self._world_obj is None:
            local_obj = self.local_obj
            world_coords = self.world_coords
            if (local_obj is not None) and (world_coords is not None):
                # Copy local object, apply transform to move to its new home.
                self._world_obj = world_coords + local_obj
        return self._world_obj

Response: The world object in the current component.


Instruction:
Explain what the following Python 3 code does
def bounding_box(self):
        if self.world_coords:
            return self.world_obj.findSolid().BoundingBox()
        return self.local_obj.findSolid().BoundingBox()

Response: Generate a bounding box based on the full complexity part.


Instruction:
Explain what the following Python 3 code does
def make_cutter(self):
        # head
        obj = self.head.make_cutter()

        # neck
        if self.neck_length:
            # neck cut diameter (if thread is larger than the neck, thread must fit through)
            (inner_radius, outer_radius) = self.thread.get_radii()
            neck_cut_radius = max(outer_radius, self.neck_diam / 2)

            neck = cadquery.Workplane(
                'XY', origin=(0, 0, -self.neck_length)
            ).circle(neck_cut_radius).extrude(self.neck_length)
            obj = obj.union(neck)

        # thread (pilot hole)
        pilot_hole = self.thread.make_pilothole_cutter() \
            .translate((0, 0, -self.length))
        obj = obj.union(pilot_hole)

        return obj

Response: Makes a cutter for the current neck and thread.


Instruction:
Can you create a Python 3 function that
gets the cutout for the shaft

Response:
def get_cutout(self, clearance=0):
        " get the cutout for the shaft"
        return cq.Workplane('XY', origin=(0, 0, 0)) \
            .circle((self.diam / 2) + clearance) \
            .extrude(10)


Instruction:
Explain what the following Python 3 code does
def mate_bottom(self):
        " connect to the bottom of the cup"
        return Mate(self, CoordSystem(\
            origin=(0, 0, -self.height),\
            xDir=(1, 0, 0),\
            normal=(0, 0, 1)))

Response: connect to the bottom of the cup


Instruction:
Can you tell what is the following Python 3 function doing
def as_parameter(nullable=True, strict=True):
    def decorator(cls):
        base_class = Parameter if nullable else NonNullParameter

        return type(cls.__name__, (base_class,), {
            # Preserve text for documentation
            '__name__': cls.__name__,
            '__doc__': cls.__doc__,
            '__module__': cls.__module__,
            # Sphinx doc type string
            '_doc_type': ":class:`{class_name} <{module}.{class_name}>`".format(
                class_name=cls.__name__, module=__name__
            ),
            #
            'type': lambda self, value: cls(**value)
        })

    return decorator

Response: A class decorator that creates a functional container class for a parametric object.


Instruction:
Write a Python 3 function for
returning valid base API path based on version given

Response:
def _construct_api_path(self, version):
        """Returns valid base API path based on version given

           The base API path for the URL is different depending on UniFi server version.
           Default returns correct path for latest known stable working versions.

        """

        V2_PATH = 'api/'
        V3_PATH = 'api/s/' + self.site_id + '/'

        if(version == 'v2'):
            return V2_PATH
        if(version == 'v3'):
            return V3_PATH
        if(version == 'v4'):
            return V3_PATH
        if(version == 'v5'):
            return V3_PATH
        else:
            return V2_PATH


Instruction:
Make a summary of the following Python 3 code
def get_alerts_unarchived(self):

        js = json.dumps({'_sort': '-time', 'archived': False})
        params = urllib.urlencode({'json': js})
        return self._read(self.api_url + 'list/alarm', params)

Response: Return a list of Alerts unarchived.


Instruction:
Can you tell what is the following Python 3 function doing
def get_statistics_24h(self, endtime):

        js = json.dumps(
            {'attrs': ["bytes", "num_sta", "time"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000})
        params = urllib.urlencode({'json': js})
        return self._read(self.api_url + 'stat/report/hourly.system', params)

Response: Return statistical data last 24h from time


Instruction:
Write a Python 3 script for
returning a list of all APs with significant information about each.

Response:
def get_aps(self):
        """Return a list of all AP:s, with significant information about each."""

        #Set test to 0 instead of NULL
        params = json.dumps({'_depth': 2, 'test': 0})
        return self._read(self.api_url + 'stat/device', params)


Instruction:
How would you code a function in Python 3 to
restart an access point by name.

Response:
def restart_ap_name(self, name):
        """Restart an access point (by name).

        Arguments:
            name -- the name address of the AP to restart.

        """

        if not name:
            raise APIError('%s is not a valid name' % str(name))
        for ap in self.get_aps():
            if ap.get('state', 0) == 1 and ap.get('name', None) == name:
                self.restart_ap(ap['mac'])


Instruction:
Implement a function in Python 3 to
ask controller to create a backup archive file

Response:
def create_backup(self):
        """Ask controller to create a backup archive file, response contains the path to the backup file.

        Warning: This process puts significant load on the controller may
                 render it partially unresponsive for other requests.
        """

        js = json.dumps({'cmd': 'backup'})
        params = urllib.urlencode({'json': js})
        answer = self._read(self.api_url + 'cmd/system', params)

        return answer[0].get('url')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_backup(self, target_file='unifi-backup.unf'):
        download_path = self.create_backup()

        opener = self.opener.open(self.url + download_path)
        unifi_archive = opener.read()

        backupfile = open(target_file, 'w')
        backupfile.write(unifi_archive)
        backupfile.close()

Response: Get a backup archive from a controller.


Instruction:
Can you generate the documentation for the following Python 3 function
def authorize_guest(self, guest_mac, minutes, up_bandwidth=None, down_bandwidth=None, byte_quota=None, ap_mac=None):
        cmd = 'authorize-guest'
        js = {'mac': guest_mac, 'minutes': minutes}

        if up_bandwidth:
            js['up'] = up_bandwidth
        if down_bandwidth:
            js['down'] = down_bandwidth
        if byte_quota:
            js['bytes'] = byte_quota
        if ap_mac and self.version != 'v2':
            js['ap_mac'] = ap_mac

        return self._run_command(cmd, params=js)

Response: This method is used to authorize a guest based on his MAC address.


Instruction:
Here you have a function in Python 3, explain what it does
def unauthorize_guest(self, guest_mac):
        cmd = 'unauthorize-guest'
        js = {'mac': guest_mac}

        return self._run_command(cmd, params=js)

Response: Unauthorize a guest based on his MAC address.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def download(gfile, wks_name=None, col_names=False, row_names=False,
            credentials=None, start_cell = 'A1'):
    """
        Download Google Spreadsheet and convert it to Pandas DataFrame

        :param gfile: path to Google Spreadsheet or gspread ID
        :param wks_name: worksheet name
        :param col_names: assing top row to column names for Pandas DataFrame
        :param row_names: assing left column to row names for Pandas DataFrame
        :param credentials: provide own credentials
        :param start_cell: specify where to start capturing of the DataFrame; default is A1
        :type gfile: str
        :type wks_name: str
        :type col_names: bool
        :type row_names: bool
        :type credentials: class 'oauth2client.client.OAuth2Credentials'
        :type start_cell: str
        :returns: Pandas DataFrame
        :rtype: class 'pandas.core.frame.DataFrame'

        :Example:

            >>> from df2gspread import gspread2df as g2d
            >>> df = g2d.download(gfile="1U-kSDyeD-...", col_names=True, row_names=True)
            >>> df
                   col1 col2
            field1    1    2
            field2    3    4
    """

    # access credentials
    credentials = get_credentials(credentials)
    # auth for gspread
    gc = gspread.authorize(credentials)

    try:
        # if gfile is file_id
        gc.open_by_key(gfile).__repr__()
        gfile_id = gfile
    except:
        # else look for file_id in drive
        gfile_id = get_file_id(credentials, gfile)

    if gfile_id is None:
        raise RuntimeError(
            "Trying to open non-existent or inaccessible spreadsheet")

    wks = get_worksheet(gc, gfile_id, wks_name)

    if wks is None:
        raise RuntimeError(
            "Trying to open non-existent or inaccessible worksheet")

    raw_data = wks.get_all_values()

    if not raw_data:
        raise ValueError(
            'Worksheet is empty or invalid.'
            )

    start_row_int, start_col_int = gspread.utils.a1_to_rowcol(start_cell)

    rows, cols  = np.shape(raw_data)
    if start_col_int > cols or (row_names and start_col_int + 1 > cols):
        raise RuntimeError(
            "Start col (%s) out of the table columns(%s)" % (start_col_int +
                                                            row_names, cols))

    if start_row_int > rows or (col_names and start_row_int + 1 > rows):
        raise RuntimeError(
            "Start row (%s) out of the table rows(%s)" % (start_row_int +
                                                            col_names, rows))

    raw_data = [row[start_col_int-1:] for row in raw_data[start_row_int-1:]]

    if row_names and col_names:
        row_names = [row[0] for row in raw_data[1:]]
        col_names = raw_data[0][1:]
        raw_data = [row[1:] for row in raw_data[1:]]
    elif row_names:
        row_names = [row[0] for row in raw_data]
        col_names = np.arange(len(raw_data[0]) - 1)
        raw_data = [row[1:] for row in raw_data]
    elif col_names:
        row_names = np.arange(len(raw_data) - 1)
        col_names = raw_data[0]
        raw_data = raw_data[1:]
    else:
        row_names = np.arange(len(raw_data))
        col_names = np.arange(len(raw_data[0]))

    df = pd.DataFrame([pd.Series(row) for row in raw_data], index=row_names)
    df.columns = col_names

    return df

Response: Download a file from Google Spreadsheet and convert it to Pandas DataFrame.


Instruction:
Create a Python 3 function for
returning valid credentials object.

Response:
def get_credentials(credentials=None, client_secret_file=CLIENT_SECRET_FILE, refresh_token=None):
    """Consistently returns valid credentials object.

    See Also:
        https://developers.google.com/drive/web/quickstart/python

    Args:
        client_secret_file (str): path to client secrets file, defaults to .gdrive_private
        refresh_token (str): path to a user provided refresh token that is already
            pre-authenticated
        credentials (`~oauth2client.client.OAuth2Credentials`, optional): handle direct
            input of credentials, which will check credentials for valid type and
            return them

    Returns:
        `~oauth2client.client.OAuth2Credentials`: google credentials object

    """

    # if the utility was provided credentials just return those
    if credentials:
        if _is_valid_credentials(credentials):
            # auth for gspread
            return credentials
        else:
            print("Invalid credentials supplied. Will generate from default token.")

    token = refresh_token or DEFAULT_TOKEN
    dir_name = os.path.dirname(DEFAULT_TOKEN)
    try:
        os.makedirs(dir_name)
    except OSError:
        if not os.path.isdir(dir_name):
            raise
    store = file.Storage(token)
    credentials = store.get()

    try:
        import argparse
        flags = argparse.ArgumentParser(
            parents=[tools.argparser]).parse_known_args()[0]
    except ImportError:
        flags = None
        logr.error(
            'Unable to parse oauth2client args; `pip install argparse`')

    if not credentials or credentials.invalid:

        flow = client.flow_from_clientsecrets(
            client_secret_file, SCOPES)
        flow.redirect_uri = client.OOB_CALLBACK_URN
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        logr.info('Storing credentials to ' + DEFAULT_TOKEN)

    return credentials