Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, nickname=None, **kwargs):
        url = self.url + 'hips/update'
        payload = {
            'membership': {
                'nickname': nickname,
            },
        }
        payload['membership'].update(kwargs)
        response = self.session.post(url, json=payload)
        return Member(self, self.group_id, **response.data)

Response: Update your own membership.


Instruction:
How would you explain what the following Python 3 function does
def remove(self, membership_id):
        path = '{}/remove'.format(membership_id)
        url = utils.urljoin(self.url, path)
        payload = {'membership_id': membership_id}
        response = self.session.post(url, json=payload)
        return response.ok

Response: Removes a member from the group.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def post(self, text=None, attachments=None, source_guid=None):
        return self.messages.create(text=text, attachments=attachments,
                                    source_guid=source_guid)

Response: Post a direct message to the user.


Instruction:
How would you implement a function in Python 3 that
adds the member to another group.

Response:
def add_to_group(self, group_id, nickname=None):
        """Add the member to another group.

        If a nickname is not provided the member's current nickname is used.

        :param str group_id: the group_id of a group
        :param str nickname: a new nickname
        :return: a membership request
        :rtype: :class:`MembershipRequest`
        """
        if nickname is None:
            nickname = self.nickname
        memberships = Memberships(self.manager.session, group_id=group_id)
        return memberships.add(nickname, user_id=self.user_id)


Instruction:
Can you generate the documentation for the following Python 3 function
def check_if_ready(self):
        try:
            results = self.manager.check(self.results_id)
        except exceptions.ResultsNotReady as e:
            self._is_ready = False
            self._not_ready_exception = e
        except exceptions.ResultsExpired as e:
            self._is_ready = True
            self._expired_exception = e
        else:
            failures = self.get_failed_requests(results)
            members = self.get_new_members(results)
            self.results = self.__class__.Results(list(members), list(failures))
            self._is_ready = True
            self._not_ready_exception = None

Response: Check for and fetch the results if ready.


Instruction:
How would you implement a function in Python 3 that
returns the requests that failed.

Response:
def get_failed_requests(self, results):
        """Return the requests that failed.

        :param results: the results of a membership request check
        :type results: :class:`list`
        :return: the failed requests
        :rtype: generator
        """
        data = {member['guid']: member for member in results}
        for request in self.requests:
            if request['guid'] not in data:
                yield request


Instruction:
Here you have a function in Python 3, explain what it does
def get_new_members(self, results):
        for member in results:
            guid = member.pop('guid')
            yield Member(self.manager, self.group_id, **member)
            member['guid'] = guid

Response: Return the newly added members.


Instruction:
Write a Python 3 function that can
return True if the results are ready.

Response:
def is_ready(self, check=True):
        """Return ``True`` if the results are ready.

        If you pass ``check=False``, no attempt is made to check again for
        results.

        :param bool check: whether to query for the results
        :return: ``True`` if the results are ready
        :rtype: bool
        """
        if not self._is_ready and check:
            self.check_if_ready()
        return self._is_ready


Instruction:
Write a Python 3 function for
polling the membership request for the result set to become ready.

Response:
def poll(self, timeout=30, interval=2):
        """Return the results when they become ready.

        :param int timeout: the maximum time to wait for the results
        :param float interval: the number of seconds between checks
        :return: the membership request result
        :rtype: :class:`~groupy.api.memberships.MembershipResult.Results`
        """
        time.sleep(interval)
        start = time.time()
        while time.time() - start < timeout and not self.is_ready():
            time.sleep(interval)
        return self.get()


Instruction:
Explain what the following Python 3 code does
def get(self):
        if self._expired_exception:
            raise self._expired_exception
        if self._not_ready_exception:
            raise self._not_ready_exception
        return self.results

Response: Return the results now.


Instruction:
How would you explain what the following Python 3 function does
def list(self, page=1, per_page=10, omit=None):
        return pagers.GroupList(self, self._raw_list, page=page,
                                per_page=per_page, omit=omit)

Response: List the groups by page.


Instruction:
Here you have a function in Python 3, explain what it does
def list_all(self, per_page=10, omit=None):
        return self.list(per_page=per_page, omit=omit).autopage()

Response:
List all groups.

        Since the order of groups is determined by recent activity, this is the
        recommended way to obtain a list of all groups. See
        :func:`~groupy.api.groups.Groups.list` for details about ``omit``.

        :param int per_page: number of groups per page
        :param int omit: a comma-separated list of fields to exclude
        :return: a list of groups
        :rtype: :class:`~groupy.pagers.GroupList`


Instruction:
Can you generate the documentation for the following Python 3 function
def list_former(self):
        url = utils.urljoin(self.url, 'former')
        response = self.session.get(url)
        return [Group(self, **group) for group in response.data]

Response: List all former groups.


Instruction:
How would you implement a function in Python 3 that
gets a single group by ID.

Response:
def get(self, id):
        """Get a single group by ID.

        :param str id: a group ID
        :return: a group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        url = utils.urljoin(self.url, id)
        response = self.session.get(url)
        return Group(self, **response.data)


Instruction:
Explain what the following Python 3 code does
def create(self, name, description=None, image_url=None, share=None, **kwargs):
        payload = {
            'name': name,
            'description': description,
            'image_url': image_url,
            'share': share,
        }
        payload.update(kwargs)
        response = self.session.post(self.url, json=payload)
        return Group(self, **response.data)

Response: Create a new group.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update(self, id, name=None, description=None, image_url=None,
               office_mode=None, share=None, **kwargs):
        """Update the details of a group.

        .. note::

            There are significant bugs in this endpoint!
            1. not providing ``name`` produces 400: "Topic can't be blank"
            2. not providing ``office_mode`` produces 500: "sql: Scan error on
            column index 14: sql/driver: couldn't convert <nil> (<nil>) into
            type bool"

            Note that these issues are "handled" automatically when calling
            update on a :class:`~groupy.api.groups.Group` object.

        :param str id: group ID
        :param str name: group name (140 characters maximum)
        :param str description: short description (255 characters maximum)
        :param str image_url: GroupMe image service URL
        :param bool office_mode: (undocumented)
        :param bool share: whether to generate a share URL
        :return: an updated group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        path = '{}/update'.format(id)
        url = utils.urljoin(self.url, path)
        payload = {
            'name': name,
            'description': description,
            'image_url': image_url,
            'office_mode': office_mode,
            'share': share,
        }
        payload.update(kwargs)
        response = self.session.post(url, json=payload)
        return Group(self, **response.data)

Response: Update the details of a group.


Instruction:
Write a Python 3 script for
destroying a group s ID .

Response:
def destroy(self, id):
        """Destroy a group.

        :param str id: a group ID
        :return: ``True`` if successful
        :rtype: bool
        """
        path = '{}/destroy'.format(id)
        url = utils.urljoin(self.url, path)
        response = self.session.post(url)
        return response.ok


Instruction:
Write a Python 3 function for
joining a group using a share token.

Response:
def join(self, group_id, share_token):
        """Join a group using a share token.

        :param str group_id: the group_id of a group
        :param str share_token: the share token
        :return: the group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        path = '{}/join/{}'.format(group_id, share_token)
        url = utils.urljoin(self.url, path)
        response = self.session.post(url)
        group = response.data['group']
        return Group(self, **group)


Instruction:
Here you have a function in Python 3, explain what it does
def rejoin(self, group_id):
        url = utils.urljoin(self.url, 'join')
        payload = {'group_id': group_id}
        response = self.session.post(url, json=payload)
        return Group(self, **response.data)

Response: Rejoin a former group.


Instruction:
Write a Python 3 function that can
change the owner of a group.

Response:
def change_owners(self, group_id, owner_id):
        """Change the owner of a group.

        .. note:: you must be the owner to change owners

        :param str group_id: the group_id of a group
        :param str owner_id: the ID of the new owner
        :return: the result
        :rtype: :class:`~groupy.api.groups.ChangeOwnersResult`
        """
        url = utils.urljoin(self.url, 'change_owners')
        payload = {
            'requests': [{
                'group_id': group_id,
                'owner_id': owner_id,
            }],
        }
        response = self.session.post(url, json=payload)
        result, = response.data['results']  # should be exactly one
        return ChangeOwnersResult(**result)


Instruction:
Create a Python 3 function for
updating the details of the group.

Response:
def update(self, name=None, description=None, image_url=None,
               office_mode=None, share=None, **kwargs):
        """Update the details of the group.

        :param str name: group name (140 characters maximum)
        :param str description: short description (255 characters maximum)
        :param str image_url: GroupMe image service URL
        :param bool office_mode: (undocumented)
        :param bool share: whether to generate a share URL
        :return: an updated group
        :rtype: :class:`~groupy.api.groups.Group`
        """
        # note we default to the current values for name and office_mode as a
        # work-around for issues with the group update endpoint
        if name is None:
            name = self.name
        if office_mode is None:
            office_mode = self.office_mode
        return self.manager.update(id=self.id, name=name, description=description,
                                   image_url=image_url, office_mode=office_mode,
                                   share=share, **kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def refresh_from_server(self):
        group = self.manager.get(id=self.id)
        self.__init__(self.manager, **group.data)

Response: Refresh the group from the server in place.


Instruction:
Write a Python 3 function for
creating a new bot in a particular group.

Response:
def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None,
                   **kwargs):
        """Create a new bot in a particular group.

        :param str name: bot name
        :param str avatar_url: the URL of an image to use as an avatar
        :param str callback_url: a POST-back URL for each new message
        :param bool dm_notification: whether to POST-back for direct messages?
        :return: the new bot
        :rtype: :class:`~groupy.api.bots.Bot`
        """
        return self._bots.create(name=name, group_id=self.group_id,
                                 avatar_url=avatar_url, callback_url=callback_url,
                                 dm_notification=dm_notification)


Instruction:
How would you explain what the following Python 3 function does
def get_membership(self):
        user_id = self._user.me['user_id']
        for member in self.members:
            if member.user_id == user_id:
                return member
        raise exceptions.MissingMembershipError(self.group_id, user_id)

Response:
Get your membership.

        Note that your membership may not exist. For example, you do not have
        a membership in a former group. Also, the group returned by the API
        when rejoining a former group does not contain your membership. You
        must call :func:`refresh_from_server` to update the list of members.

        :return: your membership in the group
        :rtype: :class:`~groupy.api.memberships.Member`
        :raises groupy.exceptions.MissingMembershipError: if your membership is
                not in the group data


Instruction:
Write a Python 3 function for
updating your own membership. Note that this fails on former groups. :param str nickname: new nickname :return: updated membership :rtype: :class:`~groupy.api.members.Member`

Response:
def update_membership(self, nickname=None, **kwargs):
        """Update your own membership.

        Note that this fails on former groups.

        :param str nickname: new nickname
        :return: updated membership
        :rtype: :class:`~groupy.api.members.Member`
        """
        return self.memberships.update(nickname=nickname, **kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def urljoin(base, path=None):
    # /foo/bar + baz makes /foo/bar/baz instead of /foo/baz
    if path is None:
        url = base
    else:
        if not base.endswith('/'):
            base += '/'
        url = urllib.parse.urljoin(base, str(path))
    return url

Response: Join a base url with a relative path.


Instruction:
How would you explain what the following Python 3 function does
def parse_share_url(share_url):
    *__, group_id, share_token = share_url.rstrip('/').split('/')
    return group_id, share_token

Response: Parse a group s share url.


Instruction:
Write a Python 3 script to
return an RFC 3339 timestamp.

Response:
def get_rfc3339(when):
    """Return an RFC 3339 timestamp.

    :param datetime.datetime when: a datetime in UTC
    :return: RFC 3339 timestamp
    :rtype: str
    """
    microseconds = format(when.microsecond, '04d')[:4]
    rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z'
    return when.strftime(rfc3339.format(microseconds))


Instruction:
Write a Python 3 script to
create a filter from keyword arguments.

Response:
def make_filter(**tests):
    """Create a filter from keyword arguments."""
    tests = [AttrTest(k, v) for k, v in tests.items()]
    return Filter(tests)


Instruction:
How would you code a function in Python 3 to
find exactly one match in the list of objects.

Response:
def find(self, objects):
        """Find exactly one match in the list of objects.

        :param objects: objects to filter
        :type objects: :class:`list`
        :return: the one matching object
        :raises groupy.exceptions.NoMatchesError: if no objects match
        :raises groupy.exceptions.MultipleMatchesError: if multiple objects match
        """
        matches = list(self.__call__(objects))
        if not matches:
            raise exceptions.NoMatchesError(objects, self.tests)
        elif len(matches) > 1:
            raise exceptions.MultipleMatchesError(objects, self.tests,
                                                  matches=matches)
        return matches[0]


Instruction:
How would you implement a function in Python 3 that
returns a list of your bots.

Response:
def list(self):
        """Return a list of bots.

        :return: all of your bots
        :rtype: :class:`list`
        """
        response = self.session.get(self.url)
        return [Bot(self, **bot) for bot in response.data]


Instruction:
Implement a Python 3 function for
creating a new bot in a particular group.

Response:
def create(self, name, group_id, avatar_url=None, callback_url=None,
               dm_notification=None, **kwargs):
        """Create a new bot in a particular group.

        :param str name: bot name
        :param str group_id: the group_id of a group
        :param str avatar_url: the URL of an image to use as an avatar
        :param str callback_url: a POST-back URL for each new message
        :param bool dm_notification: whether to POST-back for direct messages?
        :return: the new bot
        :rtype: :class:`~groupy.api.bots.Bot`
        """
        payload = {
            'bot': {
                'name': name,
                'group_id': group_id,
                'avatar_url': avatar_url,
                'callback_url': callback_url,
                'dm_notification': dm_notification,
            },
        }
        payload['bot'].update(kwargs)
        response = self.session.post(self.url, json=payload)
        bot = response.data['bot']
        return Bot(self, **bot)


Instruction:
Can you generate the documentation for the following Python 3 function
def post(self, bot_id, text, attachments=None):
        url = utils.urljoin(self.url, 'post')
        payload = dict(bot_id=bot_id, text=text)

        if attachments:
            payload['attachments'] = [a.to_json() for a in attachments]

        response = self.session.post(url, json=payload)
        return response.ok

Response: Post a new message as a bot to its room.


Instruction:
How would you implement a function in Python 3 that
destroys a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool

Response:
def destroy(self, bot_id):
        """Destroy a bot.

        :param str bot_id: the ID of the bot to destroy
        :return: ``True`` if successful
        :rtype: bool
        """
        url = utils.urljoin(self.url, 'destroy')
        payload = {'bot_id': bot_id}
        response = self.session.post(url, json=payload)
        return response.ok


Instruction:
Write a Python 3 script for
posting a message as the bot.

Response:
def post(self, text, attachments=None):
        """Post a message as the bot.

        :param str text: the text of the message
        :param attachments: a list of attachments
        :type attachments: :class:`list`
        :return: ``True`` if successful
        :rtype: bool
        """
        return self.manager.post(self.bot_id, text, attachments)


Instruction:
Can you create a Python 3 function that
flattens a nested sequence.

Response:
def flatten_until(is_leaf, xs):
    """
    Flatten a nested  sequence. A sequence could be a nested list of lists
    or tuples or a combination of both

    :param is_leaf: Predicate. Predicate to  determine whether an item
                    in the iterable `xs` is a leaf node or not.
    :param xs: Iterable. Nested lists or tuples
    :return: list.
    """

    def _flatten_until(items):
        if isinstance(Iterable, items) and not is_leaf(items):
            for item in items:
                for i in _flatten_until(item):
                    yield i
        else:
            yield items

    return list(_flatten_until(xs))


Instruction:
Implement a Python 3 function for
calling the function f by flipping the first two positional arguments

Response:
def flip(f):
    """
    Calls the function f by flipping the first two positional
    arguments
    """

    def wrapped(*args, **kwargs):
        return f(*flip_first_two(args), **kwargs)

    f_spec = make_func_curry_spec(f)

    return curry_by_spec(f_spec, wrapped)


Instruction:
Can you tell what is the following Python 3 function doing
def cachier(stale_after=None, next_time=False, pickle_reload=True,
            mongetter=None):
    """A persistent, stale-free memoization decorator.

    The positional and keyword arguments to the wrapped function must be
    hashable (i.e. Python's immutable built-in objects, not mutable
    containers). Also, notice that since objects which are instances of
    user-defined classes are hashable but all compare unequal (their hash
    value is their id), equal objects across different sessions will not yield
    identical keys.

    Arguments
    ---------
    stale_after (optional) : datetime.timedelta
        The time delta afterwhich a cached result is considered stale. Calls
        made after the result goes stale will trigger a recalculation of the
        result, but whether a stale or fresh result will be returned is
        determined by the optional next_time argument.
    next_time (optional) : bool
        If set to True, a stale result will be returned when finding one, not
        waiting for the calculation of the fresh result to return. Defaults to
        False.
    pickle_reload (optional) : bool
        If set to True, in-memory cache will be reloaded on each cache read,
        enabling different threads to share cache. Should be set to False for
        faster reads in single-thread programs. Defaults to True.
    mongetter (optional) : callable
        A callable that takes no arguments and returns a pymongo.Collection
        object with writing permissions. If unset a local pickle cache is used
        instead.
    """
    # print('Inside the wrapper maker')
    # print('mongetter={}'.format(mongetter))
    # print('stale_after={}'.format(stale_after))
    # print('next_time={}'.format(next_time))

    if mongetter:
        core = _MongoCore(mongetter, stale_after, next_time)
    else:
        core = _PickleCore(  # pylint: disable=R0204
            stale_after, next_time, pickle_reload)

    def _cachier_decorator(func):
        core.set_func(func)

        @wraps(func)
        def func_wrapper(*args, **kwds):  # pylint: disable=C0111,R0911
            # print('Inside general wrapper for {}.'.format(func.__name__))
            ignore_cache = kwds.pop('ignore_cache', False)
            overwrite_cache = kwds.pop('overwrite_cache', False)
            verbose_cache = kwds.pop('verbose_cache', False)
            _print = lambda x: None
            if verbose_cache:
                _print = print
            if ignore_cache:
                return func(*args, **kwds)
            key, entry = core.get_entry(args, kwds)
            if overwrite_cache:
                return _calc_entry(core, key, func, args, kwds)
            if entry is not None:  # pylint: disable=R0101
                _print('Entry found.')
                if entry.get('value', None) is not None:
                    _print('Cached result found.')
                    if stale_after:
                        now = datetime.datetime.now()
                        if now - entry['time'] > stale_after:
                            _print('But it is stale... :(')
                            if entry['being_calculated']:
                                if next_time:
                                    _print('Returning stale.')
                                    return entry['value']  # return stale val
                                _print('Already calc. Waiting on change.')
                                try:
                                    return core.wait_on_entry_calc(key)
                                except RecalculationNeeded:
                                    return _calc_entry(core, key, func, args, kwds)
                            if next_time:
                                _print('Async calc and return stale')
                                try:
                                    core.mark_entry_being_calculated(key)
                                    _get_executor().submit(
                                        _function_thread, core, key, func,
                                        args, kwds)
                                finally:
                                    core.mark_entry_not_calculated(key)
                                return entry['value']
                            _print('Calling decorated function and waiting')
                            return _calc_entry(core, key, func, args, kwds)
                    _print('And it is fresh!')
                    return entry['value']
                if entry['being_calculated']:
                    _print('No value but being calculated. Waiting.')
                    try:
                        return core.wait_on_entry_calc(key)
                    except RecalculationNeeded:
                        return _calc_entry(core, key, func, args, kwds)
            _print('No entry found. No current calc. Calling like a boss.')
            return _calc_entry(core, key, func, args, kwds)

        def clear_cache():
            """Clear the cache."""
            core.clear_cache()

        def clear_being_calculated():
            """Marks all entries in this cache as not being calculated."""
            core.clear_being_calculated()

        func_wrapper.clear_cache = clear_cache
        func_wrapper.clear_being_calculated = clear_being_calculated
        return func_wrapper

    return _cachier_decorator

Response: A persistent stale - free memoization decorator.


Instruction:
Implement a Python 3 function for
searching for UD s definition ID and return list of UrbanDefinition objects.

Response:
def defineID(defid):
    """Search for UD's definition ID and return list of UrbanDefinition objects.

    Keyword arguments:
    defid -- definition ID to search for (int or str)
    """
    json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid)))
    return _parse_urban_json(json)


Instruction:
Write a Python 3 function that can
check that a non - Python dependency is installed.

Response:
def has_external_dependency(name):
    'Check that a non-Python dependency is installed.'
    for directory in os.environ['PATH'].split(':'):
        if os.path.exists(os.path.join(directory, name)):
            return True
    return False


Instruction:
Write a Python 3 function that can
test VTK interface and repair of Stanford Bunny Mesh

Response:
def with_vtk(plot=True):
    """ Tests VTK interface and mesh repair of Stanford Bunny Mesh """
    mesh = vtki.PolyData(bunny_scan)
    meshfix = pymeshfix.MeshFix(mesh)
    if plot:
        print('Plotting input mesh')
        meshfix.plot()
    meshfix.repair()
    if plot:
        print('Plotting repaired mesh')
        meshfix.plot()

    return meshfix.mesh


Instruction:
Make a summary of the following Python 3 code
def load_arrays(self, v, f):
        # Check inputs
        if not isinstance(v, np.ndarray):
            try:
                v = np.asarray(v, np.float)
                if v.ndim != 2 and v.shape[1] != 3:
                    raise Exception('Invalid vertex format.  Shape ' +
                                    'should be (npoints, 3)')
            except BaseException:
                raise Exception(
                    'Unable to convert vertex input to valid numpy array')

        if not isinstance(f, np.ndarray):
            try:
                f = np.asarray(f, ctypes.c_int)
                if f.ndim != 2 and f.shape[1] != 3:
                    raise Exception('Invalid face format.  ' +
                                    'Shape should be (nfaces, 3)')
            except BaseException:
                raise Exception('Unable to convert face input to valid' +
                                ' numpy array')

        self.v = v
        self.f = f

Response: Loads triangular mesh from vertex and face numpy arrays.


Instruction:
Explain what the following Python 3 code does
def mesh(self):
        triangles = np.empty((self.f.shape[0], 4))
        triangles[:, -3:] = self.f
        triangles[:, 0] = 3
        return vtki.PolyData(self.v, triangles, deep=False)

Response: Return the surface mesh


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot(self, show_holes=True):
        if show_holes:
            edges = self.mesh.extract_edges(boundary_edges=True,
                                            feature_edges=False,
                                            manifold_edges=False)

            plotter = vtki.Plotter()
            plotter.add_mesh(self.mesh, label='mesh')
            plotter.add_mesh(edges, 'r', label='edges')
            plotter.plot()

        else:
            self.mesh.plot(show_edges=True)

Response:
Plot the mesh.

        Parameters
        ----------
        show_holes : bool, optional
            Shows boundaries.  Default True


Instruction:
How would you implement a function in Python 3 that
performs a mesh repair using MeshFix s default repair process.

Response:
def repair(self, verbose=False, joincomp=False,
               remove_smallest_components=True):
        """Performs mesh repair using MeshFix's default repair
        process.

        Parameters
        ----------
        verbose : bool, optional
            Enables or disables debug printing.  Disabled by default.

        joincomp : bool, optional
            Attempts to join nearby open components.

        remove_smallest_components : bool, optional
            Remove all but the largest isolated component from the
            mesh before beginning the repair process.  Default True

        Notes
        -----
        Vertex and face arrays are updated inplace.  Access them with:
        meshfix.v
        meshfix.f
        """
        assert self.f.shape[1] == 3, 'Face array must contain three columns'
        assert self.f.ndim == 2, 'Face array must be 2D'
        self.v, self.f = _meshfix.clean_from_arrays(self.v, self.f,
                                                    verbose, joincomp,
                                                    remove_smallest_components)


Instruction:
Create a Python 3 function for
writing a surface mesh to disk.

Response:
def write(self, filename, binary=True):
        """Writes a surface mesh to disk.

        Written file may be an ASCII or binary ply, stl, or vtk mesh
        file.

        Parameters
        ----------
        filename : str
            Filename of mesh to be written.  Filetype is inferred from
            the extension of the filename unless overridden with
            ftype.  Can be one of the following types (.ply, .stl,
            .vtk)

        ftype : str, optional
            Filetype.  Inferred from filename unless specified with a
            three character string.  Can be one of the following:
            'ply', 'stl', or 'vtk'.

        Notes
        -----
        Binary files write much faster than ASCII.
        """
        self.mesh.write(filename, binary)


Instruction:
How would you implement a function in Python 3 that
scrapes a URL optionally with parameters.

Response:
def scrape(url, params=None, user_agent=None):
    '''
    Scrape a URL optionally with parameters.
    This is effectively a wrapper around urllib2.urlopen.
    '''

    headers = {}

    if user_agent:
        headers['User-Agent'] = user_agent

    data = params and six.moves.urllib.parse.urlencode(params) or None
    req = six.moves.urllib.request.Request(url, data=data, headers=headers)
    f = six.moves.urllib.request.urlopen(req)

    text = f.read()
    f.close()

    return text


Instruction:
Can you implement a function in Python 3 that
converts pdf file to xml file

Response:
def pdftoxml(pdfdata, options=""):
    """converts pdf file to xml file"""
    pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')
    pdffout.write(pdfdata)
    pdffout.flush()

    xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')
    tmpxml = xmlin.name  # "temph.xml"
    cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes %s "%s" "%s"' % (
        options, pdffout.name, os.path.splitext(tmpxml)[0])
    # can't turn off output, so throw away even stderr yeuch
    cmd = cmd + " >/dev/null 2>&1"
    os.system(cmd)

    pdffout.close()
    #xmlfin = open(tmpxml)
    xmldata = xmlin.read()
    xmlin.close()
    return xmldata.decode('utf-8')


Instruction:
Create a Python 3 function for
executing an arbitrary SQL query given by query returning a list of OrderedDicts.

Response:
def execute(query, data=None):
    """
    Execute an arbitrary SQL query given by query, returning any
    results as a list of OrderedDicts. A list of values can be supplied as an,
    additional argument, which will be substituted into question marks in the
    query.
    """
    connection = _State.connection()
    _State.new_transaction()

    if data is None:
        data = []

    result = connection.execute(query, data)

    _State.table = None
    _State.metadata = None
    try:
        del _State.table_pending
    except AttributeError:
        pass

    if not result.returns_rows:
        return {u'data': [], u'keys': []}

    return {u'data': result.fetchall(), u'keys': list(result.keys())}


Instruction:
Explain what the following Python 3 code does
def select(query, data=None):
    connection = _State.connection()
    _State.new_transaction()
    if data is None:
        data = []

    result = connection.execute('select ' + query, data)

    rows = []
    for row in result:
        rows.append(dict(list(row.items())))

    return rows

Response: Perform a sql select statement with the given query and return any results as a list of OrderedDicts.


Instruction:
Write a Python 3 script for
saving the given data to the specified table.

Response:
def save(unique_keys, data, table_name='swdata'):
    """
    Save the given data to the table specified by `table_name`
    (which defaults to 'swdata'). The data must be a mapping
    or an iterable of mappings. Unique keys is a list of keys that exist
    for all rows and for which a unique index will be created.
    """

    _set_table(table_name)

    connection = _State.connection()

    if isinstance(data, Mapping):
        # Is a single datum
        data = [data]
    elif not isinstance(data, Iterable):
        raise TypeError("Data must be a single mapping or an iterable "
                        "of mappings")

    insert = _State.table.insert(prefixes=['OR REPLACE'])
    for row in data:
        if not isinstance(row, Mapping):
            raise TypeError("Elements of data must be mappings, got {}".format(
                            type(row)))
        fit_row(connection, row, unique_keys)
        connection.execute(insert.values(row))
    _State.check_last_committed()


Instruction:
How would you code a function in Python 3 to
set the table to work on.

Response:
def _set_table(table_name):
    """
    Specify the table to work on.
    """
    _State.connection()
    _State.reflect_metadata()
    _State.table = sqlalchemy.Table(table_name, _State.metadata,
                                    extend_existing=True)

    if list(_State.table.columns.keys()) == []:
        _State.table_pending = True
    else:
        _State.table_pending = False


Instruction:
Can you tell what is the following Python 3 function doing
def show_tables():
    _State.connection()
    _State.reflect_metadata()
    metadata = _State.metadata

    response = select('name, sql from sqlite_master where type="table"')

    return {row['name']: row['sql'] for row in response}

Response: Return the names of the tables currently in the database.


Instruction:
Can you create a Python 3 function that
saves a variable to the table specified by _State. vars_table_name.

Response:
def save_var(name, value):
    """
    Save a variable to the table specified by _State.vars_table_name. Key is
    the name of the variable, and value is the value.
    """
    connection = _State.connection()
    _State.reflect_metadata()

    vars_table = sqlalchemy.Table(
        _State.vars_table_name, _State.metadata,
        sqlalchemy.Column('name', sqlalchemy.types.Text, primary_key=True),
        sqlalchemy.Column('value_blob', sqlalchemy.types.LargeBinary),
        sqlalchemy.Column('type', sqlalchemy.types.Text),
        keep_existing=True
    )

    vars_table.create(bind=connection, checkfirst=True)

    column_type = get_column_type(value)

    if column_type == sqlalchemy.types.LargeBinary:
        value_blob = value
    else:
        value_blob = unicode(value).encode('utf-8')

    values = dict(name=name,
                  value_blob=value_blob,
                  # value_blob=Blob(value),
                  type=column_type.__visit_name__.lower())

    vars_table.insert(prefixes=['OR REPLACE']).values(**values).execute()


Instruction:
Write a Python 3 function that can
return the value of a variable in the _State. vars_table_name.

Response:
def get_var(name, default=None):
    """
    Returns the variable with the provided key from the
    table specified by _State.vars_table_name.
    """
    alchemytypes = {"text": lambda x: x.decode('utf-8'),
                    "big_integer": lambda x: int(x),
                    "date": lambda x: x.decode('utf-8'),
                    "datetime": lambda x: x.decode('utf-8'),
                    "float": lambda x: float(x),
                    "large_binary": lambda x: x,
                    "boolean": lambda x: x==b'True'}

    connection = _State.connection()
    _State.new_transaction()

    if _State.vars_table_name not in list(_State.metadata.tables.keys()):
        return None

    table = sqlalchemy.Table(_State.vars_table_name, _State.metadata)
    s = sqlalchemy.select([table.c.value_blob, table.c.type])
    s = s.where(table.c.name == name)
    result = connection.execute(s).fetchone()

    if not result:
        return None

    return alchemytypes[result[1]](result[0])

    # This is to do the variable type conversion through the SQL engine
    execute = connection.execute
    execute("CREATE TEMPORARY TABLE _sw_tmp ('value' {})".format(result.type))
    execute("INSERT INTO _sw_tmp VALUES (:value)", value=result.value_blob)
    var = execute('SELECT value FROM _sw_tmp').fetchone().value
    execute("DROP TABLE _sw_tmp")
    return var.decode('utf-8')


Instruction:
Write a Python 3 function that can
create a new index of the columns in column_names where column_names is a list of strings.

Response:
def create_index(column_names, unique=False):
    """
    Create a new index of the columns in column_names, where column_names is
    a list of strings. If unique is True, it will be a
    unique index.
    """
    connection = _State.connection()
    _State.reflect_metadata()
    table_name = _State.table.name

    table = _State.table

    index_name = re.sub(r'[^a-zA-Z0-9]', '', table_name) + '_'
    index_name += '_'.join(re.sub(r'[^a-zA-Z0-9]', '', x)
                           for x in column_names)

    if unique:
        index_name += '_unique'

    columns = []
    for column_name in column_names:
        columns.append(table.columns[column_name])

    current_indices = [x.name for x in table.indexes]
    index = sqlalchemy.schema.Index(index_name, *columns, unique=unique)
    if index.name not in current_indices:
        index.create(bind=_State.engine)


Instruction:
Make a summary of the following Python 3 code
def fit_row(connection, row, unique_keys):
    new_columns = []
    for column_name, column_value in list(row.items()):
        new_column = sqlalchemy.Column(column_name,
                                       get_column_type(column_value))

        if not column_name in list(_State.table.columns.keys()):
            new_columns.append(new_column)
            _State.table.append_column(new_column)

    if _State.table_pending:
        create_table(unique_keys)
        return

    for new_column in new_columns:
        add_column(connection, new_column)

Response: Takes a row and checks to make sure it fits in the columns of the current table. Adds the required columns.


Instruction:
How would you explain what the following Python 3 function does
def create_table(unique_keys):
    _State.new_transaction()
    _State.table.create(bind=_State.engine, checkfirst=True)
    if unique_keys != []:
        create_index(unique_keys, unique=True)
    _State.table_pending = False
    _State.reflect_metadata()

Response: Create the table in the database.


Instruction:
Write a Python 3 function for
adding a column to the current table.

Response:
def add_column(connection, column):
    """
    Add a column to the current table.
    """
    stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
    connection.execute(stmt)
    _State.reflect_metadata()


Instruction:
Can you tell what is the following Python 3 function doing
def drop():
    # Ensure the connection is up
    _State.connection()
    _State.table.drop(checkfirst=True)
    _State.metadata.remove(_State.table)
    _State.table = None
    _State.new_transaction()

Response: Drop the current table if it exists.


Instruction:
How would you implement a function in Python 3 that
extracts attributes and attaches them to element.

Response:
def attach_attrs_table(key, value, fmt, meta):
    """Extracts attributes and attaches them to element."""

    # We can't use attach_attrs_factory() because Table is a block-level element
    if key in ['Table']:
        assert len(value) == 5
        caption = value[0]  # caption, align, x, head, body

        # Set n to the index where the attributes start
        n = 0
        while n < len(caption) and not \
          (caption[n]['t'] == 'Str' and caption[n]['c'].startswith('{')):
            n += 1

        try:
            attrs = extract_attrs(caption, n)
            value.insert(0, attrs)
        except (ValueError, IndexError):
            pass


Instruction:
Write a Python 3 script to
process the attributed tables.

Response:
def process_tables(key, value, fmt, meta):
    """Processes the attributed tables."""

    global has_unnumbered_tables  # pylint: disable=global-statement

    # Process block-level Table elements
    if key == 'Table':

        # Inspect the table
        if len(value) == 5:  # Unattributed, bail out
            has_unnumbered_tables = True
            if fmt in ['latex']:
                return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
                        Table(*value),
                        RawBlock('tex', r'\end{no-prefix-table-caption}')]
            return None

        # Process the table
        table = _process_table(value, fmt)

        # Context-dependent output
        attrs = table['attrs']
        if table['is_unnumbered']:
            if fmt in ['latex']:
                return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
                        AttrTable(*value),
                        RawBlock('tex', r'\end{no-prefix-table-caption}')]

        elif fmt in ['latex']:
            if table['is_tagged']:  # Code in the tags
                tex = '\n'.join([r'\let\oldthetable=\thetable',
                                 r'\renewcommand\thetable{%s}'%\
                                 references[attrs[0]]])
                pre = RawBlock('tex', tex)
                tex = '\n'.join([r'\let\thetable=\oldthetable',
                                 r'\addtocounter{table}{-1}'])
                post = RawBlock('tex', tex)
                return [pre, AttrTable(*value), post]
        elif table['is_unreferenceable']:
            attrs[0] = ''  # The label isn't needed any further
        elif fmt in ('html', 'html5') and LABEL_PATTERN.match(attrs[0]):
            # Insert anchor
            anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0])
            return [anchor, AttrTable(*value)]
        elif fmt == 'docx':
            # As per http://officeopenxml.com/WPhyperlink.php
            bookmarkstart = \
              RawBlock('openxml',
                       '<w:bookmarkStart w:id="0" w:name="%s"/>'
                       %attrs[0])
            bookmarkend = \
              RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
            return [bookmarkstart, AttrTable(*value), bookmarkend]

    return None


Instruction:
How would you code a function in Python 3 to
filter the document AST and returns the resulting XML tree.

Response:
def main():
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, insert_secnos,
                                process_tables, delete_secnos,
                                detach_attrs_table], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()


Instruction:
Given the following Python 3 function, write the documentation
def request(url, xml):

    r = _urllib.Request(url, xml)
    r.add_header('Content-Type', 'application/xml')
    r.add_header('User-Agent', 'Clockwork Python wrapper/1.0')

    result = {}
    try:
        f = _urllib.urlopen(r)
    except URLError as error:
        raise clockwork_exceptions.HttpException("Error connecting to clockwork server: %s" % error)

    result['data'] = f.read()
    result['status'] = f.getcode()

    if hasattr(f, 'headers'):
        result['etag'] = f.headers.get('ETag')
        result['lastmodified'] = f.headers.get('Last-Modified')
        if f.headers.get('content−encoding', '') == 'gzip':
            result['data'] = gzip.GzipFile(fileobj=StringIO(result['data'])).read()
        if hasattr(f, 'url'):
            result['url'] = f.url
            result['status'] = 200
    f.close()

    if result['status'] != 200:
        raise clockwork_exceptions.HttpException("Error connecting to clockwork server - status code %s" % result['status'])

    return result

Response: Make a http request to the clockwork server


Instruction:
How would you code a function in Python 3 to
check the balance fot this account.

Response:
def get_balance(self):
        """Check the balance fot this account.
           Returns a dictionary containing:
           account_type: The account type
           balance: The balance remaining on the account
           currency: The currency used for the account balance. Assume GBP in not set"""

        xml_root = self.__init_xml('Balance')

        response = clockwork_http.request(BALANCE_URL, etree.tostring(xml_root, encoding='utf-8'))
        data_etree = etree.fromstring(response['data'])

        err_desc = data_etree.find('ErrDesc')
        if err_desc is not None:
            raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text)

        result = {}
        result['account_type'] = data_etree.find('AccountType').text
        result['balance'] = data_etree.find('Balance').text
        result['currency'] = data_etree.find('Currency').text
        return result


Instruction:
Explain what the following Python 3 code does
def send(self, messages):

        tmpSms = SMS(to='', message='')
        if str(type(messages)) == str(type(tmpSms)):
            messages = [messages]

        xml_root = self.__init_xml('Message')
        wrapper_id = 0

        for m in messages:
            m.wrapper_id = wrapper_id
            msg = self.__build_sms_data(m)
            sms = etree.SubElement(xml_root, 'SMS')
            for sms_element in msg:
                element = etree.SubElement(sms, sms_element)
                element.text = msg[sms_element]

        # print etree.tostring(xml_root)
        response = clockwork_http.request(SMS_URL, etree.tostring(xml_root, encoding='utf-8'))
        response_data = response['data']

        # print response_data
        data_etree = etree.fromstring(response_data)

        # Check for general error
        err_desc = data_etree.find('ErrDesc')
        if err_desc is not None:
            raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text)

        # Return a consistent object
        results = []
        for sms in data_etree:
            matching_sms = next((s for s in messages if str(s.wrapper_id) == sms.find('WrapperID').text), None)
            new_result = SMSResponse(
                sms = matching_sms,
                id = '' if sms.find('MessageID') is None else sms.find('MessageID').text,
                error_code = 0 if sms.find('ErrNo') is None else sms.find('ErrNo').text,
                error_message = '' if sms.find('ErrDesc') is None else sms.find('ErrDesc').text,
                success = True if sms.find('ErrNo') is None else (sms.find('ErrNo').text == 0)
            )
            results.append(new_result)

        if len(results) > 1:
            return results

        return results[0]

Response: Send a list of SMS messages or an array of SMS messages


Instruction:
Given the following Python 3 function, write the documentation
def __init_xml(self, rootElementTag):
        xml_root = etree.Element(rootElementTag)
        key = etree.SubElement(xml_root, "Key")
        key.text = self.apikey
        return xml_root

Response: Init a etree element and pop a key in there


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

        attributes = {}

        attributes_to_translate = {
            'to' : 'To',
            'message' : 'Content',
            'client_id' : 'ClientID',
            'concat' : 'Concat',
            'from_name': 'From',
            'invalid_char_option' : 'InvalidCharOption',
            'truncate' : 'Truncate',
            'wrapper_id' : 'WrapperId'
        }

        for attr in attributes_to_translate:
            val_to_use = None
            if hasattr(message, attr):
                val_to_use = getattr(message, attr)
            if val_to_use is None and hasattr(self, attr):
                val_to_use = getattr(self, attr)
            if val_to_use is not None:
                attributes[attributes_to_translate[attr]] = str(val_to_use)

        return attributes

Response: Build a dictionary of SMS message elements


Instruction:
How would you explain what the following Python 3 function does
def pstats2entries(data):
    # Each entry's key is a tuple of (filename, line number, function name)
    entries = {}
    allcallers = {}

    # first pass over stats to build the list of entry instances
    for code_info, call_info in data.stats.items():
        # build a fake code object
        code = Code(*code_info)

        # build a fake entry object.  entry.calls will be filled during the
        # second pass over stats
        cc, nc, tt, ct, callers = call_info
        entry = Entry(code, callcount=cc, reccallcount=nc - cc, inlinetime=tt,
                      totaltime=ct, calls=[])

        # collect the new entry
        entries[code_info] = entry
        allcallers[code_info] = list(callers.items())

    # second pass of stats to plug callees into callers
    for entry in entries.values():
        entry_label = cProfile.label(entry.code)
        entry_callers = allcallers.get(entry_label, [])
        for entry_caller, call_info in entry_callers:
            cc, nc, tt, ct = call_info
            subentry = Subentry(entry.code, callcount=cc, reccallcount=nc - cc,
                                inlinetime=tt, totaltime=ct)
            # entry_caller has the same form as code_info
            entries[entry_caller].calls.append(subentry)

    return list(entries.values())

Response: Convert serialized pstats to a list of raw entries.


Instruction:
Explain what the following Python 3 code does
def is_installed(prog):
    with open(os.devnull, 'w') as devnull:
        try:
            if os.name == 'nt':
                retcode = subprocess.call(['where', prog], stdout=devnull)
            else:
                retcode = subprocess.call(['which', prog], stdout=devnull)
        except OSError as e:
            # If where or which doesn't exist, a "ENOENT" error will occur (The
            # FileNotFoundError subclass on Python 3).
            if e.errno != errno.ENOENT:
                raise
            retcode = 1

    return retcode == 0

Response: Return whether or not a given executable is installed on the machine.


Instruction:
Can you write a function in Python 3 where it
executes the kcachegrind tool on the calltree.

Response:
def main():
    """Execute the converter using parameters provided on the command line"""

    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--outfile', metavar='output_file_path',
                        help="Save calltree stats to <outfile>")
    parser.add_argument('-i', '--infile', metavar='input_file_path',
                        help="Read Python stats from <infile>")
    parser.add_argument('-k', '--kcachegrind',
                        help="Run the kcachegrind tool on the converted data",
                        action="store_true")
    parser.add_argument('-r', '--run-script',
                        nargs=argparse.REMAINDER,
                        metavar=('scriptfile', 'args'),
                        dest='script',
                        help="Name of the Python script to run to collect"
                        " profiling data")
    args = parser.parse_args()

    outfile = args.outfile

    if args.script is not None:
        # collect profiling data by running the given script
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.script[0])

        fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree')
        os.close(fd)
        try:
            cmd = [
                sys.executable,
                '-m', 'cProfile',
                '-o', tmp_path,
            ]
            cmd.extend(args.script)
            subprocess.check_call(cmd)

            kg = CalltreeConverter(tmp_path)
        finally:
            os.remove(tmp_path)

    elif args.infile is not None:
        # use the profiling data from some input file
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.infile)

        if args.infile == outfile:
            # prevent name collisions by appending another extension
            outfile += ".log"

        kg = CalltreeConverter(pstats.Stats(args.infile))

    else:
        # at least an input file or a script to run is required
        parser.print_usage()
        sys.exit(2)

    if args.outfile is not None or not args.kcachegrind:
        # user either explicitly required output file or requested by not
        # explicitly asking to launch kcachegrind
        sys.stderr.write("writing converted data to: %s\n" % outfile)
        with open(outfile, 'w') as f:
            kg.output(f)

    if args.kcachegrind:
        sys.stderr.write("launching kcachegrind\n")
        kg.visualize()


Instruction:
Can you generate the documentation for the following Python 3 function
def convert(profiling_data, outputfile):
    converter = CalltreeConverter(profiling_data)
    if is_basestring(outputfile):
        with open(outputfile, "w") as f:
            converter.output(f)
    else:
        converter.output(outputfile)

Response: convert profiling_data to calltree format and dump it to outputfile


Instruction:
Given the following Python 3 function, write the documentation
def output(self, out_file):
        self.out_file = out_file
        out_file.write('event: ns : Nanoseconds\n')
        out_file.write('events: ns\n')
        self._output_summary()
        for entry in sorted(self.entries, key=_entry_sort_key):
            self._output_entry(entry)

Response: Write the converted entries to out_file


Instruction:
Create a Python 3 function to
launch kcachegrind on the converted entries.

Response:
def visualize(self):
        """Launch kcachegrind on the converted entries.

        One of the executables listed in KCACHEGRIND_EXECUTABLES
        must be present in the system path.
        """

        available_cmd = None
        for cmd in KCACHEGRIND_EXECUTABLES:
            if is_installed(cmd):
                available_cmd = cmd
                break

        if available_cmd is None:
            sys.stderr.write("Could not find kcachegrind. Tried: %s\n" %
                             ", ".join(KCACHEGRIND_EXECUTABLES))
            return

        if self.out_file is None:
            fd, outfile = tempfile.mkstemp(".log", "pyprof2calltree")
            use_temp_file = True
        else:
            outfile = self.out_file.name
            use_temp_file = False

        try:
            if use_temp_file:
                with io.open(fd, "w") as f:
                    self.output(f)
            subprocess.call([available_cmd, outfile])
        finally:
            # clean the temporary file
            if use_temp_file:
                os.remove(outfile)
                self.out_file = None


Instruction:
Here you have a function in Python 3, explain what it does
def get_app(self, reference_app=None):

        if reference_app is not None:
            return reference_app

        if self.app is not None:
            return self.app

        ctx = stack.top

        if ctx is not None:
            return ctx.app

        raise RuntimeError('Application not registered on Bouncer'
                           ' instance and no application bound'
                           ' to current context')

Response: Helper method that implements the logic to look up an application.


Instruction:
How would you implement a function in Python 3 that
initializes the Flask - Bouncer extension for the specified application.

Response:
def init_app(self, app, **kwargs):
        """ Initializes the Flask-Bouncer extension for the specified application.

        :param app: The application.
        """
        self.app = app

        self._init_extension()

        self.app.before_request(self.check_implicit_rules)

        if kwargs.get('ensure_authorization', False):
            self.app.after_request(self.check_authorization)


Instruction:
Here you have a function in Python 3, explain what it does
def check_authorization(self, response):
        if not hasattr(request, '_authorized'):
            raise Unauthorized
        elif not request._authorized:
            raise Unauthorized
        return response

Response: checks that an authorization call has been made during the request


Instruction:
Can you tell what is the following Python 3 function doing
def check_implicit_rules(self):
        if not self.request_is_managed_by_flask_classy():
            return

        if self.method_is_explictly_overwritten():
            return

        class_name, action = request.endpoint.split(':')
        clazz = [classy_class for classy_class in self.flask_classy_classes if classy_class.__name__ == class_name][0]
        Condition(action, clazz.__target_model__).test()

Response: Check implicit rules for the current user.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
    x, y = texture
    x = x.copy() - x_offset
    y = y.copy() - y_offset
    angle = np.radians(rotation)
    x_rot = x * np.cos(angle) + y * np.sin(angle)
    y_rot = x * -np.sin(angle) + y * np.cos(angle)
    return x_rot + x_offset, y_rot + y_offset

Response: Rotates the given texture by a given angle.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fit_texture(layer):
    x, y = layer
    x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x))
    y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y))
    return x, y

Response: Fits a layer into a texture by scaling each axis to 0 1.


Instruction:
Can you tell what is the following Python 3 function doing
def check_valid_solution(solution, graph):
    expected = Counter(
        i for (i, _) in graph.iter_starts_with_index()
        if i < graph.get_disjoint(i)
    )
    actual = Counter(
        min(i, graph.get_disjoint(i))
        for i in solution
    )

    difference = Counter(expected)
    difference.subtract(actual)
    difference = {k: v for k, v in difference.items() if v != 0}
    if difference:
        print('Solution is not valid!'
              'Difference in node counts (expected - actual): {}'.format(difference))
        return False
    return True

Response: Check that the solution is valid.


Instruction:
Can you create a Python 3 function that
converts a solution into a list of paths suitable for rendering.

Response:
def get_route_from_solution(solution, graph):
    """Converts a solution (a list of node indices) into a list
    of paths suitable for rendering."""

    # As a guard against comparing invalid "solutions",
    # ensure that this solution is valid.
    assert check_valid_solution(solution, graph)

    return [graph.get_path(i) for i in solution]


Instruction:
Can you generate the documentation for the following Python 3 function
def branching_turtle_generator(turtle_program, turn_amount=DEFAULT_TURN,
                               initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
    """Given a turtle program, creates a generator of turtle positions.

    The state of the turtle consists of its position and angle.
    The turtle starts at the position ``(0, 0)`` facing up. Each character in the
    turtle program is processed in order and causes an update to the state.
    The position component of the state is yielded at each state change. A
    ``(nan, nan)`` separator is emitted between state changes for which no line
    should be drawn.

    The turtle program consists of the following commands:

    - Any letter in ``ABCDEFGHIJ`` means "move forward one unit and draw a path"
    - Any letter in ``abcdefghij`` means "move forward" (no path)
    - The character ``-`` means "move counter-clockwise"
    - The character ``+`` means "move clockwise"
    - The character ``[`` means "push a copy of the current state to the stack"
    - The character ``]`` means "pop a state from the stack and return there"
    - All other characters are silently ignored (this is useful when producing
      programs with L-Systems)

    Args:
        turtle_program (str): a string or generator representing the turtle program
        turn_amount (float): how much the turn commands should change the angle
        initial_angle (float): if provided, the turtle starts at this angle (degrees)
        resolution (int): if provided, interpolate this many points along each visible
            line

    Yields:
        pair: The next coordinate pair, or ``(nan, nan)`` as a path separator.
    """
    saved_states = list()
    state = (0, 0, DEFAULT_INITIAL_ANGLE)
    yield (0, 0)

    for command in turtle_program:
        x, y, angle = state

        if command in FORWARD_COMMANDS:
            new_x = x - np.cos(np.radians(angle))
            new_y = y + np.sin(np.radians(angle))
            state = (new_x, new_y, angle)

            if command not in VISIBLE_FORWARD_COMMANDS:
                yield (np.nan, np.nan)
                yield (state[0], state[1])
            else:
                dx = new_x - x
                dy = new_y - y
                for frac in (1 - np.flipud(np.linspace(0, 1, resolution, False))):
                    yield (x + frac * dx, y + frac * dy)

        elif command == CW_TURN_COMMAND:
            state = (x, y, angle + turn_amount)

        elif command == CCW_TURN_COMMAND:
            state = (x, y, angle - turn_amount)

        elif command == PUSH_STATE_COMMAND:
            saved_states.append(state)

        elif command == POP_STATE_COMMAND:
            state = saved_states.pop()
            yield (np.nan, np.nan)
            x, y, _ = state
            yield (x, y)

Response: Generates a generator of turtle positions and lines that are branched at each location.


Instruction:
Write a Python 3 function for
making a texture from a turtle program.

Response:
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
                      initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
    """Makes a texture from a turtle program.

    Args:
        turtle_program (str): a string representing the turtle program; see the
            docstring of `branching_turtle_generator` for more details
        turn_amount (float): amount to turn in degrees
        initial_angle (float): initial orientation of the turtle
        resolution (int): if provided, interpolation amount for visible lines

    Returns:
        texture: A texture.
    """
    generator = branching_turtle_generator(
        turtle_program, turn_amount, initial_angle, resolution)
    return texture_from_generator(generator)


Instruction:
Explain what the following Python 3 code does
def transform_sequence(sequence, transformations):
    for c in sequence:
        for k in transformations.get(c, c):
            yield k

Response: Applies a given set of substitution rules to the given string or generator.


Instruction:
Implement a Python 3 function for
chaining a transformation a given number of times.

Response:
def transform_multiple(sequence, transformations, iterations):
    """Chains a transformation a given number of times.

    Args:
        sequence (str): a string or generator onto which transformations are applied
        transformations (dict): a dictionary mapping each char to the string that is
            substituted for it when the rule is applied
        iterations (int): how many times to repeat the transformation

    Yields:
        str: the next character in the output sequence.
    """
    for _ in range(iterations):
        sequence = transform_sequence(sequence, transformations)
    return sequence


Instruction:
How would you code a function in Python 3 to
generate a texture by running transformations on a turtle program that is a turtle system.

Response:
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
    """Generates a texture by running transformations on a turtle program.

    First, the given transformations are applied to the axiom. This is
    repeated `iterations` times. Then, the output is run as a turtle
    program to get a texture, which is returned.

    For more background see: https://en.wikipedia.org/wiki/L-system

    Args:
        axiom (str): the axiom of the Lindenmeyer system (a string)
        transformations (dict): a dictionary mapping each char to the string that is
            substituted for it when the rule is applied
        iterations (int): the number of times to apply the transformations
        angle (float): the angle to use for turns when interpreting the string
            as a turtle graphics program
        resolution (int): the number of midpoints to create in each turtle step

    Returns:
        A texture
    """
    turtle_program = transform_multiple(axiom, transformations, iterations)
    return turtle_to_texture(turtle_program, angle, resolution=resolution)


Instruction:
Explain what the following Python 3 code does
def get_path(self, i):
        index = (i - 1) // 2
        reverse = (i - 1) % 2
        path = self.paths[index]
        if reverse:
            return path.reversed()
        else:
            return path

Response: Returns the path corresponding to the node i.


Instruction:
Implement a function in Python 3 to
return the distance between the end of path i and the start of path j.

Response:
def cost(self, i, j):
        """Returns the distance between the end of path i
        and the start of path j."""
        return dist(self.endpoints[i][1], self.endpoints[j][0])


Instruction:
Can you create a Python 3 function that
returns the starting coordinates of node i as a pair and the end coordinates iff end is True.

Response:
def get_coordinates(self, i, end=False):
        """Returns the starting coordinates of node i as a pair,
        or the end coordinates iff end is True."""
        if end:
            endpoint = self.endpoints[i][1]
        else:
            endpoint = self.endpoints[i][0]
        return (endpoint.real, endpoint.imag)


Instruction:
How would you explain what the following Python 3 function does
def iter_starts_with_index(self):
        for i in range(1, len(self.endpoints)):
            yield i, self.get_coordinates(i)

Response: Returns a generator over ( index start coordinate ) pairs and the original location of the resource.


Instruction:
Here you have a function in Python 3, explain what it does
def iter_disjunctions(self):
        for i in range(1, len(self.endpoints), 2):
            yield [i, self.get_disjoint(i)]

Response: Returns an iterator over the disjoints of the cluster - level entries.


Instruction:
Create a Python 3 function for
previewing a plot in a jupyter notebook.

Response:
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
    """Preview a plot in a jupyter notebook.

    Args:
        plot (list): the plot to display (list of layers)
        width (int): the width of the preview
        height (int): the height of the preview

    Returns:
        An object that renders in Jupyter as the provided plot
    """
    return SVG(data=plot_to_svg(plot, width, height))


Instruction:
Can you generate the documentation for the following Python 3 function
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
    min_x = min(np.nanmin(x) for x, y in layers)
    max_x = max(np.nanmax(x) for x, y in layers)
    min_y = min(np.nanmin(y) for x, y in layers)
    max_y = max(np.nanmax(y) for x, y in layers)
    height = max_y - min_y
    width = max_x - min_x

    if height > width * aspect_ratio:
        adj_height = height * (1. + margin)
        adj_width = adj_height / aspect_ratio
    else:
        adj_width = width * (1. + margin)
        adj_height = adj_width * aspect_ratio

    width_buffer = (adj_width - width) / 2.
    height_buffer = (adj_height - height) / 2.

    return (
        min_x - width_buffer,
        min_y - height_buffer,
        adj_width,
        adj_height
    )

Response: Calculates the size of the SVG viewBox to use.


Instruction:
Create a Python 3 function for
generating an SVG path from a given layer.

Response:
def _layer_to_path_gen(layer):
    """Generates an SVG path from a given layer.

    Args:
        layer (layer): the layer to convert

    Yields:
        str: the next component of the path
    """
    draw = False
    for x, y in zip(*layer):
        if np.isnan(x) or np.isnan(y):
            draw = False
        elif not draw:
            yield 'M {} {}'.format(x, y)
            draw = True
        else:
            yield 'L {} {}'.format(x, y)


Instruction:
Create a Python 3 function to
convert a list of layers into an SVG document.

Response:
def plot_to_svg(plot, width, height, unit=''):
    """Converts a plot (list of layers) into an SVG document.

    Args:
        plot (list): list of layers that make up the plot
        width (float): the width of the resulting image
        height (float): the height of the resulting image
        unit (str): the units of the resulting image if not pixels

    Returns:
        str: A stringified XML document representing the image
    """
    flipped_plot = [(x, -y) for x, y in plot]
    aspect_ratio = height / width
    view_box = calculate_view_box(flipped_plot, aspect_ratio=aspect_ratio)
    view_box_str = '{} {} {} {}'.format(*view_box)
    stroke_thickness = STROKE_THICKNESS * (view_box[2])

    svg = ET.Element('svg', attrib={
        'xmlns': 'http://www.w3.org/2000/svg',
        'xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape',
        'width': '{}{}'.format(width, unit),
        'height': '{}{}'.format(height, unit),
        'viewBox': view_box_str})

    for i, layer in enumerate(flipped_plot):
        group = ET.SubElement(svg, 'g', attrib={
            'inkscape:label': '{}-layer'.format(i),
            'inkscape:groupmode': 'layer',
        })

        color = PLOT_COLORS[i % len(PLOT_COLORS)]
        ET.SubElement(group, 'path', attrib={
            'style': 'stroke-width: {}; stroke: {};'.format(stroke_thickness, color),
            'fill': 'none',
            'd': layer_to_path(layer)
        })

    try:
        return ET.tostring(svg, encoding='unicode')
    except LookupError:
        # Python 2.x
        return ET.tostring(svg)


Instruction:
Can you tell what is the following Python 3 function doing
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
    svg = plot_to_svg(plot, width, height, unit)
    with open(filename, 'w') as outfile:
        outfile.write(svg)

Response: Writes a plot SVG to a file.


Instruction:
Write a Python 3 function that can
draw a layer on the given matplotlib axis.

Response:
def draw_layer(ax, layer):
    """Draws a layer on the given matplotlib axis.

    Args:
        ax (axis): the matplotlib axis to draw on
        layer (layer): the layers to plot
    """
    ax.set_aspect('equal', 'datalim')
    ax.plot(*layer)
    ax.axis('off')


Instruction:
Explain what the following Python 3 code does
def map_texture_to_surface(texture, surface):
    texture_x, texture_y = texture
    surface_h, surface_w = surface.shape

    surface_x = np.clip(
        np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
    surface_y = np.clip(
        np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)

    surface_z = surface[surface_y, surface_x]
    return surface_z

Response: Returns the values on a surface for each point in the specified texture.


Instruction:
Can you create a Python 3 function that
creates a new texture by adding z - values to an existing texture and projecting it.

Response:
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
    """Creates a texture by adding z-values to an existing texture and projecting.

    When working with surfaces there are two ways to accomplish the same thing:

    1. project the surface and map a texture to the projected surface
    2. map a texture to the surface, and then project the result

    The first method, which does not use this function, is preferred because
    it is easier to do occlusion removal that way. This function is provided
    for cases where you do not wish to generate a surface (and don't care about
    occlusion removal.)

    Args:
        texture_xy (texture): the texture to project
        texture_z (np.array): the Z-values to use in the projection
        angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)

    Returns:
        layer: A layer.
    """
    z_coef = np.sin(np.radians(angle))
    y_coef = np.cos(np.radians(angle))
    surface_x, surface_y = texture
    return (surface_x, -surface_y * y_coef + surface_z * z_coef)


Instruction:
Can you implement a function in Python 3 that
returns the height of the surface when projected at the given angle.

Response:
def project_surface(surface, angle=DEFAULT_ANGLE):
    """Returns the height of the surface when projected at the given angle.

    Args:
        surface (surface): the surface to project
        angle (float): the angle at which to project the surface

    Returns:
        surface: A projected surface.
    """
    z_coef = np.sin(np.radians(angle))
    y_coef = np.cos(np.radians(angle))

    surface_height, surface_width = surface.shape
    slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T

    return slope * y_coef + surface * z_coef


Instruction:
Write a Python 3 script to
map a texture onto a surface then projects it onto a 2D layer.

Response:
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
    """Maps a texture onto a surface, then projects to 2D and returns a layer.

    Args:
        texture (texture): the texture to project
        surface (surface): the surface to project onto
        angle (float): the projection angle in degrees (0 = top-down, 90 = side view)

    Returns:
        layer: A layer.
    """
    projected_surface = project_surface(surface, angle)
    texture_x, _ = texture
    texture_y = map_texture_to_surface(texture, projected_surface)
    return texture_x, texture_y


Instruction:
Write a Python 3 script to
remove hidden parts from a projected surface.

Response:
def _remove_hidden_parts(projected_surface):
    """Removes parts of a projected surface that are not visible.

    Args:
        projected_surface (surface): the surface to use

    Returns:
        surface: A projected surface.
    """
    surface = np.copy(projected_surface)
    surface[~_make_occlusion_mask(projected_surface)] = np.nan
    return surface


Instruction:
Can you write a function in Python 3 where it
projects a texture onto a surface with occluded areas removed.

Response:
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
    """Projects a texture onto a surface with occluded areas removed.

    Args:
        texture (texture): the texture to map to the projected surface
        surface (surface): the surface to project
        angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)

    Returns:
        layer: A layer.
    """
    projected_surface = project_surface(surface, angle)
    projected_surface = _remove_hidden_parts(projected_surface)
    texture_y = map_texture_to_surface(texture, projected_surface)
    texture_x, _ = texture
    return texture_x, texture_y


Instruction:
Can you write a function in Python 3 where it
makes a texture consisting of a given number of horizontal lines.

Response:
def make_lines_texture(num_lines=10, resolution=50):
    """Makes a texture consisting of a given number of horizontal lines.

    Args:
        num_lines (int): the number of lines to draw
        resolution (int): the number of midpoints on each line

    Returns:
        A texture.
    """
    x, y = np.meshgrid(
        np.hstack([np.linspace(0, 1, resolution), np.nan]),
        np.linspace(0, 1, num_lines),
    )

    y[np.isnan(x)] = np.nan
    return x.flatten(), y.flatten()


Instruction:
How would you code a function in Python 3 to
make a texture consisting of a grid of horizontal and vertical lines.

Response:
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
    """Makes a texture consisting of a grid of vertical and horizontal lines.

    Args:
        num_h_lines (int): the number of horizontal lines to draw
        num_v_lines (int): the number of vertical lines to draw
        resolution (int): the number of midpoints to draw on each line

    Returns:
        A texture.
    """
    x_h, y_h = make_lines_texture(num_h_lines, resolution)
    y_v, x_v = make_lines_texture(num_v_lines, resolution)
    return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v])


Instruction:
Implement a function in Python 3 to
make a texture consisting of a spiral from the origin.

Response:
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
    """Makes a texture consisting of a spiral from the origin.

    Args:
        spirals (float): the number of rotations to make
        ccw (bool): make spirals counter-clockwise (default is clockwise)
        offset (float): if non-zero, spirals start offset by this amount
        resolution (int): number of midpoints along the spiral

    Returns:
        A texture.
    """
    dist = np.sqrt(np.linspace(0., 1., resolution))
    if ccw:
        direction = 1.
    else:
        direction = -1.
    angle = dist * spirals * np.pi * 2. * direction
    spiral_texture = (
        (np.cos(angle) * dist / 2.) + 0.5,
        (np.sin(angle) * dist / 2.) + 0.5
    )
    return spiral_texture


Instruction:
Explain what the following Python 3 code does
def make_hex_texture(grid_size = 2, resolution=1):
    grid_x, grid_y = np.meshgrid(
        np.arange(grid_size),
        np.arange(grid_size)
    )
    ROOT_3_OVER_2 = np.sqrt(3) / 2
    ONE_HALF = 0.5

    grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
    grid_y = grid_y.flatten() * 1.5

    grid_points = grid_x.shape[0]

    x_offsets = np.interp(np.arange(4 * resolution),
        np.arange(4) * resolution, [
            ROOT_3_OVER_2,
            0.,
            -ROOT_3_OVER_2,
            -ROOT_3_OVER_2,
        ])
    y_offsets = np.interp(np.arange(4 * resolution),
        np.arange(4) * resolution, [
            -ONE_HALF,
            -1.,
            -ONE_HALF,
            ONE_HALF
        ])

    tmx = 4 * resolution
    x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1))
    y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1))

    x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))])
    y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))])

    return fit_texture((x_t.flatten('F'), y_t.flatten('F')))

Response: Makes a texture consisting on a grid of hexagons.


Instruction:
Explain what the following Python 3 code does
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
    if seed is not None:
        np.random.seed(seed)

    return gaussian_filter(np.random.normal(size=dims), blur)

Response: Makes a random noise surface


Instruction:
Here you have a function in Python 3, explain what it does
def make_gradients(dims=DEFAULT_DIMS):
    return np.meshgrid(
        np.linspace(0.0, 1.0, dims[0]),
        np.linspace(0.0, 1.0, dims[1])
    )

Response: Makes a pair of gradients to generate textures from numpy primitives.


Instruction:
How would you explain what the following Python 3 function does
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
    gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
    return np.sin(np.linalg.norm(gradients, axis=0))

Response: Makes a surface from the 3D sine function.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
    gradients = make_gradients(dims)
    return (
        np.sin((gradients[0] - 0.5) * repeat * np.pi) *
        np.sin((gradients[1] - 0.5) * repeat * np.pi))

Response: Makes a surface from the product of sine functions on each axis.


Instruction:
Make a summary of the following Python 3 code
def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60):
    # Create the VRP routing model. The 1 means we are only looking
    # for a single path.
    routing = pywrapcp.RoutingModel(path_graph.num_nodes(),
                                    1, path_graph.ORIGIN)

    # For every path node, add a disjunction so that we do not also
    # draw its reverse.
    for disjunction in path_graph.iter_disjunctions():
        routing.AddDisjunction(disjunction)

    # Wrap the distance function so that it converts to an integer,
    # as or-tools requires. Values are multiplied by COST_MULTIPLIER
    # prior to conversion to reduce the loss of precision.
    COST_MULTIPLIER = 1e4

    def distance(i, j):
        return int(path_graph.cost(i, j) * COST_MULTIPLIER)
    routing.SetArcCostEvaluatorOfAllVehicles(distance)

    start_time = time()

    def found_solution():
        t = time() - start_time
        cost = routing.CostVar().Max() / COST_MULTIPLIER
        print('\rBest solution at {} seconds has cost {}        '.format(
            int(t), cost), end='')
    routing.AddAtSolutionCallback(found_solution)

    # If we weren't supplied with a solution initially, construct one by taking
    # all of the paths in their original direction, in their original order.
    if not initial_solution:
        initial_solution = [i for i, _ in path_graph.iter_disjunctions()]

    # Compute the cost of the initial solution. This is the number we hope to
    # improve on.
    initial_assignment = routing.ReadAssignmentFromRoutes([initial_solution],
                                                          True)
    # print('Initial distance:',
    #      initial_assignment.ObjectiveValue() / COST_MULTIPLIER)

    # Set the parameters of the search.
    search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
    search_parameters.time_limit_ms = runtime_seconds * 1000
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)

    # Run the optimizer and report the final distance.
    assignment = routing.SolveFromAssignmentWithParameters(initial_assignment,
                                                           search_parameters)
    print()
    #print('Final distance:', assignment.ObjectiveValue() / COST_MULTIPLIER)

    # Iterate over the result to produce a list to return as the solution.
    solution = []
    index = routing.Start(0)
    while not routing.IsEnd(index):
        index = assignment.Value(routing.NextVar(index))
        node = routing.IndexToNode(index)
        if node != 0:
            # For compatibility with the greedy solution, exclude the origin.
            solution.append(node)
    return solution

Response: Solve a path using or - tools Vehicle Routing Problem solver.


Instruction:
Make a summary of the following Python 3 code
def init_controller(url):
    # pylint: disable=global-statement
    global _VERA_CONTROLLER
    created = False
    if _VERA_CONTROLLER is None:
        _VERA_CONTROLLER = VeraController(url)
        created = True
        _VERA_CONTROLLER.start()
    return [_VERA_CONTROLLER, created]

Response:
Initialize a controller.

    Provides a single global controller for applications that can't do this
    themselves


Instruction:
Create a Python 3 function to
perform a data_request and return the result.

Response:
def data_request(self, payload, timeout=TIMEOUT):
        """Perform a data_request and return the result."""
        request_url = self.base_url + "/data_request"
        return requests.get(request_url, timeout=timeout, params=payload)


Instruction:
Make a summary of the following Python 3 code
def get_simple_devices_info(self):
        j = self.data_request({'id': 'sdata'}).json()

        self.scenes = []
        items = j.get('scenes')

        for item in items:
            self.scenes.append(VeraScene(item, self))

        if j.get('temperature'):
            self.temperature_units = j.get('temperature')

        self.categories = {}
        cats = j.get('categories')

        for cat in cats:
            self.categories[cat.get('id')] = cat.get('name')

        self.device_id_map = {}

        devs = j.get('devices')
        for dev in devs:
            dev['categoryName'] = self.categories.get(dev.get('category'))
            self.device_id_map[dev.get('id')] = dev

Response: Get basic device info from Vera.


Instruction:
Write a Python 3 script to
search the list of connected devices by name.

Response:
def get_device_by_name(self, device_name):
        """Search the list of connected devices by name.

        device_name param is the string name of the device
        """

        # Find the device for the vera device name we are interested in
        found_device = None
        for device in self.get_devices():
            if device.name == device_name:
              found_device = device
              # found the first (and should be only) one so we will finish
              break

        if found_device is None:
            logger.debug('Did not find device with {}'.format(device_name))

        return found_device


Instruction:
How would you code a function in Python 3 to
search the list of connected devices by ID.

Response:
def get_device_by_id(self, device_id):
        """Search the list of connected devices by ID.

        device_id param is the integer ID of the device
        """

        # Find the device for the vera device name we are interested in
        found_device = None
        for device in self.get_devices():
            if device.device_id == device_id:
              found_device = device
              # found the first (and should be only) one so we will finish
              break

        if found_device is None:
            logger.debug('Did not find device with {}'.format(device_id))

        return found_device


Instruction:
Create a Python 3 function to
get list of connected devices.

Response:
def get_devices(self, category_filter=''):
        """Get list of connected devices.

        category_filter param is an array of strings
        """
        # pylint: disable=too-many-branches

        # the Vera rest API is a bit rough so we need to make 2 calls to get
        # all the info e need
        self.get_simple_devices_info()

        j = self.data_request({'id': 'status', 'output_format': 'json'}).json()

        self.devices = []
        items = j.get('devices')

        for item in items:
            item['deviceInfo'] = self.device_id_map.get(item.get('id'))
            if item.get('deviceInfo'):
                device_category = item.get('deviceInfo').get('category')
                if device_category == CATEGORY_DIMMER:
                    device = VeraDimmer(item, self)
                elif ( device_category == CATEGORY_SWITCH or
                       device_category == CATEGORY_VERA_SIREN):
                    device = VeraSwitch(item, self)
                elif device_category == CATEGORY_THERMOSTAT:
                    device = VeraThermostat(item, self)
                elif device_category == CATEGORY_LOCK:
                    device = VeraLock(item, self)
                elif device_category == CATEGORY_CURTAIN:
                    device = VeraCurtain(item, self)
                elif device_category == CATEGORY_ARMABLE:
                    device = VeraBinarySensor(item, self)
                elif (device_category == CATEGORY_SENSOR or
                      device_category == CATEGORY_HUMIDITY_SENSOR or
                      device_category == CATEGORY_TEMPERATURE_SENSOR or
                      device_category == CATEGORY_LIGHT_SENSOR or
                      device_category == CATEGORY_POWER_METER or
                      device_category == CATEGORY_UV_SENSOR):
                    device = VeraSensor(item, self)
                elif (device_category == CATEGORY_SCENE_CONTROLLER or
                      device_category == CATEGORY_REMOTE):
                    device = VeraSceneController(item, self)
                elif device_category == CATEGORY_GARAGE_DOOR:
                    device = VeraGarageDoor(item, self)
                else:
                    device = VeraDevice(item, self)
                self.devices.append(device)
                if (device.is_armable and not (
                    device_category == CATEGORY_SWITCH or
                    device_category == CATEGORY_VERA_SIREN or
                    device_category == CATEGORY_CURTAIN or
                    device_category == CATEGORY_GARAGE_DOOR)):
                    self.devices.append(VeraArmableDevice(item, self))
            else:
                self.devices.append(VeraDevice(item, self))

        if not category_filter:
            return self.devices

        devices = []
        for device in self.devices:
            if (device.category_name is not None and
                    device.category_name != '' and
                    device.category_name in category_filter):
                devices.append(device)
        return devices


Instruction:
Can you generate the documentation for the following Python 3 function
def refresh_data(self):
        j = self.data_request({'id': 'sdata'}).json()

        self.temperature_units = j.get('temperature', 'C')
        self.model = j.get('model')
        self.version = j.get('version')
        self.serial_number = j.get('serial_number')

        categories = {}
        cats = j.get('categories')

        for cat in cats:
            categories[cat.get('id')] = cat.get('name')

        device_id_map = {}

        devs = j.get('devices')
        for dev in devs:
            dev['categoryName'] = categories.get(dev.get('category'))
            device_id_map[dev.get('id')] = dev

        return device_id_map

Response: Refresh data from Vera device.


Instruction:
Can you tell what is the following Python 3 function doing
def map_services(self):
        # the Vera rest API is a bit rough so we need to make 2 calls
        # to get all the info e need
        self.get_simple_devices_info()

        j = self.data_request({'id': 'status', 'output_format': 'json'}).json()

        service_map = {}

        items = j.get('devices')

        for item in items:
            service_map[item.get('id')] = item.get('states')

        self.device_services_map = service_map

Response: Get full Vera device service info.


Instruction:
Implement a function in Python 3 to
get data since last timestamp.

Response:
def get_changed_devices(self, timestamp):
        """Get data since last timestamp.

        This is done via a blocking call, pass NONE for initial state.
        """
        if timestamp is None:
            payload = {}
        else:
            payload = {
                'timeout': SUBSCRIPTION_WAIT,
                'minimumdelay': SUBSCRIPTION_MIN_WAIT
            }
            payload.update(timestamp)
        # double the timeout here so requests doesn't timeout before vera
        payload.update({
            'id': 'lu_sdata',
        })

        logger.debug("get_changed_devices() requesting payload %s", str(payload))
        r = self.data_request(payload, TIMEOUT*2)
        r.raise_for_status()

        # If the Vera disconnects before writing a full response (as lu_sdata
        # will do when interrupted by a Luup reload), the requests module will
        # happily return 200 with an empty string. So, test for empty response,
        # so we don't rely on the JSON parser to throw an exception.
        if r.text == "":
            raise PyveraError("Empty response from Vera")

        # Catch a wide swath of what the JSON parser might throw, within
        # reason. Unfortunately, some parsers don't specifically return
        # json.decode.JSONDecodeError, but so far most seem to derive what
        # they do throw from ValueError, so that's helpful.
        try:
            result = r.json()
        except ValueError as ex:
            raise PyveraError("JSON decode error: " + str(ex))

        if not ( type(result) is dict
                 and 'loadtime' in result and 'dataversion' in result ):
            raise PyveraError("Unexpected/garbled response from Vera")

        # At this point, all good. Update timestamp and return change data.
        device_data = result.get('devices')
        timestamp = {
            'loadtime': result.get('loadtime'),
            'dataversion': result.get('dataversion')
        }
        return [device_data, timestamp]


Instruction:
Can you generate the documentation for the following Python 3 function
def set_service_value(self, service_id, set_name, parameter_name, value):
        payload = {
            'id': 'lu_action',
            'action': 'Set' + set_name,
            'serviceId': service_id,
            parameter_name: value
        }
        result = self.vera_request(**payload)
        logger.debug("set_service_value: "
                  "result of vera_request with payload %s: %s",
                  payload, result.text)

Response: Set a variable on the vera device.


Instruction:
Create a Python 3 function to
call a Vera service.

Response:
def call_service(self, service_id, action):
        """Call a Vera service.

        This will call the Vera api to change device state.
        """
        result = self.vera_request(id='action', serviceId=service_id,
                                   action=action)
        logger.debug("call_service: "
                  "result of vera_request with id %s: %s", service_id,
                  result.text)
        return result


Instruction:
Given the following Python 3 function, write the documentation
def set_cache_value(self, name, value):
        dev_info = self.json_state.get('deviceInfo')
        if dev_info.get(name.lower()) is None:
            logger.error("Could not set %s for %s (key does not exist).",
                      name, self.name)
            logger.error("- dictionary %s", dev_info)
            return
        dev_info[name.lower()] = str(value)

Response: Set a variable in the local state dictionary.


Instruction:
Write a Python 3 script to
set a variable in the local complex state dictionary.

Response:
def set_cache_complex_value(self, name, value):
        """Set a variable in the local complex state dictionary.

        This does not change the physical device. Useful if you want the
        device state to refect a new value which has not yet updated from
        Vera.
        """
        for item in self.json_state.get('states'):
            if item.get('variable') == name:
                item['value'] = str(value)